@copilotkit/runtime 1.4.8-coagents-v0-3.1 → 1.4.8-next.1

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 (77) hide show
  1. package/CHANGELOG.md +5 -4
  2. package/__snapshots__/schema/schema.graphql +10 -7
  3. package/dist/{chunk-FVYNRYIB.mjs → chunk-5KJYPVQJ.mjs} +307 -423
  4. package/dist/chunk-5KJYPVQJ.mjs.map +1 -0
  5. package/dist/{chunk-RFF5IIZJ.mjs → chunk-B74M7FXG.mjs} +2 -3
  6. package/dist/chunk-B74M7FXG.mjs.map +1 -0
  7. package/dist/{chunk-BACNNHHI.mjs → chunk-CGGI46KC.mjs} +2 -2
  8. package/dist/{chunk-YFG3Q3YH.mjs → chunk-EU52BTKR.mjs} +2 -2
  9. package/dist/{chunk-MQJNZYAH.mjs → chunk-KO4QCMY4.mjs} +2 -2
  10. package/dist/{chunk-2PK2SFRB.mjs → chunk-W7GP2EOT.mjs} +106 -221
  11. package/dist/chunk-W7GP2EOT.mjs.map +1 -0
  12. package/dist/{copilot-runtime-b15b683d.d.ts → copilot-runtime-1c5bf72b.d.ts} +2 -2
  13. package/dist/graphql/types/converted/index.d.ts +1 -1
  14. package/dist/graphql/types/converted/index.js +1 -2
  15. package/dist/graphql/types/converted/index.js.map +1 -1
  16. package/dist/graphql/types/converted/index.mjs +1 -1
  17. package/dist/{groq-adapter-50aa9621.d.ts → groq-adapter-b6a40422.d.ts} +1 -1
  18. package/dist/{index-ff3fbc33.d.ts → index-10b1c870.d.ts} +8 -7
  19. package/dist/index.d.ts +5 -5
  20. package/dist/index.js +515 -745
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +10 -6
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/{langserve-8ec29cba.d.ts → langserve-6245df39.d.ts} +14 -52
  25. package/dist/lib/index.d.ts +4 -4
  26. package/dist/lib/index.js +442 -706
  27. package/dist/lib/index.js.map +1 -1
  28. package/dist/lib/index.mjs +6 -6
  29. package/dist/lib/integrations/index.d.ts +4 -4
  30. package/dist/lib/integrations/index.js +37 -71
  31. package/dist/lib/integrations/index.js.map +1 -1
  32. package/dist/lib/integrations/index.mjs +6 -6
  33. package/dist/lib/integrations/nest/index.d.ts +3 -3
  34. package/dist/lib/integrations/nest/index.js +37 -71
  35. package/dist/lib/integrations/nest/index.js.map +1 -1
  36. package/dist/lib/integrations/nest/index.mjs +4 -4
  37. package/dist/lib/integrations/node-express/index.d.ts +3 -3
  38. package/dist/lib/integrations/node-express/index.js +37 -71
  39. package/dist/lib/integrations/node-express/index.js.map +1 -1
  40. package/dist/lib/integrations/node-express/index.mjs +4 -4
  41. package/dist/lib/integrations/node-http/index.d.ts +3 -3
  42. package/dist/lib/integrations/node-http/index.js +37 -71
  43. package/dist/lib/integrations/node-http/index.js.map +1 -1
  44. package/dist/lib/integrations/node-http/index.mjs +3 -3
  45. package/dist/service-adapters/index.d.ts +36 -5
  46. package/dist/service-adapters/index.js +106 -219
  47. package/dist/service-adapters/index.js.map +1 -1
  48. package/dist/service-adapters/index.mjs +5 -1
  49. package/package.json +2 -2
  50. package/src/agents/langgraph/event-source.ts +148 -140
  51. package/src/agents/langgraph/events.ts +1 -1
  52. package/src/graphql/inputs/forwarded-parameters.input.ts +3 -0
  53. package/src/graphql/inputs/message.input.ts +3 -15
  54. package/src/graphql/resolvers/copilot.resolver.ts +6 -32
  55. package/src/graphql/types/converted/index.ts +3 -4
  56. package/src/graphql/types/copilot-response.type.ts +3 -12
  57. package/src/graphql/types/enums.ts +11 -0
  58. package/src/lib/runtime/remote-action-constructors.ts +62 -60
  59. package/src/lib/runtime/remote-actions.ts +0 -1
  60. package/src/lib/runtime/remote-lg-action.ts +140 -161
  61. package/src/service-adapters/anthropic/anthropic-adapter.ts +6 -16
  62. package/src/service-adapters/conversion.ts +1 -2
  63. package/src/service-adapters/events.ts +52 -111
  64. package/src/service-adapters/experimental/empty/empty-adapter.ts +33 -0
  65. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +3 -7
  66. package/src/service-adapters/groq/groq-adapter.ts +8 -23
  67. package/src/service-adapters/index.ts +7 -1
  68. package/src/service-adapters/langchain/utils.ts +31 -49
  69. package/src/service-adapters/openai/openai-adapter.ts +9 -22
  70. package/src/service-adapters/openai/openai-assistant-adapter.ts +8 -22
  71. package/src/service-adapters/unify/unify-adapter.ts +11 -28
  72. package/dist/chunk-2PK2SFRB.mjs.map +0 -1
  73. package/dist/chunk-FVYNRYIB.mjs.map +0 -1
  74. package/dist/chunk-RFF5IIZJ.mjs.map +0 -1
  75. /package/dist/{chunk-BACNNHHI.mjs.map → chunk-CGGI46KC.mjs.map} +0 -0
  76. /package/dist/{chunk-YFG3Q3YH.mjs.map → chunk-EU52BTKR.mjs.map} +0 -0
  77. /package/dist/{chunk-MQJNZYAH.mjs.map → chunk-KO4QCMY4.mjs.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  RemoteChain,
3
3
  streamLangChainResponse
4
- } from "./chunk-2PK2SFRB.mjs";
4
+ } from "./chunk-W7GP2EOT.mjs";
5
5
  import {
6
6
  GuardrailsValidationFailureResponse,
7
7
  MessageStreamInterruptedResponse,
@@ -14,7 +14,7 @@ import {
14
14
  AgentStateMessage,
15
15
  ResultMessage,
16
16
  TextMessage
17
- } from "./chunk-RFF5IIZJ.mjs";
17
+ } from "./chunk-B74M7FXG.mjs";
18
18
  import {
19
19
  BaseMessageInput
20
20
  } from "./chunk-D2WLFQS6.mjs";
@@ -37,7 +37,7 @@ var require_package = __commonJS({
37
37
  publishConfig: {
38
38
  access: "public"
39
39
  },
40
- version: "1.4.8-coagents-v0-3.1",
40
+ version: "1.4.8-next.1",
41
41
  sideEffects: false,
42
42
  main: "./dist/index.js",
43
43
  module: "./dist/index.mjs",
@@ -122,7 +122,7 @@ import { buildSchemaSync } from "type-graphql";
122
122
 
123
123
  // src/graphql/resolvers/copilot.resolver.ts
124
124
  import { Arg, Ctx, Mutation, Query, Resolver } from "type-graphql";
125
- import { ReplaySubject as ReplaySubject3, Subject, filter, finalize, firstValueFrom as firstValueFrom2, shareReplay, skipWhile, take, takeWhile, tap } from "rxjs";
125
+ import { ReplaySubject as ReplaySubject3, Subject, finalize, firstValueFrom as firstValueFrom2, shareReplay, skipWhile, take, takeWhile, tap } from "rxjs";
126
126
 
127
127
  // src/graphql/inputs/generate-copilot-response.input.ts
128
128
  import { Field as Field9, InputType as InputType9 } from "type-graphql";
@@ -139,6 +139,12 @@ var MessageRole;
139
139
  MessageRole2["system"] = "system";
140
140
  MessageRole2["tool"] = "tool";
141
141
  })(MessageRole || (MessageRole = {}));
142
+ var ActionExecutionScope;
143
+ (function(ActionExecutionScope2) {
144
+ ActionExecutionScope2["server"] = "server";
145
+ ActionExecutionScope2["client"] = "client";
146
+ ActionExecutionScope2["passThrough"] = "passThrough";
147
+ })(ActionExecutionScope || (ActionExecutionScope = {}));
142
148
  var CopilotRequestType;
143
149
  (function(CopilotRequestType2) {
144
150
  CopilotRequestType2["Chat"] = "Chat";
@@ -157,6 +163,10 @@ registerEnumType(MessageRole, {
157
163
  name: "MessageRole",
158
164
  description: "The role of the message"
159
165
  });
166
+ registerEnumType(ActionExecutionScope, {
167
+ name: "ActionExecutionScope",
168
+ description: "The scope of the action"
169
+ });
160
170
  registerEnumType(CopilotRequestType, {
161
171
  name: "CopilotRequestType",
162
172
  description: "The type of Copilot request"
@@ -219,7 +229,6 @@ MessageInput = _ts_decorate([
219
229
  ], MessageInput);
220
230
  var TextMessageInput = class {
221
231
  content;
222
- parentMessageId;
223
232
  role;
224
233
  };
225
234
  __name(TextMessageInput, "TextMessageInput");
@@ -227,12 +236,6 @@ _ts_decorate([
227
236
  Field(() => String),
228
237
  _ts_metadata("design:type", String)
229
238
  ], TextMessageInput.prototype, "content", void 0);
230
- _ts_decorate([
231
- Field(() => String, {
232
- nullable: true
233
- }),
234
- _ts_metadata("design:type", String)
235
- ], TextMessageInput.prototype, "parentMessageId", void 0);
236
239
  _ts_decorate([
237
240
  Field(() => MessageRole),
238
241
  _ts_metadata("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
@@ -243,7 +246,6 @@ TextMessageInput = _ts_decorate([
243
246
  var ActionExecutionMessageInput = class {
244
247
  name;
245
248
  arguments;
246
- parentMessageId;
247
249
  scope;
248
250
  };
249
251
  __name(ActionExecutionMessageInput, "ActionExecutionMessageInput");
@@ -256,17 +258,8 @@ _ts_decorate([
256
258
  _ts_metadata("design:type", String)
257
259
  ], ActionExecutionMessageInput.prototype, "arguments", void 0);
258
260
  _ts_decorate([
259
- Field(() => String, {
260
- nullable: true
261
- }),
262
- _ts_metadata("design:type", String)
263
- ], ActionExecutionMessageInput.prototype, "parentMessageId", void 0);
264
- _ts_decorate([
265
- Field(() => String, {
266
- nullable: true,
267
- deprecationReason: "This field will be removed in a future version"
268
- }),
269
- _ts_metadata("design:type", typeof String === "undefined" ? Object : String)
261
+ Field(() => ActionExecutionScope),
262
+ _ts_metadata("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
270
263
  ], ActionExecutionMessageInput.prototype, "scope", void 0);
271
264
  ActionExecutionMessageInput = _ts_decorate([
272
265
  InputType()
@@ -274,7 +267,6 @@ ActionExecutionMessageInput = _ts_decorate([
274
267
  var ResultMessageInput = class {
275
268
  actionExecutionId;
276
269
  actionName;
277
- parentMessageId;
278
270
  result;
279
271
  };
280
272
  __name(ResultMessageInput, "ResultMessageInput");
@@ -286,12 +278,6 @@ _ts_decorate([
286
278
  Field(() => String),
287
279
  _ts_metadata("design:type", String)
288
280
  ], ResultMessageInput.prototype, "actionName", void 0);
289
- _ts_decorate([
290
- Field(() => String, {
291
- nullable: true
292
- }),
293
- _ts_metadata("design:type", String)
294
- ], ResultMessageInput.prototype, "parentMessageId", void 0);
295
281
  _ts_decorate([
296
282
  Field(() => String),
297
283
  _ts_metadata("design:type", String)
@@ -555,6 +541,7 @@ var ForwardedParametersInput = class {
555
541
  stop;
556
542
  toolChoice;
557
543
  toolChoiceFunctionName;
544
+ temperature;
558
545
  };
559
546
  __name(ForwardedParametersInput, "ForwardedParametersInput");
560
547
  _ts_decorate6([
@@ -589,6 +576,12 @@ _ts_decorate6([
589
576
  }),
590
577
  _ts_metadata6("design:type", String)
591
578
  ], ForwardedParametersInput.prototype, "toolChoiceFunctionName", void 0);
579
+ _ts_decorate6([
580
+ Field6(() => Number, {
581
+ nullable: true
582
+ }),
583
+ _ts_metadata6("design:type", Number)
584
+ ], ForwardedParametersInput.prototype, "temperature", void 0);
592
585
  ForwardedParametersInput = _ts_decorate6([
593
586
  InputType6()
594
587
  ], ForwardedParametersInput);
@@ -907,7 +900,6 @@ BaseMessageOutput = _ts_decorate11([
907
900
  var TextMessageOutput = class {
908
901
  role;
909
902
  content;
910
- parentMessageId;
911
903
  };
912
904
  __name(TextMessageOutput, "TextMessageOutput");
913
905
  _ts_decorate11([
@@ -920,12 +912,6 @@ _ts_decorate11([
920
912
  ]),
921
913
  _ts_metadata11("design:type", Array)
922
914
  ], TextMessageOutput.prototype, "content", void 0);
923
- _ts_decorate11([
924
- Field11(() => String, {
925
- nullable: true
926
- }),
927
- _ts_metadata11("design:type", String)
928
- ], TextMessageOutput.prototype, "parentMessageId", void 0);
929
915
  TextMessageOutput = _ts_decorate11([
930
916
  ObjectType2({
931
917
  implements: BaseMessageOutput
@@ -935,7 +921,6 @@ var ActionExecutionMessageOutput = class {
935
921
  name;
936
922
  scope;
937
923
  arguments;
938
- parentMessageId;
939
924
  };
940
925
  __name(ActionExecutionMessageOutput, "ActionExecutionMessageOutput");
941
926
  _ts_decorate11([
@@ -943,11 +928,8 @@ _ts_decorate11([
943
928
  _ts_metadata11("design:type", String)
944
929
  ], ActionExecutionMessageOutput.prototype, "name", void 0);
945
930
  _ts_decorate11([
946
- Field11(() => String, {
947
- nullable: true,
948
- deprecationReason: "This field will be removed in a future version"
949
- }),
950
- _ts_metadata11("design:type", String)
931
+ Field11(() => ActionExecutionScope),
932
+ _ts_metadata11("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
951
933
  ], ActionExecutionMessageOutput.prototype, "scope", void 0);
952
934
  _ts_decorate11([
953
935
  Field11(() => [
@@ -955,12 +937,6 @@ _ts_decorate11([
955
937
  ]),
956
938
  _ts_metadata11("design:type", Array)
957
939
  ], ActionExecutionMessageOutput.prototype, "arguments", void 0);
958
- _ts_decorate11([
959
- Field11(() => String, {
960
- nullable: true
961
- }),
962
- _ts_metadata11("design:type", String)
963
- ], ActionExecutionMessageOutput.prototype, "parentMessageId", void 0);
964
940
  ActionExecutionMessageOutput = _ts_decorate11([
965
941
  ObjectType2({
966
942
  implements: BaseMessageOutput
@@ -1073,7 +1049,7 @@ import { Repeater } from "graphql-yoga";
1073
1049
 
1074
1050
  // src/service-adapters/events.ts
1075
1051
  import { randomId as randomId3 } from "@copilotkit/shared";
1076
- import { of, concat, scan as scan2, concatMap, ReplaySubject as ReplaySubject2, firstValueFrom, from as from2 } from "rxjs";
1052
+ import { of, concat, map, scan as scan2, concatMap, ReplaySubject as ReplaySubject2, firstValueFrom, from as from2 } from "rxjs";
1077
1053
 
1078
1054
  // src/lib/telemetry-client.ts
1079
1055
  import { TelemetryClient } from "@copilotkit/shared";
@@ -1121,167 +1097,163 @@ var RemoteLangGraphEventSource = class {
1121
1097
  }
1122
1098
  return shouldEmitToolCalls === toolCallName;
1123
1099
  }
1124
- getCurrentContent(event) {
1125
- var _a, _b, _c, _d, _e;
1126
- const content = ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.content) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.content);
1127
- if (!content) {
1128
- const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
1129
- for (const chunk of toolCallChunks) {
1130
- if (chunk.args) {
1131
- return chunk.args;
1132
- }
1133
- }
1134
- }
1135
- if (typeof content === "string") {
1136
- return content;
1137
- } else if (Array.isArray(content) && content.length > 0) {
1138
- return content[0].text;
1139
- }
1140
- return null;
1141
- }
1142
- getCurrentMessageId(event) {
1143
- var _a, _b, _c, _d, _e;
1144
- return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.id) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.id);
1145
- }
1146
- getCurrentToolCallChunks(event) {
1147
- var _a, _b, _c, _d, _e;
1148
- return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.tool_call_chunks);
1149
- }
1150
- getResponseMetadata(event) {
1151
- var _a, _b, _c, _d, _e;
1152
- return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.response_metadata) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.response_metadata);
1153
- }
1154
1100
  processLangGraphEvents() {
1155
1101
  let lastEventWithState = null;
1156
1102
  return this.eventStream$.pipe(scan((acc, event) => {
1103
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1157
1104
  if (event.event === LangGraphEventTypes.OnChatModelStream) {
1158
- const prevMessageId = acc.lastMessageId;
1159
- acc.currentContent = this.getCurrentContent(event);
1160
- acc.lastMessageId = this.getCurrentMessageId(event) ?? acc.lastMessageId;
1161
- const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
1162
- const responseMetadata = this.getResponseMetadata(event);
1163
- acc.isToolCallStart = toolCallChunks.some((chunk) => chunk.name && chunk.id);
1164
- acc.isMessageStart = prevMessageId !== acc.lastMessageId && !acc.isToolCallStart;
1165
- acc.isToolCall = toolCallChunks && toolCallChunks.length > 0;
1166
- acc.isToolCallEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls";
1167
- acc.isMessageEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop";
1168
- ({ name: acc.lastToolCallName, id: acc.lastToolCallId } = toolCallChunks.find((chunk) => chunk.name && chunk.id) ?? {
1169
- name: acc.lastToolCallName,
1170
- id: acc.lastToolCallId
1171
- });
1105
+ const content = ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.content) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.content);
1106
+ if (typeof content === "string") {
1107
+ acc.content = content;
1108
+ } else if (Array.isArray(content) && content.length > 0) {
1109
+ acc.content = content[0].text;
1110
+ } else {
1111
+ acc.content = null;
1112
+ }
1113
+ const toolCallChunks = (
1114
+ // @ts-expect-error -- LangGraph Platform implementation stores data outside of kwargs
1115
+ ((_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)
1116
+ );
1117
+ 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);
1118
+ if (toolCallChunks && toolCallChunks.length > 0) {
1119
+ acc.prevToolCallMessageId = acc.toolCallMessageId;
1120
+ acc.toolCallMessageId = toolCallMessageId;
1121
+ if ((_p = toolCallChunks[0]) == null ? void 0 : _p.name) {
1122
+ acc.toolCallName = toolCallChunks[0].name;
1123
+ }
1124
+ if ((_q = toolCallChunks[0]) == null ? void 0 : _q.id) {
1125
+ acc.toolCallId = toolCallChunks[0].id;
1126
+ }
1127
+ acc.prevMessageId = acc.messageId;
1128
+ acc.messageId = toolCallMessageId;
1129
+ } else if (acc.content && acc.content != "") {
1130
+ acc.prevMessageId = acc.messageId;
1131
+ acc.messageId = toolCallMessageId;
1132
+ } else {
1133
+ acc.prevToolCallMessageId = acc.toolCallMessageId;
1134
+ acc.prevMessageId = acc.messageId;
1135
+ }
1136
+ } else {
1137
+ acc.prevToolCallMessageId = acc.toolCallMessageId;
1138
+ acc.toolCallMessageId = null;
1139
+ acc.prevMessageId = acc.messageId;
1140
+ acc.messageId = null;
1141
+ acc.toolCallName = null;
1172
1142
  }
1173
1143
  acc.event = event;
1174
1144
  lastEventWithState = acc;
1175
1145
  return acc;
1176
1146
  }, {
1177
1147
  event: null,
1178
- isMessageStart: false,
1179
- isMessageEnd: false,
1180
- isToolCallStart: false,
1181
- isToolCallEnd: false,
1182
- isToolCall: false,
1183
- lastMessageId: null,
1184
- lastToolCallId: null,
1185
- lastToolCallName: null,
1186
- currentContent: null
1187
- }), mergeMap((acc) => {
1148
+ toolCallId: null,
1149
+ toolCallMessageId: null,
1150
+ prevToolCallMessageId: null,
1151
+ messageId: null,
1152
+ toolCallName: null,
1153
+ prevMessageId: null,
1154
+ content: null
1155
+ }), mergeMap((eventWithState) => {
1156
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1188
1157
  const events = [];
1189
1158
  let shouldEmitMessages = true;
1190
- let shouldEmitToolCalls = true;
1191
- if (acc.event.event == LangGraphEventTypes.OnChatModelStream) {
1192
- if ("copilotkit:emit-tool-calls" in (acc.event.metadata || {})) {
1193
- shouldEmitToolCalls = acc.event.metadata["copilotkit:emit-tool-calls"];
1159
+ let shouldEmitToolCalls = false;
1160
+ if (eventWithState.event.event == LangGraphEventTypes.OnChatModelStream) {
1161
+ if ("copilotkit:emit-tool-calls" in (eventWithState.event.metadata || {})) {
1162
+ shouldEmitToolCalls = eventWithState.event.metadata["copilotkit:emit-tool-calls"];
1194
1163
  }
1195
- if ("copilotkit:emit-messages" in (acc.event.metadata || {})) {
1196
- shouldEmitMessages = acc.event.metadata["copilotkit:emit-messages"];
1164
+ if ("copilotkit:emit-messages" in (eventWithState.event.metadata || {})) {
1165
+ shouldEmitMessages = eventWithState.event.metadata["copilotkit:emit-messages"];
1197
1166
  }
1198
1167
  }
1199
- const responseMetadata = this.getResponseMetadata(acc.event);
1200
- if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls" && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1168
+ if (eventWithState.prevToolCallMessageId !== null && eventWithState.prevToolCallMessageId !== eventWithState.toolCallMessageId && this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1201
1169
  events.push({
1202
- type: RuntimeEventTypes.ActionExecutionEnd,
1203
- actionExecutionId: acc.lastToolCallId
1170
+ type: RuntimeEventTypes.ActionExecutionEnd
1204
1171
  });
1205
1172
  }
1206
- if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop" && shouldEmitMessages) {
1173
+ if (eventWithState.prevMessageId !== null && eventWithState.prevMessageId !== eventWithState.messageId && shouldEmitMessages) {
1207
1174
  events.push({
1208
- type: RuntimeEventTypes.TextMessageEnd,
1209
- messageId: acc.lastMessageId
1175
+ type: RuntimeEventTypes.TextMessageEnd
1210
1176
  });
1211
1177
  }
1212
- switch (acc.event.event) {
1178
+ switch (eventWithState.event.event) {
1213
1179
  case LangGraphEventTypes.OnCustomEvent:
1214
- if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1180
+ if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1215
1181
  events.push({
1216
1182
  type: RuntimeEventTypes.TextMessageStart,
1217
- messageId: acc.event.data.message_id
1183
+ messageId: eventWithState.event.data.message_id
1218
1184
  });
1219
1185
  events.push({
1220
1186
  type: RuntimeEventTypes.TextMessageContent,
1221
- messageId: acc.event.data.message_id,
1222
- content: acc.event.data.message
1187
+ content: eventWithState.event.data.message
1223
1188
  });
1224
1189
  events.push({
1225
- type: RuntimeEventTypes.TextMessageEnd,
1226
- messageId: acc.event.data.message_id
1190
+ type: RuntimeEventTypes.TextMessageEnd
1227
1191
  });
1228
- } else if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1192
+ } else if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1229
1193
  events.push({
1230
1194
  type: RuntimeEventTypes.ActionExecutionStart,
1231
- actionExecutionId: acc.event.data.id,
1232
- actionName: acc.event.data.name,
1233
- parentMessageId: acc.event.data.id
1195
+ actionExecutionId: eventWithState.event.data.id,
1196
+ actionName: eventWithState.event.data.name
1234
1197
  });
1235
1198
  events.push({
1236
1199
  type: RuntimeEventTypes.ActionExecutionArgs,
1237
- actionExecutionId: acc.event.data.id,
1238
- args: JSON.stringify(acc.event.data.args)
1200
+ args: JSON.stringify(eventWithState.event.data.args)
1239
1201
  });
1240
1202
  events.push({
1241
- type: RuntimeEventTypes.ActionExecutionEnd,
1242
- actionExecutionId: acc.event.data.id
1203
+ type: RuntimeEventTypes.ActionExecutionEnd
1243
1204
  });
1244
1205
  }
1245
1206
  break;
1246
1207
  case LangGraphEventTypes.OnCopilotKitStateSync:
1247
1208
  events.push({
1248
1209
  type: RuntimeEventTypes.AgentStateMessage,
1249
- threadId: acc.event.thread_id,
1250
- role: acc.event.role,
1251
- agentName: acc.event.agent_name,
1252
- nodeName: acc.event.node_name,
1253
- runId: acc.event.run_id,
1254
- active: acc.event.active,
1255
- state: JSON.stringify(acc.event.state),
1256
- running: acc.event.running
1210
+ threadId: eventWithState.event.thread_id,
1211
+ role: eventWithState.event.role,
1212
+ agentName: eventWithState.event.agent_name,
1213
+ nodeName: eventWithState.event.node_name,
1214
+ runId: eventWithState.event.run_id,
1215
+ active: eventWithState.event.active,
1216
+ state: JSON.stringify(eventWithState.event.state),
1217
+ running: eventWithState.event.running
1257
1218
  });
1258
1219
  break;
1220
+ case LangGraphEventTypes.OnToolEnd:
1221
+ break;
1259
1222
  case LangGraphEventTypes.OnChatModelStream:
1260
- if (acc.isToolCallStart && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1261
- events.push({
1262
- type: RuntimeEventTypes.ActionExecutionStart,
1263
- actionExecutionId: acc.lastToolCallId,
1264
- actionName: acc.lastToolCallName,
1265
- parentMessageId: acc.lastMessageId
1266
- });
1267
- } else if (acc.isMessageStart && shouldEmitMessages) {
1268
- events.push({
1269
- type: RuntimeEventTypes.TextMessageStart,
1270
- messageId: acc.lastMessageId
1271
- });
1223
+ if (eventWithState.toolCallMessageId !== null && eventWithState.prevToolCallMessageId !== eventWithState.toolCallMessageId) {
1224
+ if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1225
+ events.push({
1226
+ type: RuntimeEventTypes.ActionExecutionStart,
1227
+ actionExecutionId: eventWithState.toolCallMessageId,
1228
+ actionName: eventWithState.toolCallName,
1229
+ scope: "client"
1230
+ });
1231
+ }
1232
+ } else if (eventWithState.messageId !== null && eventWithState.prevMessageId !== eventWithState.messageId) {
1233
+ if (shouldEmitMessages) {
1234
+ events.push({
1235
+ type: RuntimeEventTypes.TextMessageStart,
1236
+ messageId: eventWithState.messageId
1237
+ });
1238
+ }
1272
1239
  }
1273
- if (acc.isToolCall && acc.currentContent && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1274
- events.push({
1275
- type: RuntimeEventTypes.ActionExecutionArgs,
1276
- actionExecutionId: acc.lastToolCallId,
1277
- args: acc.currentContent
1278
- });
1279
- } else if (!acc.isToolCall && acc.currentContent && shouldEmitMessages) {
1280
- events.push({
1281
- type: RuntimeEventTypes.TextMessageContent,
1282
- messageId: acc.lastMessageId,
1283
- content: acc.currentContent
1284
- });
1240
+ 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
1241
+ ((_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);
1242
+ const content = eventWithState.content;
1243
+ if (args) {
1244
+ if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1245
+ events.push({
1246
+ type: RuntimeEventTypes.ActionExecutionArgs,
1247
+ args
1248
+ });
1249
+ }
1250
+ } else if (eventWithState.messageId !== null && content) {
1251
+ if (shouldEmitMessages) {
1252
+ events.push({
1253
+ type: RuntimeEventTypes.TextMessageContent,
1254
+ content
1255
+ });
1256
+ }
1285
1257
  }
1286
1258
  break;
1287
1259
  }
@@ -1289,16 +1261,14 @@ var RemoteLangGraphEventSource = class {
1289
1261
  }), catchError((error) => {
1290
1262
  console.error(error);
1291
1263
  const events = [];
1292
- if ((lastEventWithState == null ? void 0 : lastEventWithState.lastMessageId) && !lastEventWithState.isToolCall) {
1264
+ if (lastEventWithState == null ? void 0 : lastEventWithState.messageId) {
1293
1265
  events.push({
1294
- type: RuntimeEventTypes.TextMessageEnd,
1295
- messageId: lastEventWithState.lastMessageId
1266
+ type: RuntimeEventTypes.TextMessageEnd
1296
1267
  });
1297
1268
  }
1298
- if (lastEventWithState == null ? void 0 : lastEventWithState.lastToolCallId) {
1269
+ if (lastEventWithState == null ? void 0 : lastEventWithState.toolCallMessageId) {
1299
1270
  events.push({
1300
- type: RuntimeEventTypes.ActionExecutionEnd,
1301
- actionExecutionId: lastEventWithState.lastToolCallId
1271
+ type: RuntimeEventTypes.ActionExecutionEnd
1302
1272
  });
1303
1273
  }
1304
1274
  const messageId = randomId();
@@ -1308,12 +1278,10 @@ var RemoteLangGraphEventSource = class {
1308
1278
  });
1309
1279
  events.push({
1310
1280
  type: RuntimeEventTypes.TextMessageContent,
1311
- messageId,
1312
1281
  content: "\u274C An error occurred. Please try again."
1313
1282
  });
1314
1283
  events.push({
1315
- type: RuntimeEventTypes.TextMessageEnd,
1316
- messageId
1284
+ type: RuntimeEventTypes.TextMessageEnd
1317
1285
  });
1318
1286
  return events;
1319
1287
  }));
@@ -1371,7 +1339,7 @@ async function streamEvents(controller, args) {
1371
1339
  const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
1372
1340
  let formattedMessages = [];
1373
1341
  try {
1374
- formattedMessages = copilotkitMessagesToLangChain(messages);
1342
+ formattedMessages = formatMessages(messages);
1375
1343
  } catch (e) {
1376
1344
  logger2.error(e, `Error event thrown: ${e.message}`);
1377
1345
  }
@@ -1524,8 +1492,7 @@ async function streamEvents(controller, args) {
1524
1492
  nodeName: isEndNode ? "__end__" : nodeName,
1525
1493
  state: state.values,
1526
1494
  running: !shouldExit,
1527
- active: false,
1528
- includeMessages: true
1495
+ active: false
1529
1496
  }));
1530
1497
  return Promise.resolve();
1531
1498
  } catch (e) {
@@ -1538,20 +1505,13 @@ async function streamEvents(controller, args) {
1538
1505
  }
1539
1506
  }
1540
1507
  __name(streamEvents, "streamEvents");
1541
- function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active, includeMessages = false }) {
1542
- if (!includeMessages) {
1543
- state = Object.keys(state).reduce((acc, key) => {
1544
- if (key !== "messages") {
1545
- acc[key] = state[key];
1546
- }
1547
- return acc;
1548
- }, {});
1549
- } else {
1550
- state = {
1551
- ...state,
1552
- messages: langchainMessagesToCopilotKit(state.messages || [])
1553
- };
1554
- }
1508
+ function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active }) {
1509
+ const stateWithoutMessages = Object.keys(state).reduce((acc, key) => {
1510
+ if (key !== "messages") {
1511
+ acc[key] = state[key];
1512
+ }
1513
+ return acc;
1514
+ }, {});
1555
1515
  return JSON.stringify({
1556
1516
  event: LangGraphEventTypes.OnCopilotKitStateSync,
1557
1517
  thread_id: threadId,
@@ -1559,7 +1519,7 @@ function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, runnin
1559
1519
  agent_name: agentName,
1560
1520
  node_name: nodeName,
1561
1521
  active,
1562
- state,
1522
+ state: stateWithoutMessages,
1563
1523
  running,
1564
1524
  role: "assistant"
1565
1525
  }) + "\n";
@@ -1635,159 +1595,134 @@ function langGraphDefaultMergeState(state, messages, actions, agentName) {
1635
1595
  if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
1636
1596
  messages = messages.slice(1);
1637
1597
  }
1638
- const existingMessages = state.messages || [];
1639
- const existingMessageIds = new Set(existingMessages.map((message) => message.id));
1640
- const newMessages = messages.filter((message) => !existingMessageIds.has(message.id));
1641
- return {
1642
- ...state,
1643
- messages: newMessages,
1644
- copilotkit: {
1645
- actions
1646
- }
1647
- };
1648
- }
1649
- __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1650
- function langchainMessagesToCopilotKit(messages) {
1651
- const result = [];
1652
- const tool_call_names = {};
1653
- for (const message of messages) {
1654
- if (message.type === "ai") {
1655
- for (const tool_call of message.tool_calls) {
1656
- tool_call_names[tool_call.id] = tool_call.name;
1657
- }
1598
+ const mergedMessages = state.messages || [];
1599
+ const existingMessageIds = new Set(mergedMessages.map((message) => message.id));
1600
+ const existingToolCallResults = /* @__PURE__ */ new Set();
1601
+ for (const message of mergedMessages) {
1602
+ if ("tool_call_id" in message) {
1603
+ existingToolCallResults.add(message.tool_call_id);
1658
1604
  }
1659
1605
  }
1660
1606
  for (const message of messages) {
1661
- let content = message.content;
1662
- if (content instanceof Array) {
1663
- content = content[0];
1607
+ if ("tool_calls" in message && message.tool_calls.length > 0 && message.tool_calls[0].name === agentName) {
1608
+ continue;
1664
1609
  }
1665
- if (content instanceof Object) {
1666
- content = content.text;
1610
+ if ("name" in message && message.name === agentName) {
1611
+ continue;
1667
1612
  }
1668
- if (message.type === "human") {
1669
- result.push({
1670
- role: "user",
1671
- content,
1672
- id: message.id
1673
- });
1674
- } else if (message.type === "system") {
1675
- result.push({
1676
- role: "system",
1677
- content,
1678
- id: message.id
1679
- });
1680
- } else if (message.type === "ai") {
1681
- if (message.tool_calls && message.tool_calls.length > 0) {
1682
- for (const tool_call of message.tool_calls) {
1683
- result.push({
1684
- id: tool_call.id,
1685
- name: tool_call.name,
1686
- arguments: tool_call.args,
1687
- parentMessageId: message.id
1688
- });
1613
+ if (!existingMessageIds.has(message.id)) {
1614
+ if ("tool_call_id" in message && existingToolCallResults.has(message.tool_call_id)) {
1615
+ console.warn("Warning: Duplicate tool call result, skipping:", message.tool_call_id);
1616
+ continue;
1617
+ }
1618
+ mergedMessages.push(message);
1619
+ } else {
1620
+ for (let i = 0; i < mergedMessages.length; i++) {
1621
+ if (mergedMessages[i].id === message.id && message.role === "assistant") {
1622
+ if (("tool_calls" in mergedMessages[i] || "additional_kwargs" in mergedMessages[i]) && mergedMessages[i].content) {
1623
+ message.tool_calls = mergedMessages[i]["tool_calls"];
1624
+ message.additional_kwargs = mergedMessages[i].additional_kwargs;
1625
+ }
1626
+ mergedMessages[i] = message;
1689
1627
  }
1690
- } else {
1691
- result.push({
1692
- role: "assistant",
1693
- content,
1694
- id: message.id,
1695
- parentMessageId: message.id
1696
- });
1697
1628
  }
1698
- } else if (message.type === "tool") {
1699
- const actionName = tool_call_names[message.tool_call_id] || message.name || "";
1700
- result.push({
1701
- actionExecutionId: message.tool_call_id,
1702
- actionName,
1703
- result: content,
1704
- id: message.id
1705
- });
1706
1629
  }
1707
1630
  }
1708
- const resultsDict = {};
1709
- for (const msg of result) {
1710
- if (msg.actionExecutionId) {
1711
- resultsDict[msg.actionExecutionId] = msg;
1631
+ for (let i = 0; i < mergedMessages.length - 1; i++) {
1632
+ const currentMessage = mergedMessages[i];
1633
+ const nextMessage = mergedMessages[i + 1];
1634
+ if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0 && "tool_call_id" in nextMessage) {
1635
+ nextMessage.tool_call_id = currentMessage.tool_calls[0].id;
1712
1636
  }
1713
1637
  }
1714
- const reorderedResult = [];
1715
- for (const msg of result) {
1716
- if (!("actionExecutionId" in msg)) {
1717
- reorderedResult.push(msg);
1638
+ const correctedMessages = [];
1639
+ for (let i = 0; i < mergedMessages.length; i++) {
1640
+ const currentMessage = mergedMessages[i];
1641
+ const nextMessage = mergedMessages[i + 1] || null;
1642
+ const prevMessage = mergedMessages[i - 1] || null;
1643
+ if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0) {
1644
+ if (!nextMessage) {
1645
+ console.warn("No next message to auto-correct tool call, skipping:", currentMessage.tool_calls[0].id);
1646
+ continue;
1647
+ }
1648
+ if (!("tool_call_id" in nextMessage) || nextMessage.tool_call_id !== currentMessage.tool_calls[0].id) {
1649
+ const toolMessage = mergedMessages.find((m) => "tool_call_id" in m && m.tool_call_id === currentMessage.tool_calls[0].id);
1650
+ if (toolMessage) {
1651
+ console.warn("Auto-corrected tool call alignment issue:", currentMessage.tool_calls[0].id);
1652
+ correctedMessages.push(currentMessage, toolMessage);
1653
+ continue;
1654
+ } else {
1655
+ console.warn("No corresponding tool call result found for tool call, skipping:", currentMessage.tool_calls[0].id);
1656
+ continue;
1657
+ }
1658
+ }
1659
+ correctedMessages.push(currentMessage);
1660
+ continue;
1718
1661
  }
1719
- if ("arguments" in msg) {
1720
- const msgId = msg.id;
1721
- if (msgId in resultsDict) {
1722
- reorderedResult.push(resultsDict[msgId]);
1723
- } else {
1724
- console.warn("Tool call result message not found for id:", msgId);
1662
+ if ("tool_call_id" in currentMessage) {
1663
+ if (!prevMessage || !("tool_calls" in prevMessage)) {
1664
+ console.warn("No previous tool call, skipping tool call result:", currentMessage.id);
1665
+ continue;
1725
1666
  }
1667
+ if (prevMessage.tool_calls && prevMessage.tool_calls[0].id !== currentMessage.tool_call_id) {
1668
+ console.warn("Tool call id is incorrect, skipping tool call result:", currentMessage.id);
1669
+ continue;
1670
+ }
1671
+ correctedMessages.push(currentMessage);
1672
+ continue;
1726
1673
  }
1674
+ correctedMessages.push(currentMessage);
1727
1675
  }
1728
- return reorderedResult;
1676
+ return {
1677
+ ...state,
1678
+ messages: correctedMessages,
1679
+ copilotkit: {
1680
+ actions
1681
+ }
1682
+ };
1729
1683
  }
1730
- __name(langchainMessagesToCopilotKit, "langchainMessagesToCopilotKit");
1731
- function copilotkitMessagesToLangChain(messages) {
1732
- const result = [];
1733
- const processedActionExecutions = /* @__PURE__ */ new Set();
1734
- for (const message of messages) {
1735
- if (message.isTextMessage()) {
1736
- if (message.role === "user") {
1737
- result.push({
1738
- ...message,
1739
- role: MessageRole.user
1740
- });
1741
- } else if (message.role === "system") {
1742
- result.push({
1743
- ...message,
1744
- role: MessageRole.system
1745
- });
1746
- } else if (message.role === "assistant") {
1747
- result.push({
1748
- ...message,
1749
- role: MessageRole.assistant
1750
- });
1751
- }
1752
- continue;
1684
+ __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1685
+ function formatMessages(messages) {
1686
+ return messages.map((message) => {
1687
+ if (message.isTextMessage() && message.role === "assistant") {
1688
+ return message;
1689
+ }
1690
+ if (message.isTextMessage() && message.role === "system") {
1691
+ return message;
1692
+ }
1693
+ if (message.isTextMessage() && message.role === "user") {
1694
+ return message;
1753
1695
  }
1754
1696
  if (message.isActionExecutionMessage()) {
1755
- const messageId = message.parentMessageId ?? message.id;
1756
- if (processedActionExecutions.has(messageId)) {
1757
- continue;
1758
- }
1759
- processedActionExecutions.add(messageId);
1760
- const relatedActionExecutions = messages.filter((m) => m.isActionExecutionMessage() && (m.parentMessageId && m.parentMessageId === messageId || m.id === messageId));
1761
- const tool_calls = relatedActionExecutions.map((m) => ({
1762
- name: m.name,
1763
- args: m.arguments,
1764
- id: m.id
1765
- }));
1766
- result.push({
1767
- id: messageId,
1768
- type: "ActionExecutionMessage",
1697
+ const toolCall = {
1698
+ name: message.name,
1699
+ args: message.arguments,
1700
+ id: message.id
1701
+ };
1702
+ return {
1703
+ type: message.type,
1769
1704
  content: "",
1770
- tool_calls,
1771
- role: MessageRole.assistant
1772
- });
1773
- continue;
1705
+ tool_calls: [
1706
+ toolCall
1707
+ ],
1708
+ role: MessageRole.assistant,
1709
+ id: message.id
1710
+ };
1774
1711
  }
1775
1712
  if (message.isResultMessage()) {
1776
- result.push({
1713
+ return {
1777
1714
  type: message.type,
1778
1715
  content: message.result,
1779
1716
  id: message.id,
1780
1717
  tool_call_id: message.actionExecutionId,
1781
1718
  name: message.actionName,
1782
1719
  role: MessageRole.tool
1783
- });
1784
- continue;
1720
+ };
1785
1721
  }
1786
1722
  throw new Error(`Unknown message type ${message.type}`);
1787
- }
1788
- return result;
1723
+ });
1789
1724
  }
1790
- __name(copilotkitMessagesToLangChain, "copilotkitMessagesToLangChain");
1725
+ __name(formatMessages, "formatMessages");
1791
1726
 
1792
1727
  // src/lib/runtime/remote-action-constructors.ts
1793
1728
  function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
@@ -1797,7 +1732,7 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
1797
1732
  parameters: [],
1798
1733
  handler: async (_args) => {
1799
1734
  },
1800
- langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [] }) => {
1735
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1801
1736
  var _a;
1802
1737
  logger2.debug({
1803
1738
  actionName: agent.name
@@ -1823,10 +1758,7 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
1823
1758
  agent,
1824
1759
  threadId,
1825
1760
  nodeName,
1826
- messages: [
1827
- ...messages,
1828
- ...additionalMessages
1829
- ],
1761
+ messages,
1830
1762
  state,
1831
1763
  properties: graphqlContext.properties,
1832
1764
  actions: actionInputsWithoutAgents.map((action) => ({
@@ -1854,6 +1786,7 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
1854
1786
  }
1855
1787
  __name(constructLGCRemoteAction, "constructLGCRemoteAction");
1856
1788
  function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
1789
+ const totalAgents = Array.isArray(json["agents"]) ? json["agents"].length : 0;
1857
1790
  const actions = json["actions"].map((action) => ({
1858
1791
  name: action.name,
1859
1792
  description: action.description,
@@ -1867,7 +1800,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1867
1800
  telemetry_client_default.capture("oss.runtime.remote_action_executed", {
1868
1801
  agentExecution: false,
1869
1802
  type: "self-hosted",
1870
- agentsAmount: json["agents"].length
1803
+ agentsAmount: totalAgents
1871
1804
  });
1872
1805
  try {
1873
1806
  const response = await fetch(`${url}/actions/execute`, {
@@ -1902,13 +1835,13 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1902
1835
  }
1903
1836
  }
1904
1837
  }));
1905
- const agents = json["agents"].map((agent) => ({
1838
+ const agents = totalAgents ? json["agents"].map((agent) => ({
1906
1839
  name: agent.name,
1907
1840
  description: agent.description,
1908
1841
  parameters: [],
1909
1842
  handler: async (_args) => {
1910
1843
  },
1911
- langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [] }) => {
1844
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1912
1845
  var _a;
1913
1846
  logger2.debug({
1914
1847
  actionName: agent.name
@@ -1933,10 +1866,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1933
1866
  name,
1934
1867
  threadId,
1935
1868
  nodeName,
1936
- messages: [
1937
- ...messages,
1938
- ...additionalMessages
1939
- ],
1869
+ messages,
1940
1870
  state,
1941
1871
  properties: graphqlContext.properties,
1942
1872
  actions: actionInputsWithoutAgents.map((action) => ({
@@ -1958,7 +1888,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1958
1888
  streamResponse(response.body, eventSource.eventStream$);
1959
1889
  return eventSource.processLangGraphEvents();
1960
1890
  }
1961
- }));
1891
+ })) : [];
1962
1892
  return [
1963
1893
  ...actions,
1964
1894
  ...agents
@@ -2148,8 +2078,7 @@ function convertGqlInputToMessages(inputMessages) {
2148
2078
  id: message.id,
2149
2079
  createdAt: message.createdAt,
2150
2080
  role: message.textMessage.role,
2151
- content: message.textMessage.content,
2152
- parentMessageId: message.textMessage.parentMessageId
2081
+ content: message.textMessage.content
2153
2082
  }));
2154
2083
  } else if (message.actionExecutionMessage) {
2155
2084
  messages.push(plainToInstance(ActionExecutionMessage, {
@@ -2157,7 +2086,7 @@ function convertGqlInputToMessages(inputMessages) {
2157
2086
  createdAt: message.createdAt,
2158
2087
  name: message.actionExecutionMessage.name,
2159
2088
  arguments: JSON.parse(message.actionExecutionMessage.arguments),
2160
- parentMessageId: message.actionExecutionMessage.parentMessageId
2089
+ scope: message.actionExecutionMessage.scope
2161
2090
  }));
2162
2091
  } else if (message.resultMessage) {
2163
2092
  messages.push(plainToInstance(ResultMessage, {
@@ -2460,7 +2389,6 @@ __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
2460
2389
  var telemetry_client_default = telemetryClient;
2461
2390
 
2462
2391
  // src/service-adapters/events.ts
2463
- import { plainToInstance as plainToInstance2 } from "class-transformer";
2464
2392
  var RuntimeEventTypes;
2465
2393
  (function(RuntimeEventTypes2) {
2466
2394
  RuntimeEventTypes2["TextMessageStart"] = "TextMessageStart";
@@ -2476,74 +2404,52 @@ var RuntimeEventSubject = class extends ReplaySubject2 {
2476
2404
  constructor() {
2477
2405
  super();
2478
2406
  }
2479
- sendTextMessageStart({ messageId, parentMessageId }) {
2407
+ sendTextMessageStart(messageId) {
2480
2408
  this.next({
2481
2409
  type: "TextMessageStart",
2482
- messageId,
2483
- parentMessageId
2410
+ messageId
2484
2411
  });
2485
2412
  }
2486
- sendTextMessageContent({ messageId, content }) {
2413
+ sendTextMessageContent(content) {
2487
2414
  this.next({
2488
2415
  type: "TextMessageContent",
2489
- content,
2490
- messageId
2416
+ content
2491
2417
  });
2492
2418
  }
2493
- sendTextMessageEnd({ messageId }) {
2419
+ sendTextMessageEnd() {
2494
2420
  this.next({
2495
- type: "TextMessageEnd",
2496
- messageId
2421
+ type: "TextMessageEnd"
2497
2422
  });
2498
2423
  }
2499
2424
  sendTextMessage(messageId, content) {
2500
- this.sendTextMessageStart({
2501
- messageId
2502
- });
2503
- this.sendTextMessageContent({
2504
- messageId,
2505
- content
2506
- });
2507
- this.sendTextMessageEnd({
2508
- messageId
2509
- });
2425
+ this.sendTextMessageStart(messageId);
2426
+ this.sendTextMessageContent(content);
2427
+ this.sendTextMessageEnd();
2510
2428
  }
2511
- sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId }) {
2429
+ sendActionExecutionStart(actionExecutionId, actionName) {
2512
2430
  this.next({
2513
2431
  type: "ActionExecutionStart",
2514
2432
  actionExecutionId,
2515
- actionName,
2516
- parentMessageId
2433
+ actionName
2517
2434
  });
2518
2435
  }
2519
- sendActionExecutionArgs({ actionExecutionId, args }) {
2436
+ sendActionExecutionArgs(args) {
2520
2437
  this.next({
2521
2438
  type: "ActionExecutionArgs",
2522
- args,
2523
- actionExecutionId
2439
+ args
2524
2440
  });
2525
2441
  }
2526
- sendActionExecutionEnd({ actionExecutionId }) {
2442
+ sendActionExecutionEnd() {
2527
2443
  this.next({
2528
- type: "ActionExecutionEnd",
2529
- actionExecutionId
2444
+ type: "ActionExecutionEnd"
2530
2445
  });
2531
2446
  }
2532
- sendActionExecution({ actionExecutionId, actionName, args, parentMessageId }) {
2533
- this.sendActionExecutionStart({
2534
- actionExecutionId,
2535
- actionName,
2536
- parentMessageId
2537
- });
2538
- this.sendActionExecutionArgs({
2539
- actionExecutionId,
2540
- args
2541
- });
2542
- this.sendActionExecutionEnd({
2543
- actionExecutionId
2544
- });
2447
+ sendActionExecution(actionExecutionId, toolName, args) {
2448
+ this.sendActionExecutionStart(actionExecutionId, toolName);
2449
+ this.sendActionExecutionArgs(args);
2450
+ this.sendActionExecutionEnd();
2545
2451
  }
2546
- sendActionExecutionResult({ actionExecutionId, actionName, result }) {
2452
+ sendActionExecutionResult(actionExecutionId, actionName, result) {
2547
2453
  this.next({
2548
2454
  type: "ActionExecutionResult",
2549
2455
  actionName,
@@ -2551,7 +2457,7 @@ var RuntimeEventSubject = class extends ReplaySubject2 {
2551
2457
  result
2552
2458
  });
2553
2459
  }
2554
- sendAgentStateMessage({ threadId, agentName, nodeName, runId, active, role, state, running }) {
2460
+ sendAgentStateMessage(threadId, agentName, nodeName, runId, active, role, state, running) {
2555
2461
  this.next({
2556
2462
  type: "AgentStateMessage",
2557
2463
  threadId,
@@ -2588,13 +2494,22 @@ var RuntimeEventSource = class {
2588
2494
  this.sendErrorMessageToChat();
2589
2495
  });
2590
2496
  return this.eventStream$.pipe(
2497
+ // mark tools for server side execution
2498
+ map((event) => {
2499
+ if (event.type === "ActionExecutionStart") {
2500
+ if (event.scope !== "passThrough") {
2501
+ event.scope = serverSideActions.find((action) => action.name === event.actionName) ? "server" : "client";
2502
+ }
2503
+ }
2504
+ return event;
2505
+ }),
2591
2506
  // track state
2592
2507
  scan2((acc, event) => {
2593
2508
  acc = {
2594
2509
  ...acc
2595
2510
  };
2596
2511
  if (event.type === "ActionExecutionStart") {
2597
- acc.callActionServerSide = serverSideActions.find((action) => action.name === event.actionName) !== void 0;
2512
+ acc.callActionServerSide = event.scope === "server";
2598
2513
  acc.args = "";
2599
2514
  acc.actionExecutionId = event.actionExecutionId;
2600
2515
  if (acc.callActionServerSide) {
@@ -2648,33 +2563,10 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
2648
2563
  }
2649
2564
  }
2650
2565
  if (isLangGraphAgentAction(action)) {
2651
- const result = `${action.name} agent started`;
2652
- const agentExecution = plainToInstance2(ActionExecutionMessage, {
2653
- id: actionExecutionId,
2654
- createdAt: /* @__PURE__ */ new Date(),
2655
- name: action.name,
2656
- arguments: JSON.parse(actionArguments),
2657
- parentMessageId: actionExecutionId
2658
- });
2659
- const agentExecutionResult = plainToInstance2(ResultMessage, {
2660
- id: "result-" + actionExecutionId,
2661
- createdAt: /* @__PURE__ */ new Date(),
2662
- actionExecutionId,
2663
- actionName: action.name,
2664
- result
2665
- });
2666
- eventStream$.sendActionExecutionResult({
2667
- actionExecutionId,
2668
- actionName: action.name,
2669
- result
2670
- });
2566
+ eventStream$.sendActionExecutionResult(actionExecutionId, action.name, `${action.name} agent started`);
2671
2567
  const stream = await action.langGraphAgentHandler({
2672
2568
  name: action.name,
2673
- actionInputsWithoutAgents,
2674
- additionalMessages: [
2675
- agentExecution,
2676
- agentExecutionResult
2677
- ]
2569
+ actionInputsWithoutAgents
2678
2570
  });
2679
2571
  from2(stream).subscribe({
2680
2572
  next: (event) => eventStream$.next(event),
@@ -2697,7 +2589,7 @@ __name(executeAction, "executeAction");
2697
2589
 
2698
2590
  // src/graphql/resolvers/copilot.resolver.ts
2699
2591
  import { GraphQLJSONObject } from "graphql-scalars";
2700
- import { plainToInstance as plainToInstance3 } from "class-transformer";
2592
+ import { plainToInstance as plainToInstance2 } from "class-transformer";
2701
2593
  import { GraphQLError } from "graphql";
2702
2594
  import { randomId as randomId4 } from "@copilotkit/shared";
2703
2595
  function _ts_decorate12(decorators, target, key, desc) {
@@ -2860,7 +2752,7 @@ var CopilotResolver = class {
2860
2752
  reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`
2861
2753
  });
2862
2754
  outputMessages = [
2863
- plainToInstance3(TextMessage, {
2755
+ plainToInstance2(TextMessage, {
2864
2756
  id: randomId4(),
2865
2757
  createdAt: /* @__PURE__ */ new Date(),
2866
2758
  content: result.reason,
@@ -2909,15 +2801,12 @@ var CopilotResolver = class {
2909
2801
  // skip until this message start event
2910
2802
  skipWhile((e) => e !== event),
2911
2803
  // take until the message end event
2912
- takeWhile((e) => !(e.type === RuntimeEventTypes.TextMessageEnd && e.messageId == event.messageId)),
2913
- // filter out any other message events or message ids
2914
- filter((e) => e.type == RuntimeEventTypes.TextMessageContent && e.messageId == event.messageId)
2804
+ takeWhile((e) => e.type != RuntimeEventTypes.TextMessageEnd)
2915
2805
  );
2916
2806
  const streamingTextStatus = new Subject();
2917
2807
  const messageId = event.messageId;
2918
2808
  pushMessage({
2919
2809
  id: messageId,
2920
- parentMessageId: event.parentMessageId,
2921
2810
  status: firstValueFrom2(streamingTextStatus),
2922
2811
  createdAt: /* @__PURE__ */ new Date(),
2923
2812
  role: MessageRole.assistant,
@@ -2930,7 +2819,7 @@ var CopilotResolver = class {
2930
2819
  reason,
2931
2820
  messageId: messageId2
2932
2821
  }, "Text streaming interrupted");
2933
- streamingTextStatus.next(plainToInstance3(FailedMessageStatus, {
2822
+ streamingTextStatus.next(plainToInstance2(FailedMessageStatus, {
2934
2823
  reason
2935
2824
  }));
2936
2825
  responseStatus$.next(new MessageStreamInterruptedResponse({
@@ -2963,7 +2852,7 @@ var CopilotResolver = class {
2963
2852
  streamingTextStatus.next(new SuccessMessageStatus());
2964
2853
  stopStreamingText();
2965
2854
  textSubscription == null ? void 0 : textSubscription.unsubscribe();
2966
- outputMessages.push(plainToInstance3(TextMessage, {
2855
+ outputMessages.push(plainToInstance2(TextMessage, {
2967
2856
  id: messageId,
2968
2857
  createdAt: /* @__PURE__ */ new Date(),
2969
2858
  content: textChunks.join(""),
@@ -2976,20 +2865,14 @@ var CopilotResolver = class {
2976
2865
  break;
2977
2866
  case RuntimeEventTypes.ActionExecutionStart:
2978
2867
  logger2.debug("Action execution start event received");
2979
- const actionExecutionArgumentStream = eventStream.pipe(
2980
- skipWhile((e) => e !== event),
2981
- // take until the action execution end event
2982
- takeWhile((e) => !(e.type === RuntimeEventTypes.ActionExecutionEnd && e.actionExecutionId == event.actionExecutionId)),
2983
- // filter out any other action execution events or action execution ids
2984
- filter((e) => e.type == RuntimeEventTypes.ActionExecutionArgs && e.actionExecutionId == event.actionExecutionId)
2985
- );
2868
+ const actionExecutionArgumentStream = eventStream.pipe(skipWhile((e) => e !== event), takeWhile((e) => e.type != RuntimeEventTypes.ActionExecutionEnd));
2986
2869
  const streamingArgumentsStatus = new Subject();
2987
2870
  pushMessage({
2988
2871
  id: event.actionExecutionId,
2989
- parentMessageId: event.parentMessageId,
2990
2872
  status: firstValueFrom2(streamingArgumentsStatus),
2991
2873
  createdAt: /* @__PURE__ */ new Date(),
2992
2874
  name: event.actionName,
2875
+ scope: event.scope,
2993
2876
  arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
2994
2877
  logger2.debug("Action execution argument stream created");
2995
2878
  const argumentChunks = [];
@@ -3005,7 +2888,7 @@ var CopilotResolver = class {
3005
2888
  logger2.error({
3006
2889
  err
3007
2890
  }, "Error in action execution argument stream");
3008
- streamingArgumentsStatus.next(plainToInstance3(FailedMessageStatus, {
2891
+ streamingArgumentsStatus.next(plainToInstance2(FailedMessageStatus, {
3009
2892
  reason: "An unknown error has occurred in the action execution argument stream"
3010
2893
  }));
3011
2894
  stopStreamingArguments();
@@ -3016,10 +2899,11 @@ var CopilotResolver = class {
3016
2899
  streamingArgumentsStatus.next(new SuccessMessageStatus());
3017
2900
  stopStreamingArguments();
3018
2901
  actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
3019
- outputMessages.push(plainToInstance3(ActionExecutionMessage, {
2902
+ outputMessages.push(plainToInstance2(ActionExecutionMessage, {
3020
2903
  id: event.actionExecutionId,
3021
2904
  createdAt: /* @__PURE__ */ new Date(),
3022
2905
  name: event.actionName,
2906
+ scope: event.scope,
3023
2907
  arguments: argumentChunks.join("")
3024
2908
  }));
3025
2909
  }
@@ -3032,15 +2916,15 @@ var CopilotResolver = class {
3032
2916
  result: event.result
3033
2917
  }, "Action execution result event received");
3034
2918
  pushMessage({
3035
- id: "result-" + event.actionExecutionId,
2919
+ id: randomId4(),
3036
2920
  status: new SuccessMessageStatus(),
3037
2921
  createdAt: /* @__PURE__ */ new Date(),
3038
2922
  actionExecutionId: event.actionExecutionId,
3039
2923
  actionName: event.actionName,
3040
2924
  result: event.result
3041
2925
  });
3042
- outputMessages.push(plainToInstance3(ResultMessage, {
3043
- id: "result-" + event.actionExecutionId,
2926
+ outputMessages.push(plainToInstance2(ResultMessage, {
2927
+ id: randomId4(),
3044
2928
  createdAt: /* @__PURE__ */ new Date(),
3045
2929
  actionExecutionId: event.actionExecutionId,
3046
2930
  actionName: event.actionName,
@@ -3064,7 +2948,7 @@ var CopilotResolver = class {
3064
2948
  role: MessageRole.assistant,
3065
2949
  createdAt: /* @__PURE__ */ new Date()
3066
2950
  });
3067
- outputMessages.push(plainToInstance3(AgentStateMessage, {
2951
+ outputMessages.push(plainToInstance2(AgentStateMessage, {
3068
2952
  id: randomId4(),
3069
2953
  threadId: event.threadId,
3070
2954
  agentName: event.agentName,
@@ -3276,4 +3160,4 @@ export {
3276
3160
  getCommonConfig,
3277
3161
  copilotRuntimeNodeHttpEndpoint
3278
3162
  };
3279
- //# sourceMappingURL=chunk-FVYNRYIB.mjs.map
3163
+ //# sourceMappingURL=chunk-5KJYPVQJ.mjs.map