@copilotkit/runtime 1.4.7 → 1.4.8-coagents-v0-3.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 (73) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/__snapshots__/schema/schema.graphql +7 -9
  3. package/dist/{chunk-OKQVDDJ2.mjs → chunk-2PK2SFRB.mjs} +220 -57
  4. package/dist/chunk-2PK2SFRB.mjs.map +1 -0
  5. package/dist/{chunk-XWWKPWHL.mjs → chunk-BACNNHHI.mjs} +2 -2
  6. package/dist/{chunk-44ICGB7P.mjs → chunk-FVYNRYIB.mjs} +420 -296
  7. package/dist/chunk-FVYNRYIB.mjs.map +1 -0
  8. package/dist/{chunk-BE5WOXMD.mjs → chunk-MQJNZYAH.mjs} +2 -2
  9. package/dist/{chunk-B74M7FXG.mjs → chunk-RFF5IIZJ.mjs} +3 -2
  10. package/dist/chunk-RFF5IIZJ.mjs.map +1 -0
  11. package/dist/{chunk-DRO25ADD.mjs → chunk-YFG3Q3YH.mjs} +2 -2
  12. package/dist/{copilot-runtime-12e7ac40.d.ts → copilot-runtime-b15b683d.d.ts} +2 -2
  13. package/dist/graphql/types/converted/index.d.ts +1 -1
  14. package/dist/graphql/types/converted/index.js +2 -1
  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-24abe931.d.ts → groq-adapter-50aa9621.d.ts} +1 -1
  18. package/dist/{index-10b1c870.d.ts → index-ff3fbc33.d.ts} +7 -8
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +725 -437
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +6 -6
  23. package/dist/{langserve-f021ab9c.d.ts → langserve-8ec29cba.d.ts} +51 -12
  24. package/dist/lib/index.d.ts +4 -4
  25. package/dist/lib/index.js +703 -431
  26. package/dist/lib/index.js.map +1 -1
  27. package/dist/lib/index.mjs +6 -6
  28. package/dist/lib/integrations/index.d.ts +4 -4
  29. package/dist/lib/integrations/index.js +71 -30
  30. package/dist/lib/integrations/index.js.map +1 -1
  31. package/dist/lib/integrations/index.mjs +6 -6
  32. package/dist/lib/integrations/nest/index.d.ts +3 -3
  33. package/dist/lib/integrations/nest/index.js +71 -30
  34. package/dist/lib/integrations/nest/index.js.map +1 -1
  35. package/dist/lib/integrations/nest/index.mjs +4 -4
  36. package/dist/lib/integrations/node-express/index.d.ts +3 -3
  37. package/dist/lib/integrations/node-express/index.js +71 -30
  38. package/dist/lib/integrations/node-express/index.js.map +1 -1
  39. package/dist/lib/integrations/node-express/index.mjs +4 -4
  40. package/dist/lib/integrations/node-http/index.d.ts +3 -3
  41. package/dist/lib/integrations/node-http/index.js +71 -30
  42. package/dist/lib/integrations/node-http/index.js.map +1 -1
  43. package/dist/lib/integrations/node-http/index.mjs +3 -3
  44. package/dist/service-adapters/index.d.ts +4 -4
  45. package/dist/service-adapters/index.js +219 -56
  46. package/dist/service-adapters/index.js.map +1 -1
  47. package/dist/service-adapters/index.mjs +1 -1
  48. package/package.json +2 -2
  49. package/src/agents/langgraph/event-source.ts +140 -148
  50. package/src/agents/langgraph/events.ts +1 -1
  51. package/src/graphql/inputs/message.input.ts +15 -3
  52. package/src/graphql/resolvers/copilot.resolver.ts +32 -6
  53. package/src/graphql/types/converted/index.ts +4 -3
  54. package/src/graphql/types/copilot-response.type.ts +12 -3
  55. package/src/graphql/types/enums.ts +0 -11
  56. package/src/lib/runtime/remote-action-constructors.ts +4 -2
  57. package/src/lib/runtime/remote-actions.ts +1 -0
  58. package/src/lib/runtime/remote-lg-action.ts +161 -140
  59. package/src/service-adapters/anthropic/anthropic-adapter.ts +16 -6
  60. package/src/service-adapters/conversion.ts +2 -1
  61. package/src/service-adapters/events.ts +111 -52
  62. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +7 -3
  63. package/src/service-adapters/groq/groq-adapter.ts +23 -8
  64. package/src/service-adapters/langchain/utils.ts +49 -31
  65. package/src/service-adapters/openai/openai-adapter.ts +22 -9
  66. package/src/service-adapters/openai/openai-assistant-adapter.ts +22 -8
  67. package/src/service-adapters/unify/unify-adapter.ts +28 -11
  68. package/dist/chunk-44ICGB7P.mjs.map +0 -1
  69. package/dist/chunk-B74M7FXG.mjs.map +0 -1
  70. package/dist/chunk-OKQVDDJ2.mjs.map +0 -1
  71. /package/dist/{chunk-XWWKPWHL.mjs.map → chunk-BACNNHHI.mjs.map} +0 -0
  72. /package/dist/{chunk-BE5WOXMD.mjs.map → chunk-MQJNZYAH.mjs.map} +0 -0
  73. /package/dist/{chunk-DRO25ADD.mjs.map → chunk-YFG3Q3YH.mjs.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  RemoteChain,
3
3
  streamLangChainResponse
4
- } from "./chunk-OKQVDDJ2.mjs";
4
+ } from "./chunk-2PK2SFRB.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-B74M7FXG.mjs";
17
+ } from "./chunk-RFF5IIZJ.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.7",
40
+ version: "1.4.8-coagents-v0-3.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, finalize, firstValueFrom as firstValueFrom2, shareReplay, skipWhile, take, takeWhile, tap } from "rxjs";
125
+ import { ReplaySubject as ReplaySubject3, Subject, filter, 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,12 +139,6 @@ 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 = {}));
148
142
  var CopilotRequestType;
149
143
  (function(CopilotRequestType2) {
150
144
  CopilotRequestType2["Chat"] = "Chat";
@@ -163,10 +157,6 @@ registerEnumType(MessageRole, {
163
157
  name: "MessageRole",
164
158
  description: "The role of the message"
165
159
  });
166
- registerEnumType(ActionExecutionScope, {
167
- name: "ActionExecutionScope",
168
- description: "The scope of the action"
169
- });
170
160
  registerEnumType(CopilotRequestType, {
171
161
  name: "CopilotRequestType",
172
162
  description: "The type of Copilot request"
@@ -229,6 +219,7 @@ MessageInput = _ts_decorate([
229
219
  ], MessageInput);
230
220
  var TextMessageInput = class {
231
221
  content;
222
+ parentMessageId;
232
223
  role;
233
224
  };
234
225
  __name(TextMessageInput, "TextMessageInput");
@@ -236,6 +227,12 @@ _ts_decorate([
236
227
  Field(() => String),
237
228
  _ts_metadata("design:type", String)
238
229
  ], 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);
239
236
  _ts_decorate([
240
237
  Field(() => MessageRole),
241
238
  _ts_metadata("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
@@ -246,6 +243,7 @@ TextMessageInput = _ts_decorate([
246
243
  var ActionExecutionMessageInput = class {
247
244
  name;
248
245
  arguments;
246
+ parentMessageId;
249
247
  scope;
250
248
  };
251
249
  __name(ActionExecutionMessageInput, "ActionExecutionMessageInput");
@@ -258,8 +256,17 @@ _ts_decorate([
258
256
  _ts_metadata("design:type", String)
259
257
  ], ActionExecutionMessageInput.prototype, "arguments", void 0);
260
258
  _ts_decorate([
261
- Field(() => ActionExecutionScope),
262
- _ts_metadata("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
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)
263
270
  ], ActionExecutionMessageInput.prototype, "scope", void 0);
264
271
  ActionExecutionMessageInput = _ts_decorate([
265
272
  InputType()
@@ -267,6 +274,7 @@ ActionExecutionMessageInput = _ts_decorate([
267
274
  var ResultMessageInput = class {
268
275
  actionExecutionId;
269
276
  actionName;
277
+ parentMessageId;
270
278
  result;
271
279
  };
272
280
  __name(ResultMessageInput, "ResultMessageInput");
@@ -278,6 +286,12 @@ _ts_decorate([
278
286
  Field(() => String),
279
287
  _ts_metadata("design:type", String)
280
288
  ], 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);
281
295
  _ts_decorate([
282
296
  Field(() => String),
283
297
  _ts_metadata("design:type", String)
@@ -893,6 +907,7 @@ BaseMessageOutput = _ts_decorate11([
893
907
  var TextMessageOutput = class {
894
908
  role;
895
909
  content;
910
+ parentMessageId;
896
911
  };
897
912
  __name(TextMessageOutput, "TextMessageOutput");
898
913
  _ts_decorate11([
@@ -905,6 +920,12 @@ _ts_decorate11([
905
920
  ]),
906
921
  _ts_metadata11("design:type", Array)
907
922
  ], 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);
908
929
  TextMessageOutput = _ts_decorate11([
909
930
  ObjectType2({
910
931
  implements: BaseMessageOutput
@@ -914,6 +935,7 @@ var ActionExecutionMessageOutput = class {
914
935
  name;
915
936
  scope;
916
937
  arguments;
938
+ parentMessageId;
917
939
  };
918
940
  __name(ActionExecutionMessageOutput, "ActionExecutionMessageOutput");
919
941
  _ts_decorate11([
@@ -921,8 +943,11 @@ _ts_decorate11([
921
943
  _ts_metadata11("design:type", String)
922
944
  ], ActionExecutionMessageOutput.prototype, "name", void 0);
923
945
  _ts_decorate11([
924
- Field11(() => ActionExecutionScope),
925
- _ts_metadata11("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
946
+ Field11(() => String, {
947
+ nullable: true,
948
+ deprecationReason: "This field will be removed in a future version"
949
+ }),
950
+ _ts_metadata11("design:type", String)
926
951
  ], ActionExecutionMessageOutput.prototype, "scope", void 0);
927
952
  _ts_decorate11([
928
953
  Field11(() => [
@@ -930,6 +955,12 @@ _ts_decorate11([
930
955
  ]),
931
956
  _ts_metadata11("design:type", Array)
932
957
  ], 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);
933
964
  ActionExecutionMessageOutput = _ts_decorate11([
934
965
  ObjectType2({
935
966
  implements: BaseMessageOutput
@@ -1042,7 +1073,7 @@ import { Repeater } from "graphql-yoga";
1042
1073
 
1043
1074
  // src/service-adapters/events.ts
1044
1075
  import { randomId as randomId3 } from "@copilotkit/shared";
1045
- import { of, concat, map, scan as scan2, concatMap, ReplaySubject as ReplaySubject2, firstValueFrom, from as from2 } from "rxjs";
1076
+ import { of, concat, scan as scan2, concatMap, ReplaySubject as ReplaySubject2, firstValueFrom, from as from2 } from "rxjs";
1046
1077
 
1047
1078
  // src/lib/telemetry-client.ts
1048
1079
  import { TelemetryClient } from "@copilotkit/shared";
@@ -1090,163 +1121,167 @@ var RemoteLangGraphEventSource = class {
1090
1121
  }
1091
1122
  return shouldEmitToolCalls === toolCallName;
1092
1123
  }
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
+ }
1093
1154
  processLangGraphEvents() {
1094
1155
  let lastEventWithState = null;
1095
1156
  return this.eventStream$.pipe(scan((acc, event) => {
1096
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1097
1157
  if (event.event === LangGraphEventTypes.OnChatModelStream) {
1098
- 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);
1099
- if (typeof content === "string") {
1100
- acc.content = content;
1101
- } else if (Array.isArray(content) && content.length > 0) {
1102
- acc.content = content[0].text;
1103
- } else {
1104
- acc.content = null;
1105
- }
1106
- const toolCallChunks = (
1107
- // @ts-expect-error -- LangGraph Platform implementation stores data outside of kwargs
1108
- ((_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)
1109
- );
1110
- 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);
1111
- if (toolCallChunks && toolCallChunks.length > 0) {
1112
- acc.prevToolCallMessageId = acc.toolCallMessageId;
1113
- acc.toolCallMessageId = toolCallMessageId;
1114
- if ((_p = toolCallChunks[0]) == null ? void 0 : _p.name) {
1115
- acc.toolCallName = toolCallChunks[0].name;
1116
- }
1117
- if ((_q = toolCallChunks[0]) == null ? void 0 : _q.id) {
1118
- acc.toolCallId = toolCallChunks[0].id;
1119
- }
1120
- acc.prevMessageId = acc.messageId;
1121
- acc.messageId = toolCallMessageId;
1122
- } else if (acc.content && acc.content != "") {
1123
- acc.prevMessageId = acc.messageId;
1124
- acc.messageId = toolCallMessageId;
1125
- } else {
1126
- acc.prevToolCallMessageId = acc.toolCallMessageId;
1127
- acc.prevMessageId = acc.messageId;
1128
- }
1129
- } else {
1130
- acc.prevToolCallMessageId = acc.toolCallMessageId;
1131
- acc.toolCallMessageId = null;
1132
- acc.prevMessageId = acc.messageId;
1133
- acc.messageId = null;
1134
- acc.toolCallName = null;
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
+ });
1135
1172
  }
1136
1173
  acc.event = event;
1137
1174
  lastEventWithState = acc;
1138
1175
  return acc;
1139
1176
  }, {
1140
1177
  event: null,
1141
- toolCallId: null,
1142
- toolCallMessageId: null,
1143
- prevToolCallMessageId: null,
1144
- messageId: null,
1145
- toolCallName: null,
1146
- prevMessageId: null,
1147
- content: null
1148
- }), mergeMap((eventWithState) => {
1149
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
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) => {
1150
1188
  const events = [];
1151
1189
  let shouldEmitMessages = true;
1152
- let shouldEmitToolCalls = false;
1153
- if (eventWithState.event.event == LangGraphEventTypes.OnChatModelStream) {
1154
- if ("copilotkit:emit-tool-calls" in (eventWithState.event.metadata || {})) {
1155
- shouldEmitToolCalls = eventWithState.event.metadata["copilotkit:emit-tool-calls"];
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"];
1156
1194
  }
1157
- if ("copilotkit:emit-messages" in (eventWithState.event.metadata || {})) {
1158
- shouldEmitMessages = eventWithState.event.metadata["copilotkit:emit-messages"];
1195
+ if ("copilotkit:emit-messages" in (acc.event.metadata || {})) {
1196
+ shouldEmitMessages = acc.event.metadata["copilotkit:emit-messages"];
1159
1197
  }
1160
1198
  }
1161
- if (eventWithState.prevToolCallMessageId !== null && eventWithState.prevToolCallMessageId !== eventWithState.toolCallMessageId && this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1199
+ const responseMetadata = this.getResponseMetadata(acc.event);
1200
+ if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls" && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1162
1201
  events.push({
1163
- type: RuntimeEventTypes.ActionExecutionEnd
1202
+ type: RuntimeEventTypes.ActionExecutionEnd,
1203
+ actionExecutionId: acc.lastToolCallId
1164
1204
  });
1165
1205
  }
1166
- if (eventWithState.prevMessageId !== null && eventWithState.prevMessageId !== eventWithState.messageId && shouldEmitMessages) {
1206
+ if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop" && shouldEmitMessages) {
1167
1207
  events.push({
1168
- type: RuntimeEventTypes.TextMessageEnd
1208
+ type: RuntimeEventTypes.TextMessageEnd,
1209
+ messageId: acc.lastMessageId
1169
1210
  });
1170
1211
  }
1171
- switch (eventWithState.event.event) {
1212
+ switch (acc.event.event) {
1172
1213
  case LangGraphEventTypes.OnCustomEvent:
1173
- if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1214
+ if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1174
1215
  events.push({
1175
1216
  type: RuntimeEventTypes.TextMessageStart,
1176
- messageId: eventWithState.event.data.message_id
1217
+ messageId: acc.event.data.message_id
1177
1218
  });
1178
1219
  events.push({
1179
1220
  type: RuntimeEventTypes.TextMessageContent,
1180
- content: eventWithState.event.data.message
1221
+ messageId: acc.event.data.message_id,
1222
+ content: acc.event.data.message
1181
1223
  });
1182
1224
  events.push({
1183
- type: RuntimeEventTypes.TextMessageEnd
1225
+ type: RuntimeEventTypes.TextMessageEnd,
1226
+ messageId: acc.event.data.message_id
1184
1227
  });
1185
- } else if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1228
+ } else if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1186
1229
  events.push({
1187
1230
  type: RuntimeEventTypes.ActionExecutionStart,
1188
- actionExecutionId: eventWithState.event.data.id,
1189
- actionName: eventWithState.event.data.name
1231
+ actionExecutionId: acc.event.data.id,
1232
+ actionName: acc.event.data.name,
1233
+ parentMessageId: acc.event.data.id
1190
1234
  });
1191
1235
  events.push({
1192
1236
  type: RuntimeEventTypes.ActionExecutionArgs,
1193
- args: JSON.stringify(eventWithState.event.data.args)
1237
+ actionExecutionId: acc.event.data.id,
1238
+ args: JSON.stringify(acc.event.data.args)
1194
1239
  });
1195
1240
  events.push({
1196
- type: RuntimeEventTypes.ActionExecutionEnd
1241
+ type: RuntimeEventTypes.ActionExecutionEnd,
1242
+ actionExecutionId: acc.event.data.id
1197
1243
  });
1198
1244
  }
1199
1245
  break;
1200
1246
  case LangGraphEventTypes.OnCopilotKitStateSync:
1201
1247
  events.push({
1202
1248
  type: RuntimeEventTypes.AgentStateMessage,
1203
- threadId: eventWithState.event.thread_id,
1204
- role: eventWithState.event.role,
1205
- agentName: eventWithState.event.agent_name,
1206
- nodeName: eventWithState.event.node_name,
1207
- runId: eventWithState.event.run_id,
1208
- active: eventWithState.event.active,
1209
- state: JSON.stringify(eventWithState.event.state),
1210
- running: eventWithState.event.running
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
1211
1257
  });
1212
1258
  break;
1213
- case LangGraphEventTypes.OnToolEnd:
1214
- break;
1215
1259
  case LangGraphEventTypes.OnChatModelStream:
1216
- if (eventWithState.toolCallMessageId !== null && eventWithState.prevToolCallMessageId !== eventWithState.toolCallMessageId) {
1217
- if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1218
- events.push({
1219
- type: RuntimeEventTypes.ActionExecutionStart,
1220
- actionExecutionId: eventWithState.toolCallMessageId,
1221
- actionName: eventWithState.toolCallName,
1222
- scope: "client"
1223
- });
1224
- }
1225
- } else if (eventWithState.messageId !== null && eventWithState.prevMessageId !== eventWithState.messageId) {
1226
- if (shouldEmitMessages) {
1227
- events.push({
1228
- type: RuntimeEventTypes.TextMessageStart,
1229
- messageId: eventWithState.messageId
1230
- });
1231
- }
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
+ });
1232
1272
  }
1233
- 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
1234
- ((_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);
1235
- const content = eventWithState.content;
1236
- if (args) {
1237
- if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1238
- events.push({
1239
- type: RuntimeEventTypes.ActionExecutionArgs,
1240
- args
1241
- });
1242
- }
1243
- } else if (eventWithState.messageId !== null && content) {
1244
- if (shouldEmitMessages) {
1245
- events.push({
1246
- type: RuntimeEventTypes.TextMessageContent,
1247
- content
1248
- });
1249
- }
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
+ });
1250
1285
  }
1251
1286
  break;
1252
1287
  }
@@ -1254,14 +1289,16 @@ var RemoteLangGraphEventSource = class {
1254
1289
  }), catchError((error) => {
1255
1290
  console.error(error);
1256
1291
  const events = [];
1257
- if (lastEventWithState == null ? void 0 : lastEventWithState.messageId) {
1292
+ if ((lastEventWithState == null ? void 0 : lastEventWithState.lastMessageId) && !lastEventWithState.isToolCall) {
1258
1293
  events.push({
1259
- type: RuntimeEventTypes.TextMessageEnd
1294
+ type: RuntimeEventTypes.TextMessageEnd,
1295
+ messageId: lastEventWithState.lastMessageId
1260
1296
  });
1261
1297
  }
1262
- if (lastEventWithState == null ? void 0 : lastEventWithState.toolCallMessageId) {
1298
+ if (lastEventWithState == null ? void 0 : lastEventWithState.lastToolCallId) {
1263
1299
  events.push({
1264
- type: RuntimeEventTypes.ActionExecutionEnd
1300
+ type: RuntimeEventTypes.ActionExecutionEnd,
1301
+ actionExecutionId: lastEventWithState.lastToolCallId
1265
1302
  });
1266
1303
  }
1267
1304
  const messageId = randomId();
@@ -1271,10 +1308,12 @@ var RemoteLangGraphEventSource = class {
1271
1308
  });
1272
1309
  events.push({
1273
1310
  type: RuntimeEventTypes.TextMessageContent,
1311
+ messageId,
1274
1312
  content: "\u274C An error occurred. Please try again."
1275
1313
  });
1276
1314
  events.push({
1277
- type: RuntimeEventTypes.TextMessageEnd
1315
+ type: RuntimeEventTypes.TextMessageEnd,
1316
+ messageId
1278
1317
  });
1279
1318
  return events;
1280
1319
  }));
@@ -1332,7 +1371,7 @@ async function streamEvents(controller, args) {
1332
1371
  const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
1333
1372
  let formattedMessages = [];
1334
1373
  try {
1335
- formattedMessages = formatMessages(messages);
1374
+ formattedMessages = copilotkitMessagesToLangChain(messages);
1336
1375
  } catch (e) {
1337
1376
  logger2.error(e, `Error event thrown: ${e.message}`);
1338
1377
  }
@@ -1485,7 +1524,8 @@ async function streamEvents(controller, args) {
1485
1524
  nodeName: isEndNode ? "__end__" : nodeName,
1486
1525
  state: state.values,
1487
1526
  running: !shouldExit,
1488
- active: false
1527
+ active: false,
1528
+ includeMessages: true
1489
1529
  }));
1490
1530
  return Promise.resolve();
1491
1531
  } catch (e) {
@@ -1498,13 +1538,20 @@ async function streamEvents(controller, args) {
1498
1538
  }
1499
1539
  }
1500
1540
  __name(streamEvents, "streamEvents");
1501
- function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active }) {
1502
- const stateWithoutMessages = Object.keys(state).reduce((acc, key) => {
1503
- if (key !== "messages") {
1504
- acc[key] = state[key];
1505
- }
1506
- return acc;
1507
- }, {});
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
1555
  return JSON.stringify({
1509
1556
  event: LangGraphEventTypes.OnCopilotKitStateSync,
1510
1557
  thread_id: threadId,
@@ -1512,7 +1559,7 @@ function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, runnin
1512
1559
  agent_name: agentName,
1513
1560
  node_name: nodeName,
1514
1561
  active,
1515
- state: stateWithoutMessages,
1562
+ state,
1516
1563
  running,
1517
1564
  role: "assistant"
1518
1565
  }) + "\n";
@@ -1588,134 +1635,159 @@ function langGraphDefaultMergeState(state, messages, actions, agentName) {
1588
1635
  if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
1589
1636
  messages = messages.slice(1);
1590
1637
  }
1591
- const mergedMessages = state.messages || [];
1592
- const existingMessageIds = new Set(mergedMessages.map((message) => message.id));
1593
- const existingToolCallResults = /* @__PURE__ */ new Set();
1594
- for (const message of mergedMessages) {
1595
- if ("tool_call_id" in message) {
1596
- existingToolCallResults.add(message.tool_call_id);
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
+ }
1597
1658
  }
1598
1659
  }
1599
1660
  for (const message of messages) {
1600
- if ("tool_calls" in message && message.tool_calls.length > 0 && message.tool_calls[0].name === agentName) {
1601
- continue;
1661
+ let content = message.content;
1662
+ if (content instanceof Array) {
1663
+ content = content[0];
1602
1664
  }
1603
- if ("name" in message && message.name === agentName) {
1604
- continue;
1665
+ if (content instanceof Object) {
1666
+ content = content.text;
1605
1667
  }
1606
- if (!existingMessageIds.has(message.id)) {
1607
- if ("tool_call_id" in message && existingToolCallResults.has(message.tool_call_id)) {
1608
- console.warn("Warning: Duplicate tool call result, skipping:", message.tool_call_id);
1609
- continue;
1610
- }
1611
- mergedMessages.push(message);
1612
- } else {
1613
- for (let i = 0; i < mergedMessages.length; i++) {
1614
- if (mergedMessages[i].id === message.id && message.role === "assistant") {
1615
- if (("tool_calls" in mergedMessages[i] || "additional_kwargs" in mergedMessages[i]) && mergedMessages[i].content) {
1616
- message.tool_calls = mergedMessages[i]["tool_calls"];
1617
- message.additional_kwargs = mergedMessages[i].additional_kwargs;
1618
- }
1619
- mergedMessages[i] = message;
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
+ });
1620
1689
  }
1690
+ } else {
1691
+ result.push({
1692
+ role: "assistant",
1693
+ content,
1694
+ id: message.id,
1695
+ parentMessageId: message.id
1696
+ });
1621
1697
  }
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
+ });
1622
1706
  }
1623
1707
  }
1624
- for (let i = 0; i < mergedMessages.length - 1; i++) {
1625
- const currentMessage = mergedMessages[i];
1626
- const nextMessage = mergedMessages[i + 1];
1627
- if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0 && "tool_call_id" in nextMessage) {
1628
- nextMessage.tool_call_id = currentMessage.tool_calls[0].id;
1708
+ const resultsDict = {};
1709
+ for (const msg of result) {
1710
+ if (msg.actionExecutionId) {
1711
+ resultsDict[msg.actionExecutionId] = msg;
1629
1712
  }
1630
1713
  }
1631
- const correctedMessages = [];
1632
- for (let i = 0; i < mergedMessages.length; i++) {
1633
- const currentMessage = mergedMessages[i];
1634
- const nextMessage = mergedMessages[i + 1] || null;
1635
- const prevMessage = mergedMessages[i - 1] || null;
1636
- if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0) {
1637
- if (!nextMessage) {
1638
- console.warn("No next message to auto-correct tool call, skipping:", currentMessage.tool_calls[0].id);
1639
- continue;
1640
- }
1641
- if (!("tool_call_id" in nextMessage) || nextMessage.tool_call_id !== currentMessage.tool_calls[0].id) {
1642
- const toolMessage = mergedMessages.find((m) => "tool_call_id" in m && m.tool_call_id === currentMessage.tool_calls[0].id);
1643
- if (toolMessage) {
1644
- console.warn("Auto-corrected tool call alignment issue:", currentMessage.tool_calls[0].id);
1645
- correctedMessages.push(currentMessage, toolMessage);
1646
- continue;
1647
- } else {
1648
- console.warn("No corresponding tool call result found for tool call, skipping:", currentMessage.tool_calls[0].id);
1649
- continue;
1650
- }
1651
- }
1652
- correctedMessages.push(currentMessage);
1653
- continue;
1714
+ const reorderedResult = [];
1715
+ for (const msg of result) {
1716
+ if (!("actionExecutionId" in msg)) {
1717
+ reorderedResult.push(msg);
1654
1718
  }
1655
- if ("tool_call_id" in currentMessage) {
1656
- if (!prevMessage || !("tool_calls" in prevMessage)) {
1657
- console.warn("No previous tool call, skipping tool call result:", currentMessage.id);
1658
- continue;
1659
- }
1660
- if (prevMessage.tool_calls && prevMessage.tool_calls[0].id !== currentMessage.tool_call_id) {
1661
- console.warn("Tool call id is incorrect, skipping tool call result:", currentMessage.id);
1662
- continue;
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);
1663
1725
  }
1664
- correctedMessages.push(currentMessage);
1665
- continue;
1666
1726
  }
1667
- correctedMessages.push(currentMessage);
1668
1727
  }
1669
- return {
1670
- ...state,
1671
- messages: correctedMessages,
1672
- copilotkit: {
1673
- actions
1674
- }
1675
- };
1728
+ return reorderedResult;
1676
1729
  }
1677
- __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1678
- function formatMessages(messages) {
1679
- return messages.map((message) => {
1680
- if (message.isTextMessage() && message.role === "assistant") {
1681
- return message;
1682
- }
1683
- if (message.isTextMessage() && message.role === "system") {
1684
- return message;
1685
- }
1686
- if (message.isTextMessage() && message.role === "user") {
1687
- return message;
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;
1688
1753
  }
1689
1754
  if (message.isActionExecutionMessage()) {
1690
- const toolCall = {
1691
- name: message.name,
1692
- args: message.arguments,
1693
- id: message.id
1694
- };
1695
- return {
1696
- type: message.type,
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
1769
  content: "",
1698
- tool_calls: [
1699
- toolCall
1700
- ],
1701
- role: MessageRole.assistant,
1702
- id: message.id
1703
- };
1770
+ tool_calls,
1771
+ role: MessageRole.assistant
1772
+ });
1773
+ continue;
1704
1774
  }
1705
1775
  if (message.isResultMessage()) {
1706
- return {
1776
+ result.push({
1707
1777
  type: message.type,
1708
1778
  content: message.result,
1709
1779
  id: message.id,
1710
1780
  tool_call_id: message.actionExecutionId,
1711
1781
  name: message.actionName,
1712
1782
  role: MessageRole.tool
1713
- };
1783
+ });
1784
+ continue;
1714
1785
  }
1715
1786
  throw new Error(`Unknown message type ${message.type}`);
1716
- });
1787
+ }
1788
+ return result;
1717
1789
  }
1718
- __name(formatMessages, "formatMessages");
1790
+ __name(copilotkitMessagesToLangChain, "copilotkitMessagesToLangChain");
1719
1791
 
1720
1792
  // src/lib/runtime/remote-action-constructors.ts
1721
1793
  function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
@@ -1725,7 +1797,7 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
1725
1797
  parameters: [],
1726
1798
  handler: async (_args) => {
1727
1799
  },
1728
- langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1800
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [] }) => {
1729
1801
  var _a;
1730
1802
  logger2.debug({
1731
1803
  actionName: agent.name
@@ -1751,7 +1823,10 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
1751
1823
  agent,
1752
1824
  threadId,
1753
1825
  nodeName,
1754
- messages,
1826
+ messages: [
1827
+ ...messages,
1828
+ ...additionalMessages
1829
+ ],
1755
1830
  state,
1756
1831
  properties: graphqlContext.properties,
1757
1832
  actions: actionInputsWithoutAgents.map((action) => ({
@@ -1833,7 +1908,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1833
1908
  parameters: [],
1834
1909
  handler: async (_args) => {
1835
1910
  },
1836
- langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1911
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [] }) => {
1837
1912
  var _a;
1838
1913
  logger2.debug({
1839
1914
  actionName: agent.name
@@ -1858,7 +1933,10 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1858
1933
  name,
1859
1934
  threadId,
1860
1935
  nodeName,
1861
- messages,
1936
+ messages: [
1937
+ ...messages,
1938
+ ...additionalMessages
1939
+ ],
1862
1940
  state,
1863
1941
  properties: graphqlContext.properties,
1864
1942
  actions: actionInputsWithoutAgents.map((action) => ({
@@ -2070,7 +2148,8 @@ function convertGqlInputToMessages(inputMessages) {
2070
2148
  id: message.id,
2071
2149
  createdAt: message.createdAt,
2072
2150
  role: message.textMessage.role,
2073
- content: message.textMessage.content
2151
+ content: message.textMessage.content,
2152
+ parentMessageId: message.textMessage.parentMessageId
2074
2153
  }));
2075
2154
  } else if (message.actionExecutionMessage) {
2076
2155
  messages.push(plainToInstance(ActionExecutionMessage, {
@@ -2078,7 +2157,7 @@ function convertGqlInputToMessages(inputMessages) {
2078
2157
  createdAt: message.createdAt,
2079
2158
  name: message.actionExecutionMessage.name,
2080
2159
  arguments: JSON.parse(message.actionExecutionMessage.arguments),
2081
- scope: message.actionExecutionMessage.scope
2160
+ parentMessageId: message.actionExecutionMessage.parentMessageId
2082
2161
  }));
2083
2162
  } else if (message.resultMessage) {
2084
2163
  messages.push(plainToInstance(ResultMessage, {
@@ -2381,6 +2460,7 @@ __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
2381
2460
  var telemetry_client_default = telemetryClient;
2382
2461
 
2383
2462
  // src/service-adapters/events.ts
2463
+ import { plainToInstance as plainToInstance2 } from "class-transformer";
2384
2464
  var RuntimeEventTypes;
2385
2465
  (function(RuntimeEventTypes2) {
2386
2466
  RuntimeEventTypes2["TextMessageStart"] = "TextMessageStart";
@@ -2396,52 +2476,74 @@ var RuntimeEventSubject = class extends ReplaySubject2 {
2396
2476
  constructor() {
2397
2477
  super();
2398
2478
  }
2399
- sendTextMessageStart(messageId) {
2479
+ sendTextMessageStart({ messageId, parentMessageId }) {
2400
2480
  this.next({
2401
2481
  type: "TextMessageStart",
2402
- messageId
2482
+ messageId,
2483
+ parentMessageId
2403
2484
  });
2404
2485
  }
2405
- sendTextMessageContent(content) {
2486
+ sendTextMessageContent({ messageId, content }) {
2406
2487
  this.next({
2407
2488
  type: "TextMessageContent",
2408
- content
2489
+ content,
2490
+ messageId
2409
2491
  });
2410
2492
  }
2411
- sendTextMessageEnd() {
2493
+ sendTextMessageEnd({ messageId }) {
2412
2494
  this.next({
2413
- type: "TextMessageEnd"
2495
+ type: "TextMessageEnd",
2496
+ messageId
2414
2497
  });
2415
2498
  }
2416
2499
  sendTextMessage(messageId, content) {
2417
- this.sendTextMessageStart(messageId);
2418
- this.sendTextMessageContent(content);
2419
- this.sendTextMessageEnd();
2500
+ this.sendTextMessageStart({
2501
+ messageId
2502
+ });
2503
+ this.sendTextMessageContent({
2504
+ messageId,
2505
+ content
2506
+ });
2507
+ this.sendTextMessageEnd({
2508
+ messageId
2509
+ });
2420
2510
  }
2421
- sendActionExecutionStart(actionExecutionId, actionName) {
2511
+ sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId }) {
2422
2512
  this.next({
2423
2513
  type: "ActionExecutionStart",
2424
2514
  actionExecutionId,
2425
- actionName
2515
+ actionName,
2516
+ parentMessageId
2426
2517
  });
2427
2518
  }
2428
- sendActionExecutionArgs(args) {
2519
+ sendActionExecutionArgs({ actionExecutionId, args }) {
2429
2520
  this.next({
2430
2521
  type: "ActionExecutionArgs",
2431
- args
2522
+ args,
2523
+ actionExecutionId
2432
2524
  });
2433
2525
  }
2434
- sendActionExecutionEnd() {
2526
+ sendActionExecutionEnd({ actionExecutionId }) {
2435
2527
  this.next({
2436
- type: "ActionExecutionEnd"
2528
+ type: "ActionExecutionEnd",
2529
+ actionExecutionId
2437
2530
  });
2438
2531
  }
2439
- sendActionExecution(actionExecutionId, toolName, args) {
2440
- this.sendActionExecutionStart(actionExecutionId, toolName);
2441
- this.sendActionExecutionArgs(args);
2442
- this.sendActionExecutionEnd();
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
+ });
2443
2545
  }
2444
- sendActionExecutionResult(actionExecutionId, actionName, result) {
2546
+ sendActionExecutionResult({ actionExecutionId, actionName, result }) {
2445
2547
  this.next({
2446
2548
  type: "ActionExecutionResult",
2447
2549
  actionName,
@@ -2449,7 +2551,7 @@ var RuntimeEventSubject = class extends ReplaySubject2 {
2449
2551
  result
2450
2552
  });
2451
2553
  }
2452
- sendAgentStateMessage(threadId, agentName, nodeName, runId, active, role, state, running) {
2554
+ sendAgentStateMessage({ threadId, agentName, nodeName, runId, active, role, state, running }) {
2453
2555
  this.next({
2454
2556
  type: "AgentStateMessage",
2455
2557
  threadId,
@@ -2486,22 +2588,13 @@ var RuntimeEventSource = class {
2486
2588
  this.sendErrorMessageToChat();
2487
2589
  });
2488
2590
  return this.eventStream$.pipe(
2489
- // mark tools for server side execution
2490
- map((event) => {
2491
- if (event.type === "ActionExecutionStart") {
2492
- if (event.scope !== "passThrough") {
2493
- event.scope = serverSideActions.find((action) => action.name === event.actionName) ? "server" : "client";
2494
- }
2495
- }
2496
- return event;
2497
- }),
2498
2591
  // track state
2499
2592
  scan2((acc, event) => {
2500
2593
  acc = {
2501
2594
  ...acc
2502
2595
  };
2503
2596
  if (event.type === "ActionExecutionStart") {
2504
- acc.callActionServerSide = event.scope === "server";
2597
+ acc.callActionServerSide = serverSideActions.find((action) => action.name === event.actionName) !== void 0;
2505
2598
  acc.args = "";
2506
2599
  acc.actionExecutionId = event.actionExecutionId;
2507
2600
  if (acc.callActionServerSide) {
@@ -2555,10 +2648,33 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
2555
2648
  }
2556
2649
  }
2557
2650
  if (isLangGraphAgentAction(action)) {
2558
- eventStream$.sendActionExecutionResult(actionExecutionId, action.name, `${action.name} agent started`);
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
+ });
2559
2671
  const stream = await action.langGraphAgentHandler({
2560
2672
  name: action.name,
2561
- actionInputsWithoutAgents
2673
+ actionInputsWithoutAgents,
2674
+ additionalMessages: [
2675
+ agentExecution,
2676
+ agentExecutionResult
2677
+ ]
2562
2678
  });
2563
2679
  from2(stream).subscribe({
2564
2680
  next: (event) => eventStream$.next(event),
@@ -2581,7 +2697,7 @@ __name(executeAction, "executeAction");
2581
2697
 
2582
2698
  // src/graphql/resolvers/copilot.resolver.ts
2583
2699
  import { GraphQLJSONObject } from "graphql-scalars";
2584
- import { plainToInstance as plainToInstance2 } from "class-transformer";
2700
+ import { plainToInstance as plainToInstance3 } from "class-transformer";
2585
2701
  import { GraphQLError } from "graphql";
2586
2702
  import { randomId as randomId4 } from "@copilotkit/shared";
2587
2703
  function _ts_decorate12(decorators, target, key, desc) {
@@ -2744,7 +2860,7 @@ var CopilotResolver = class {
2744
2860
  reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`
2745
2861
  });
2746
2862
  outputMessages = [
2747
- plainToInstance2(TextMessage, {
2863
+ plainToInstance3(TextMessage, {
2748
2864
  id: randomId4(),
2749
2865
  createdAt: /* @__PURE__ */ new Date(),
2750
2866
  content: result.reason,
@@ -2793,12 +2909,15 @@ var CopilotResolver = class {
2793
2909
  // skip until this message start event
2794
2910
  skipWhile((e) => e !== event),
2795
2911
  // take until the message end event
2796
- takeWhile((e) => e.type != RuntimeEventTypes.TextMessageEnd)
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)
2797
2915
  );
2798
2916
  const streamingTextStatus = new Subject();
2799
2917
  const messageId = event.messageId;
2800
2918
  pushMessage({
2801
2919
  id: messageId,
2920
+ parentMessageId: event.parentMessageId,
2802
2921
  status: firstValueFrom2(streamingTextStatus),
2803
2922
  createdAt: /* @__PURE__ */ new Date(),
2804
2923
  role: MessageRole.assistant,
@@ -2811,7 +2930,7 @@ var CopilotResolver = class {
2811
2930
  reason,
2812
2931
  messageId: messageId2
2813
2932
  }, "Text streaming interrupted");
2814
- streamingTextStatus.next(plainToInstance2(FailedMessageStatus, {
2933
+ streamingTextStatus.next(plainToInstance3(FailedMessageStatus, {
2815
2934
  reason
2816
2935
  }));
2817
2936
  responseStatus$.next(new MessageStreamInterruptedResponse({
@@ -2844,7 +2963,7 @@ var CopilotResolver = class {
2844
2963
  streamingTextStatus.next(new SuccessMessageStatus());
2845
2964
  stopStreamingText();
2846
2965
  textSubscription == null ? void 0 : textSubscription.unsubscribe();
2847
- outputMessages.push(plainToInstance2(TextMessage, {
2966
+ outputMessages.push(plainToInstance3(TextMessage, {
2848
2967
  id: messageId,
2849
2968
  createdAt: /* @__PURE__ */ new Date(),
2850
2969
  content: textChunks.join(""),
@@ -2857,14 +2976,20 @@ var CopilotResolver = class {
2857
2976
  break;
2858
2977
  case RuntimeEventTypes.ActionExecutionStart:
2859
2978
  logger2.debug("Action execution start event received");
2860
- const actionExecutionArgumentStream = eventStream.pipe(skipWhile((e) => e !== event), takeWhile((e) => e.type != RuntimeEventTypes.ActionExecutionEnd));
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
+ );
2861
2986
  const streamingArgumentsStatus = new Subject();
2862
2987
  pushMessage({
2863
2988
  id: event.actionExecutionId,
2989
+ parentMessageId: event.parentMessageId,
2864
2990
  status: firstValueFrom2(streamingArgumentsStatus),
2865
2991
  createdAt: /* @__PURE__ */ new Date(),
2866
2992
  name: event.actionName,
2867
- scope: event.scope,
2868
2993
  arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
2869
2994
  logger2.debug("Action execution argument stream created");
2870
2995
  const argumentChunks = [];
@@ -2880,7 +3005,7 @@ var CopilotResolver = class {
2880
3005
  logger2.error({
2881
3006
  err
2882
3007
  }, "Error in action execution argument stream");
2883
- streamingArgumentsStatus.next(plainToInstance2(FailedMessageStatus, {
3008
+ streamingArgumentsStatus.next(plainToInstance3(FailedMessageStatus, {
2884
3009
  reason: "An unknown error has occurred in the action execution argument stream"
2885
3010
  }));
2886
3011
  stopStreamingArguments();
@@ -2891,11 +3016,10 @@ var CopilotResolver = class {
2891
3016
  streamingArgumentsStatus.next(new SuccessMessageStatus());
2892
3017
  stopStreamingArguments();
2893
3018
  actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
2894
- outputMessages.push(plainToInstance2(ActionExecutionMessage, {
3019
+ outputMessages.push(plainToInstance3(ActionExecutionMessage, {
2895
3020
  id: event.actionExecutionId,
2896
3021
  createdAt: /* @__PURE__ */ new Date(),
2897
3022
  name: event.actionName,
2898
- scope: event.scope,
2899
3023
  arguments: argumentChunks.join("")
2900
3024
  }));
2901
3025
  }
@@ -2908,15 +3032,15 @@ var CopilotResolver = class {
2908
3032
  result: event.result
2909
3033
  }, "Action execution result event received");
2910
3034
  pushMessage({
2911
- id: randomId4(),
3035
+ id: "result-" + event.actionExecutionId,
2912
3036
  status: new SuccessMessageStatus(),
2913
3037
  createdAt: /* @__PURE__ */ new Date(),
2914
3038
  actionExecutionId: event.actionExecutionId,
2915
3039
  actionName: event.actionName,
2916
3040
  result: event.result
2917
3041
  });
2918
- outputMessages.push(plainToInstance2(ResultMessage, {
2919
- id: randomId4(),
3042
+ outputMessages.push(plainToInstance3(ResultMessage, {
3043
+ id: "result-" + event.actionExecutionId,
2920
3044
  createdAt: /* @__PURE__ */ new Date(),
2921
3045
  actionExecutionId: event.actionExecutionId,
2922
3046
  actionName: event.actionName,
@@ -2940,7 +3064,7 @@ var CopilotResolver = class {
2940
3064
  role: MessageRole.assistant,
2941
3065
  createdAt: /* @__PURE__ */ new Date()
2942
3066
  });
2943
- outputMessages.push(plainToInstance2(AgentStateMessage, {
3067
+ outputMessages.push(plainToInstance3(AgentStateMessage, {
2944
3068
  id: randomId4(),
2945
3069
  threadId: event.threadId,
2946
3070
  agentName: event.agentName,
@@ -3152,4 +3276,4 @@ export {
3152
3276
  getCommonConfig,
3153
3277
  copilotRuntimeNodeHttpEndpoint
3154
3278
  };
3155
- //# sourceMappingURL=chunk-44ICGB7P.mjs.map
3279
+ //# sourceMappingURL=chunk-FVYNRYIB.mjs.map