@copilotkit/runtime 0.37.0 → 0.38.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/.turbo/turbo-build.log +69 -54
  2. package/CHANGELOG.md +11 -0
  3. package/__snapshots__/schema/schema.graphql +15 -4
  4. package/dist/{chunk-2CCVVJDU.mjs → chunk-2PJG3NAC.mjs} +13 -15
  5. package/dist/chunk-2PJG3NAC.mjs.map +1 -0
  6. package/dist/{chunk-NFCPM5AM.mjs → chunk-6NZ4UMOD.mjs} +4 -4
  7. package/dist/chunk-6NZ4UMOD.mjs.map +1 -0
  8. package/dist/{chunk-XPAUPJMW.mjs → chunk-6YGDE3YI.mjs} +432 -220
  9. package/dist/chunk-6YGDE3YI.mjs.map +1 -0
  10. package/dist/chunk-BYB2LNMK.mjs +152 -0
  11. package/dist/chunk-BYB2LNMK.mjs.map +1 -0
  12. package/dist/{chunk-7IFP53C6.mjs → chunk-FRK6BXXV.mjs} +49 -11
  13. package/dist/chunk-FRK6BXXV.mjs.map +1 -0
  14. package/dist/{chunk-5HGYI6EG.mjs → chunk-JBDOA7MK.mjs} +34 -15
  15. package/dist/chunk-JBDOA7MK.mjs.map +1 -0
  16. package/dist/{chunk-4UA4RB4C.mjs → chunk-JIKPSUGQ.mjs} +45 -76
  17. package/dist/chunk-JIKPSUGQ.mjs.map +1 -0
  18. package/dist/{chunk-BLTAUVRP.mjs → chunk-OZMCHYYR.mjs} +5 -3
  19. package/dist/{chunk-BLTAUVRP.mjs.map → chunk-OZMCHYYR.mjs.map} +1 -1
  20. package/dist/chunk-RHQLCJGG.mjs +7 -0
  21. package/dist/chunk-RHQLCJGG.mjs.map +1 -0
  22. package/dist/failed-response-status-reasons-0ab19e06.d.ts +49 -0
  23. package/dist/graphql/types/base/index.mjs +2 -1
  24. package/dist/graphql/types/converted/index.mjs +3 -2
  25. package/dist/{index-f0875df3.d.ts → index-0e75acd2.d.ts} +86 -59
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +536 -169
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +16 -13
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{langchain-adapter-9ce103f3.d.ts → langchain-adapter-a02d1d38.d.ts} +4 -4
  32. package/dist/{langserve-fd5066ee.d.ts → langserve-75ebbc38.d.ts} +25 -9
  33. package/dist/lib/cloud/index.d.ts +6 -0
  34. package/dist/lib/cloud/index.js +18 -0
  35. package/dist/lib/cloud/index.js.map +1 -0
  36. package/dist/lib/cloud/index.mjs +1 -0
  37. package/dist/lib/cloud/index.mjs.map +1 -0
  38. package/dist/lib/index.d.ts +6 -4
  39. package/dist/lib/index.js +530 -169
  40. package/dist/lib/index.js.map +1 -1
  41. package/dist/lib/index.mjs +9 -13
  42. package/dist/lib/integrations/index.d.ts +5 -3
  43. package/dist/lib/integrations/index.js +426 -64
  44. package/dist/lib/integrations/index.js.map +1 -1
  45. package/dist/lib/integrations/index.mjs +7 -5
  46. package/dist/lib/integrations/node-http/index.d.ts +4 -2
  47. package/dist/lib/integrations/node-http/index.js +416 -52
  48. package/dist/lib/integrations/node-http/index.js.map +1 -1
  49. package/dist/lib/integrations/node-http/index.mjs +6 -4
  50. package/dist/pages-router-e81920d5.d.ts +21 -0
  51. package/dist/service-adapters/index.d.ts +2 -2
  52. package/dist/service-adapters/index.js +82 -25
  53. package/dist/service-adapters/index.js.map +1 -1
  54. package/dist/service-adapters/index.mjs +5 -4
  55. package/dist/utils/index.d.ts +1 -0
  56. package/dist/utils/index.js +174 -0
  57. package/dist/utils/index.js.map +1 -0
  58. package/dist/utils/index.mjs +12 -0
  59. package/dist/utils/index.mjs.map +1 -0
  60. package/package.json +6 -4
  61. package/src/graphql/inputs/cloud-guardrails.input.ts +2 -5
  62. package/src/graphql/inputs/cloud.input.ts +2 -2
  63. package/src/graphql/resolvers/copilot.resolver.ts +340 -30
  64. package/src/graphql/types/response-status.type.ts +16 -2
  65. package/src/index.ts +1 -0
  66. package/src/lib/cloud/index.ts +4 -0
  67. package/src/lib/copilot-runtime.ts +116 -70
  68. package/src/lib/index.ts +0 -1
  69. package/src/lib/integrations/nextjs/app-router.ts +9 -17
  70. package/src/lib/integrations/nextjs/pages-router.ts +9 -15
  71. package/src/lib/integrations/node-http/index.ts +6 -14
  72. package/src/lib/integrations/shared.ts +38 -18
  73. package/src/lib/logger.ts +28 -0
  74. package/src/service-adapters/events.ts +20 -2
  75. package/src/service-adapters/experimental/groq/groq-adapter.ts +3 -1
  76. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +3 -1
  77. package/src/service-adapters/google/google-genai-adapter.ts +6 -1
  78. package/src/service-adapters/google/utils.ts +1 -1
  79. package/src/service-adapters/index.ts +1 -1
  80. package/src/service-adapters/langchain/langchain-adapter.ts +8 -9
  81. package/src/service-adapters/langchain/langserve.ts +10 -4
  82. package/src/service-adapters/langchain/utils.ts +58 -9
  83. package/src/service-adapters/openai/openai-adapter.ts +8 -7
  84. package/src/service-adapters/openai/openai-assistant-adapter.ts +6 -8
  85. package/src/service-adapters/service-adapter.ts +1 -2
  86. package/src/utils/failed-response-status-reasons.ts +48 -0
  87. package/src/utils/index.ts +1 -0
  88. package/dist/chunk-2CCVVJDU.mjs.map +0 -1
  89. package/dist/chunk-4UA4RB4C.mjs.map +0 -1
  90. package/dist/chunk-5HGYI6EG.mjs.map +0 -1
  91. package/dist/chunk-7IFP53C6.mjs.map +0 -1
  92. package/dist/chunk-NFCPM5AM.mjs.map +0 -1
  93. package/dist/chunk-XPAUPJMW.mjs.map +0 -1
  94. package/dist/pages-router-b6bc6c60.d.ts +0 -30
  95. package/src/lib/copilot-cloud.ts +0 -63
  96. package/src/lib/guardrails.ts +0 -3
package/dist/index.js CHANGED
@@ -30,14 +30,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- CopilotBackend: () => CopilotBackend,
34
- CopilotCloud: () => CopilotCloud,
35
33
  CopilotRuntime: () => CopilotRuntime,
36
34
  GoogleGenerativeAIAdapter: () => GoogleGenerativeAIAdapter,
35
+ GuardrailsValidationFailureResponse: () => GuardrailsValidationFailureResponse,
37
36
  LangChainAdapter: () => LangChainAdapter,
37
+ MessageStreamInterruptedResponse: () => MessageStreamInterruptedResponse,
38
38
  OpenAIAdapter: () => OpenAIAdapter,
39
39
  OpenAIAssistantAdapter: () => OpenAIAssistantAdapter,
40
- RemoteCopilotCloud: () => RemoteCopilotCloud,
40
+ UnknownErrorResponse: () => UnknownErrorResponse,
41
41
  buildSchema: () => buildSchema,
42
42
  config: () => config,
43
43
  copilotRuntimeNextJSAppRouterEndpoint: () => copilotRuntimeNextJSAppRouterEndpoint,
@@ -51,7 +51,7 @@ module.exports = __toCommonJS(src_exports);
51
51
  var import_reflect_metadata = require("reflect-metadata");
52
52
 
53
53
  // src/lib/copilot-runtime.ts
54
- var import_shared2 = require("@copilotkit/shared");
54
+ var import_shared = require("@copilotkit/shared");
55
55
 
56
56
  // src/service-adapters/openai/openai-adapter.ts
57
57
  var import_openai = __toESM(require("openai"));
@@ -257,6 +257,7 @@ function convertSystemMessageToAssistantAPI(message) {
257
257
  __name(convertSystemMessageToAssistantAPI, "convertSystemMessageToAssistantAPI");
258
258
 
259
259
  // src/service-adapters/openai/openai-adapter.ts
260
+ var import_nanoid = require("nanoid");
260
261
  var DEFAULT_MODEL = "gpt-4o";
261
262
  var OpenAIAdapter = class {
262
263
  model = DEFAULT_MODEL;
@@ -270,7 +271,8 @@ var OpenAIAdapter = class {
270
271
  this.model = params.model;
271
272
  }
272
273
  }
273
- async process({ model = this.model, messages, actions, eventSource }) {
274
+ async process(request) {
275
+ const { threadId, model = this.model, messages, actions, eventSource } = request;
274
276
  const tools = actions.map(convertActionInputToOpenAITool);
275
277
  let openaiMessages = messages.map(convertMessageToOpenAIMessage);
276
278
  openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
@@ -317,7 +319,9 @@ var OpenAIAdapter = class {
317
319
  }
318
320
  eventStream$.complete();
319
321
  });
320
- return {};
322
+ return {
323
+ threadId: threadId || (0, import_nanoid.nanoid)()
324
+ };
321
325
  }
322
326
  };
323
327
  __name(OpenAIAdapter, "OpenAIAdapter");
@@ -335,8 +339,9 @@ var OpenAIAssistantAdapter = class {
335
339
  this.fileSearchEnabled = params.fileSearchEnabled === false || true;
336
340
  this.assistantId = params.assistantId;
337
341
  }
338
- async process({ messages, actions, eventSource, threadId, runId }) {
339
- threadId || (threadId = (await this.openai.beta.threads.create()).id);
342
+ async process(request) {
343
+ const { messages, actions, eventSource, runId } = request;
344
+ let threadId = request.threadId || (await this.openai.beta.threads.create()).id;
340
345
  const lastMessage = messages.at(-1);
341
346
  let nextRunId = void 0;
342
347
  if (lastMessage instanceof ResultMessage && runId) {
@@ -506,7 +511,7 @@ function convertMessageToGoogleGenAIMessage(message) {
506
511
  };
507
512
  } else if (message instanceof ResultMessage) {
508
513
  return {
509
- role: "model",
514
+ role: "function",
510
515
  parts: [
511
516
  {
512
517
  functionResponse: {
@@ -561,7 +566,7 @@ function tryParseJson(str) {
561
566
  __name(tryParseJson, "tryParseJson");
562
567
 
563
568
  // src/service-adapters/google/google-genai-adapter.ts
564
- var import_nanoid = require("nanoid");
569
+ var import_nanoid2 = require("nanoid");
565
570
  var GoogleGenerativeAIAdapter = class {
566
571
  model;
567
572
  constructor(options) {
@@ -623,9 +628,12 @@ var GoogleGenerativeAIAdapter = class {
623
628
  let isTextMessage = false;
624
629
  for await (const chunk of result.stream) {
625
630
  const chunkText = chunk.text();
631
+ if (chunkText === "") {
632
+ continue;
633
+ }
626
634
  if (!isTextMessage) {
627
635
  isTextMessage = true;
628
- eventStream$.sendTextMessageStart((0, import_nanoid.nanoid)());
636
+ eventStream$.sendTextMessageStart((0, import_nanoid2.nanoid)());
629
637
  }
630
638
  eventStream$.sendTextMessageContent(chunkText);
631
639
  }
@@ -635,12 +643,14 @@ var GoogleGenerativeAIAdapter = class {
635
643
  let calls = (await result.response).functionCalls();
636
644
  if (calls) {
637
645
  for (let call of calls) {
638
- eventStream$.sendActionExecution((0, import_nanoid.nanoid)(), call.name, JSON.stringify(replaceNewlinesInObject(call.args)));
646
+ eventStream$.sendActionExecution((0, import_nanoid2.nanoid)(), call.name, JSON.stringify(replaceNewlinesInObject(call.args)));
639
647
  }
640
648
  }
641
649
  eventStream$.complete();
642
650
  });
643
- return {};
651
+ return {
652
+ threadId: request.threadId || (0, import_nanoid2.nanoid)()
653
+ };
644
654
  }
645
655
  };
646
656
  __name(GoogleGenerativeAIAdapter, "GoogleGenerativeAIAdapter");
@@ -666,7 +676,7 @@ __name(replaceNewlinesInObject, "replaceNewlinesInObject");
666
676
  var import_messages = require("@langchain/core/messages");
667
677
  var import_tools = require("@langchain/core/tools");
668
678
  var import_zod = require("zod");
669
- var import_nanoid2 = require("nanoid");
679
+ var import_nanoid3 = require("nanoid");
670
680
  function convertMessageToLangChainMessage(message) {
671
681
  if (message instanceof TextMessage) {
672
682
  if (message.role == "user") {
@@ -730,31 +740,59 @@ function convertActionInputToLangChainTool(actionInput) {
730
740
  });
731
741
  }
732
742
  __name(convertActionInputToLangChainTool, "convertActionInputToLangChainTool");
743
+ function getConstructorName(object) {
744
+ if (object && typeof object === "object" && object.constructor && object.constructor.name) {
745
+ return object.constructor.name;
746
+ }
747
+ return "";
748
+ }
749
+ __name(getConstructorName, "getConstructorName");
750
+ function isAIMessage(message) {
751
+ return getConstructorName(message) === "AIMessage";
752
+ }
753
+ __name(isAIMessage, "isAIMessage");
754
+ function isAIMessageChunk(message) {
755
+ return getConstructorName(message) === "AIMessageChunk";
756
+ }
757
+ __name(isAIMessageChunk, "isAIMessageChunk");
758
+ function isBaseMessageChunk(message) {
759
+ return getConstructorName(message) === "BaseMessageChunk";
760
+ }
761
+ __name(isBaseMessageChunk, "isBaseMessageChunk");
762
+ function maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution) {
763
+ if (actionExecution) {
764
+ eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, "Sending a message");
765
+ }
766
+ }
767
+ __name(maybeSendActionExecutionResultIsMessage, "maybeSendActionExecutionResultIsMessage");
733
768
  async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
734
769
  var _a, _b, _c, _d, _e, _f, _g, _h;
735
770
  if (typeof result === "string") {
736
771
  if (!actionExecution) {
737
- eventStream$.sendTextMessage((0, import_nanoid2.nanoid)(), result);
772
+ eventStream$.sendTextMessage((0, import_nanoid3.nanoid)(), result);
738
773
  } else {
739
774
  eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);
740
775
  }
741
- } else if (result instanceof import_messages.AIMessage) {
776
+ } else if (isAIMessage(result)) {
777
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
742
778
  if (result.content) {
743
- eventStream$.sendTextMessage((0, import_nanoid2.nanoid)(), result.content);
779
+ eventStream$.sendTextMessage((0, import_nanoid3.nanoid)(), result.content);
744
780
  }
745
781
  for (const toolCall of result.tool_calls) {
746
- eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid2.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
782
+ eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid3.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
747
783
  }
748
- } else if (result instanceof import_messages.BaseMessageChunk) {
784
+ } else if (isBaseMessageChunk(result)) {
785
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
749
786
  if ((_a = result.lc_kwargs) == null ? void 0 : _a.content) {
750
- eventStream$.sendTextMessage((0, import_nanoid2.nanoid)(), result.content);
787
+ eventStream$.sendTextMessage((0, import_nanoid3.nanoid)(), result.content);
751
788
  }
752
789
  if ((_b = result.lc_kwargs) == null ? void 0 : _b.tool_calls) {
753
790
  for (const toolCall of (_c = result.lc_kwargs) == null ? void 0 : _c.tool_calls) {
754
- eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid2.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
791
+ eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid3.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
755
792
  }
756
793
  }
757
- } else if ("getReader" in result) {
794
+ } else if (result && "getReader" in result) {
795
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
758
796
  let reader = result.getReader();
759
797
  let mode = null;
760
798
  while (true) {
@@ -764,14 +802,14 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
764
802
  let toolCallId = void 0;
765
803
  let toolCallArgs = void 0;
766
804
  let hasToolCall = false;
767
- let content = value.content;
768
- if (value instanceof import_messages.AIMessageChunk) {
805
+ let content = value == null ? void 0 : value.content;
806
+ if (isAIMessageChunk(value)) {
769
807
  let chunk = (_d = value.tool_call_chunks) == null ? void 0 : _d[0];
770
808
  toolCallName = chunk == null ? void 0 : chunk.name;
771
809
  toolCallId = chunk == null ? void 0 : chunk.id;
772
810
  toolCallArgs = chunk == null ? void 0 : chunk.args;
773
811
  hasToolCall = chunk != void 0;
774
- } else if (value instanceof import_messages.BaseMessageChunk) {
812
+ } else if (isBaseMessageChunk(value)) {
775
813
  let chunk = (_f = (_e = value.additional_kwargs) == null ? void 0 : _e.tool_calls) == null ? void 0 : _f[0];
776
814
  toolCallName = (_g = chunk == null ? void 0 : chunk.function) == null ? void 0 : _g.name;
777
815
  toolCallId = chunk == null ? void 0 : chunk.id;
@@ -794,7 +832,7 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
794
832
  eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
795
833
  } else if (content) {
796
834
  mode = "message";
797
- eventStream$.sendTextMessageStart((0, import_nanoid2.nanoid)());
835
+ eventStream$.sendTextMessageStart((0, import_nanoid3.nanoid)());
798
836
  }
799
837
  }
800
838
  if (mode === "message" && content) {
@@ -808,15 +846,26 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
808
846
  }
809
847
  }
810
848
  } else if (actionExecution) {
811
- eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, JSON.stringify(result));
849
+ eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, encodeResult(result));
812
850
  } else {
813
851
  throw new Error("Invalid return type from LangChain function.");
814
852
  }
815
853
  eventStream$.complete();
816
854
  }
817
855
  __name(streamLangChainResponse, "streamLangChainResponse");
856
+ function encodeResult(result) {
857
+ if (result === void 0) {
858
+ return "";
859
+ } else if (typeof result === "string") {
860
+ return result;
861
+ } else {
862
+ return JSON.stringify(result);
863
+ }
864
+ }
865
+ __name(encodeResult, "encodeResult");
818
866
 
819
867
  // src/service-adapters/langchain/langchain-adapter.ts
868
+ var import_nanoid4 = require("nanoid");
820
869
  var LangChainAdapter = class {
821
870
  options;
822
871
  /**
@@ -825,7 +874,8 @@ var LangChainAdapter = class {
825
874
  constructor(options) {
826
875
  this.options = options;
827
876
  }
828
- async process({ eventSource, model, actions, messages, threadId, runId }) {
877
+ async process(request) {
878
+ const { eventSource, model, actions, messages, threadId, runId } = request;
829
879
  const result = await this.options.chainFn({
830
880
  messages: messages.map(convertMessageToLangChainMessage),
831
881
  tools: actions.map(convertActionInputToLangChainTool),
@@ -839,7 +889,9 @@ var LangChainAdapter = class {
839
889
  eventStream$
840
890
  });
841
891
  });
842
- return {};
892
+ return {
893
+ threadId: threadId || (0, import_nanoid4.nanoid)()
894
+ };
843
895
  }
844
896
  };
845
897
  __name(LangChainAdapter, "LangChainAdapter");
@@ -847,6 +899,11 @@ __name(LangChainAdapter, "LangChainAdapter");
847
899
  // src/service-adapters/langchain/langserve.ts
848
900
  var import_remote = require("langchain/runnables/remote");
849
901
  var RemoteChain = class {
902
+ name;
903
+ description;
904
+ chainUrl;
905
+ parameters;
906
+ parameterType;
850
907
  constructor(options) {
851
908
  this.name = options.name;
852
909
  this.description = options.description;
@@ -917,50 +974,6 @@ var RemoteChain = class {
917
974
  };
918
975
  __name(RemoteChain, "RemoteChain");
919
976
 
920
- // src/lib/copilot-cloud.ts
921
- var import_shared = require("@copilotkit/shared");
922
- var CopilotCloud = class {
923
- };
924
- __name(CopilotCloud, "CopilotCloud");
925
- var RemoteCopilotCloud = class extends CopilotCloud {
926
- cloudApiUrl;
927
- constructor(cloudApiUrl = import_shared.COPILOT_CLOUD_API_URL) {
928
- super();
929
- this.cloudApiUrl = cloudApiUrl;
930
- }
931
- async checkGuardrailsInput({ cloud, publicApiKey, messages }) {
932
- const url = `${this.cloudApiUrl}/${import_shared.COPILOT_CLOUD_VERSION}/copilotkit/guardrails/input`;
933
- const response = await fetch(url, {
934
- method: "PUT",
935
- headers: {
936
- "Content-Type": "application/json",
937
- [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey
938
- },
939
- body: JSON.stringify({
940
- messages,
941
- cloud
942
- })
943
- });
944
- if (!response.ok) {
945
- let message = response.statusText;
946
- try {
947
- const json2 = await response.json();
948
- if (json2.message) {
949
- message = json2.message;
950
- }
951
- } catch (error) {
952
- }
953
- throw new Error("Failed to check input guardrails: " + message);
954
- }
955
- const json = await response.json();
956
- return {
957
- status: json.status,
958
- reason: json.reason
959
- };
960
- }
961
- };
962
- __name(RemoteCopilotCloud, "RemoteCopilotCloud");
963
-
964
977
  // src/service-adapters/events.ts
965
978
  var import_rxjs = require("rxjs");
966
979
  var RuntimeEventTypes;
@@ -1038,7 +1051,7 @@ var RuntimeEventSource = class {
1038
1051
  async stream(callback) {
1039
1052
  this.callback = callback;
1040
1053
  }
1041
- process(serversideActions) {
1054
+ process({ serversideActions, guardrailsResult$ }) {
1042
1055
  this.callback(this.eventStream$).catch((error) => {
1043
1056
  console.error("Error in event source callback", error);
1044
1057
  });
@@ -1074,7 +1087,7 @@ var RuntimeEventSource = class {
1074
1087
  (0, import_rxjs.concatMap)((eventWithState) => {
1075
1088
  if (eventWithState.event.type === "ActionExecutionEnd" && eventWithState.callActionServerSide) {
1076
1089
  const toolCallEventStream$ = new RuntimeEventSubject();
1077
- executeAction(toolCallEventStream$, eventWithState.action, eventWithState.args, eventWithState.actionExecutionId).catch((error) => {
1090
+ executeAction(toolCallEventStream$, guardrailsResult$ ? guardrailsResult$ : null, eventWithState.action, eventWithState.args, eventWithState.actionExecutionId).catch((error) => {
1078
1091
  console.error(error);
1079
1092
  });
1080
1093
  return (0, import_rxjs.concat)((0, import_rxjs.of)(eventWithState.event), toolCallEventStream$);
@@ -1086,7 +1099,14 @@ var RuntimeEventSource = class {
1086
1099
  }
1087
1100
  };
1088
1101
  __name(RuntimeEventSource, "RuntimeEventSource");
1089
- async function executeAction(eventStream$, action, actionArguments, actionExecutionId) {
1102
+ async function executeAction(eventStream$, guardrailsResult$, action, actionArguments, actionExecutionId) {
1103
+ if (guardrailsResult$) {
1104
+ const { status } = await (0, import_rxjs.firstValueFrom)(guardrailsResult$);
1105
+ if (status === "denied") {
1106
+ eventStream$.complete();
1107
+ return;
1108
+ }
1109
+ }
1090
1110
  let args = [];
1091
1111
  if (actionArguments) {
1092
1112
  args = JSON.parse(actionArguments);
@@ -1139,27 +1159,23 @@ __name(convertGqlInputToMessages, "convertGqlInputToMessages");
1139
1159
 
1140
1160
  // src/lib/copilot-runtime.ts
1141
1161
  var CopilotRuntime = class {
1142
- actions = [];
1162
+ actions;
1143
1163
  langserve = [];
1144
- debug = false;
1145
- copilotCloud;
1164
+ onBeforeRequest;
1165
+ onAfterRequest;
1146
1166
  constructor(params) {
1167
+ var _a, _b;
1147
1168
  this.actions = (params == null ? void 0 : params.actions) || [];
1148
1169
  for (const chain of (params == null ? void 0 : params.langserve) || []) {
1149
1170
  const remoteChain = new RemoteChain(chain);
1150
1171
  this.langserve.push(remoteChain.toAction());
1151
1172
  }
1152
- this.debug = (params == null ? void 0 : params.debug) || false;
1153
- this.copilotCloud = (params == null ? void 0 : params.copilotCloud) || new RemoteCopilotCloud();
1154
- }
1155
- addAction(action) {
1156
- this.removeAction(action.name);
1157
- this.actions.push(action);
1158
- }
1159
- removeAction(actionName) {
1160
- this.actions = this.actions.filter((f) => f.name !== actionName);
1173
+ this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
1174
+ this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
1161
1175
  }
1162
- async process({ serviceAdapter, messages, actions: clientSideActionsInput, threadId, runId, publicApiKey }) {
1176
+ async process(request) {
1177
+ var _a;
1178
+ const { serviceAdapter, messages, actions: clientSideActionsInput, threadId, runId, properties, outputMessagesPromise } = request;
1163
1179
  const langserveFunctions = [];
1164
1180
  for (const chainPromise of this.langserve) {
1165
1181
  try {
@@ -1169,31 +1185,54 @@ var CopilotRuntime = class {
1169
1185
  console.error("Error loading langserve chain:", error);
1170
1186
  }
1171
1187
  }
1172
- const serverSideActionsInput = [
1173
- ...this.actions,
1188
+ const configuredActions = typeof this.actions === "function" ? this.actions({
1189
+ properties
1190
+ }) : this.actions;
1191
+ const actions = [
1192
+ ...configuredActions,
1174
1193
  ...langserveFunctions
1175
- ].map((action) => ({
1194
+ ];
1195
+ const serverSideActionsInput = actions.map((action) => ({
1176
1196
  name: action.name,
1177
1197
  description: action.description,
1178
- jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters))
1198
+ jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters))
1179
1199
  }));
1180
- const actions = flattenToolCallsNoDuplicates([
1200
+ const actionInputs = flattenToolCallsNoDuplicates([
1181
1201
  ...serverSideActionsInput,
1182
1202
  ...clientSideActionsInput
1183
1203
  ]);
1204
+ const inputMessages = convertGqlInputToMessages(messages);
1205
+ await ((_a = this.onBeforeRequest) == null ? void 0 : _a.call(this, {
1206
+ threadId,
1207
+ runId,
1208
+ inputMessages,
1209
+ properties
1210
+ }));
1184
1211
  try {
1185
1212
  const eventSource = new RuntimeEventSource();
1186
1213
  const result = await serviceAdapter.process({
1187
- messages: convertGqlInputToMessages(messages),
1188
- actions,
1214
+ messages: inputMessages,
1215
+ actions: actionInputs,
1189
1216
  threadId,
1190
1217
  runId,
1191
1218
  eventSource
1192
1219
  });
1220
+ outputMessagesPromise.then((outputMessages) => {
1221
+ var _a2;
1222
+ (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
1223
+ threadId: result.threadId,
1224
+ runId: result.runId,
1225
+ inputMessages,
1226
+ outputMessages,
1227
+ properties
1228
+ });
1229
+ }).catch((_error) => {
1230
+ });
1193
1231
  return {
1194
1232
  threadId: result.threadId,
1195
1233
  runId: result.runId,
1196
- eventSource
1234
+ eventSource,
1235
+ actions
1197
1236
  };
1198
1237
  } catch (error) {
1199
1238
  console.error("Error getting response:", error);
@@ -1214,9 +1253,6 @@ function flattenToolCallsNoDuplicates(toolsByPriority) {
1214
1253
  return allTools;
1215
1254
  }
1216
1255
  __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
1217
- var CopilotBackend = class extends CopilotRuntime {
1218
- };
1219
- __name(CopilotBackend, "CopilotBackend");
1220
1256
 
1221
1257
  // src/lib/integrations/shared.ts
1222
1258
  var import_type_graphql13 = require("type-graphql");
@@ -1459,15 +1495,10 @@ function _ts_metadata5(k, v) {
1459
1495
  }
1460
1496
  __name(_ts_metadata5, "_ts_metadata");
1461
1497
  var GuardrailsRuleInput = class {
1462
- id;
1463
1498
  allowList = [];
1464
1499
  denyList = [];
1465
1500
  };
1466
1501
  __name(GuardrailsRuleInput, "GuardrailsRuleInput");
1467
- _ts_decorate5([
1468
- (0, import_type_graphql6.Field)(() => String),
1469
- _ts_metadata5("design:type", String)
1470
- ], GuardrailsRuleInput.prototype, "id", void 0);
1471
1502
  _ts_decorate5([
1472
1503
  (0, import_type_graphql6.Field)(() => [
1473
1504
  String
@@ -1488,16 +1519,17 @@ GuardrailsRuleInput = _ts_decorate5([
1488
1519
  (0, import_type_graphql6.InputType)()
1489
1520
  ], GuardrailsRuleInput);
1490
1521
  var GuardrailsInput = class {
1491
- inputValidationRules = [];
1522
+ inputValidationRules = {
1523
+ allowList: [],
1524
+ denyList: []
1525
+ };
1492
1526
  };
1493
1527
  __name(GuardrailsInput, "GuardrailsInput");
1494
1528
  _ts_decorate5([
1495
- (0, import_type_graphql6.Field)(() => [
1496
- GuardrailsRuleInput
1497
- ], {
1529
+ (0, import_type_graphql6.Field)(() => GuardrailsRuleInput, {
1498
1530
  nullable: true
1499
1531
  }),
1500
- _ts_metadata5("design:type", Array)
1532
+ _ts_metadata5("design:type", typeof GuardrailsRuleInput === "undefined" ? Object : GuardrailsRuleInput)
1501
1533
  ], GuardrailsInput.prototype, "inputValidationRules", void 0);
1502
1534
  GuardrailsInput = _ts_decorate5([
1503
1535
  (0, import_type_graphql6.InputType)()
@@ -1525,7 +1557,9 @@ var CloudInput = class {
1525
1557
  };
1526
1558
  __name(CloudInput, "CloudInput");
1527
1559
  _ts_decorate6([
1528
- (0, import_type_graphql7.Field)(() => GuardrailsInput),
1560
+ (0, import_type_graphql7.Field)(() => GuardrailsInput, {
1561
+ nullable: true
1562
+ }),
1529
1563
  _ts_metadata6("design:type", typeof GuardrailsInput === "undefined" ? Object : GuardrailsInput)
1530
1564
  ], CloudInput.prototype, "guardrails", void 0);
1531
1565
  CloudInput = _ts_decorate6([
@@ -1665,6 +1699,7 @@ var MessageStatusUnion = (0, import_type_graphql9.createUnionType)({
1665
1699
  });
1666
1700
 
1667
1701
  // src/graphql/types/response-status.type.ts
1702
+ var import_graphql_scalars = require("graphql-scalars");
1668
1703
  var import_type_graphql10 = require("type-graphql");
1669
1704
  function _ts_decorate9(decorators, target, key, desc) {
1670
1705
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -1731,15 +1766,31 @@ SuccessResponseStatus = _ts_decorate9([
1731
1766
  implements: BaseResponseStatus
1732
1767
  })
1733
1768
  ], SuccessResponseStatus);
1769
+ var FailedResponseStatusReason;
1770
+ (function(FailedResponseStatusReason2) {
1771
+ FailedResponseStatusReason2["GUARDRAILS_VALIDATION_FAILED"] = "GUARDRAILS_VALIDATION_FAILED";
1772
+ FailedResponseStatusReason2["MESSAGE_STREAM_INTERRUPTED"] = "MESSAGE_STREAM_INTERRUPTED";
1773
+ FailedResponseStatusReason2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
1774
+ })(FailedResponseStatusReason || (FailedResponseStatusReason = {}));
1775
+ (0, import_type_graphql10.registerEnumType)(FailedResponseStatusReason, {
1776
+ name: "FailedResponseStatusReason"
1777
+ });
1734
1778
  var FailedResponseStatus = class extends BaseResponseStatus {
1735
1779
  code = "failed";
1736
1780
  reason;
1781
+ details = null;
1737
1782
  };
1738
1783
  __name(FailedResponseStatus, "FailedResponseStatus");
1739
1784
  _ts_decorate9([
1740
- (0, import_type_graphql10.Field)(() => String),
1785
+ (0, import_type_graphql10.Field)(() => FailedResponseStatusReason),
1741
1786
  _ts_metadata9("design:type", String)
1742
1787
  ], FailedResponseStatus.prototype, "reason", void 0);
1788
+ _ts_decorate9([
1789
+ (0, import_type_graphql10.Field)(() => import_graphql_scalars.GraphQLJSON, {
1790
+ nullable: true
1791
+ }),
1792
+ _ts_metadata9("design:type", typeof Record === "undefined" ? Object : Record)
1793
+ ], FailedResponseStatus.prototype, "details", void 0);
1743
1794
  FailedResponseStatus = _ts_decorate9([
1744
1795
  (0, import_type_graphql10.ObjectType)({
1745
1796
  implements: BaseResponseStatus
@@ -1903,8 +1954,45 @@ CopilotResponse = _ts_decorate10([
1903
1954
 
1904
1955
  // src/graphql/resolvers/copilot.resolver.ts
1905
1956
  var import_graphql_yoga = require("graphql-yoga");
1906
- var import_nanoid3 = require("nanoid");
1907
- var import_graphql_scalars = require("graphql-scalars");
1957
+ var import_nanoid5 = require("nanoid");
1958
+ var import_graphql_scalars2 = require("graphql-scalars");
1959
+ var import_class_transformer2 = require("class-transformer");
1960
+ var import_graphql = require("graphql");
1961
+
1962
+ // src/utils/failed-response-status-reasons.ts
1963
+ var GuardrailsValidationFailureResponse = class extends FailedResponseStatus {
1964
+ reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;
1965
+ constructor({ guardrailsReason }) {
1966
+ super();
1967
+ this.details = {
1968
+ guardrailsReason
1969
+ };
1970
+ }
1971
+ };
1972
+ __name(GuardrailsValidationFailureResponse, "GuardrailsValidationFailureResponse");
1973
+ var MessageStreamInterruptedResponse = class extends FailedResponseStatus {
1974
+ reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;
1975
+ constructor({ messageId }) {
1976
+ super();
1977
+ this.details = {
1978
+ messageId,
1979
+ description: "Check the message for mode details"
1980
+ };
1981
+ }
1982
+ };
1983
+ __name(MessageStreamInterruptedResponse, "MessageStreamInterruptedResponse");
1984
+ var UnknownErrorResponse = class extends FailedResponseStatus {
1985
+ reason = FailedResponseStatusReason.UNKNOWN_ERROR;
1986
+ constructor({ description }) {
1987
+ super();
1988
+ this.details = {
1989
+ description
1990
+ };
1991
+ }
1992
+ };
1993
+ __name(UnknownErrorResponse, "UnknownErrorResponse");
1994
+
1995
+ // src/graphql/resolvers/copilot.resolver.ts
1908
1996
  function _ts_decorate11(decorators, target, key, desc) {
1909
1997
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1910
1998
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -1927,39 +2015,173 @@ function _ts_param(paramIndex, decorator) {
1927
2015
  };
1928
2016
  }
1929
2017
  __name(_ts_param, "_ts_param");
2018
+ var invokeGuardrails = /* @__PURE__ */ __name(async ({ baseUrl, copilotCloudPublicApiKey, data, onResult, onError }) => {
2019
+ var _a;
2020
+ if (data.messages.length && ((_a = data.messages[data.messages.length - 1].textMessage) == null ? void 0 : _a.role) === MessageRole.user) {
2021
+ const messages = data.messages.filter((m) => m.textMessage !== void 0 && (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant)).map((m) => ({
2022
+ role: m.textMessage.role,
2023
+ content: m.textMessage.content
2024
+ }));
2025
+ const lastMessage = messages[messages.length - 1];
2026
+ const restOfMessages = messages.slice(0, -1);
2027
+ const body = {
2028
+ input: lastMessage.content,
2029
+ validTopics: data.cloud.guardrails.inputValidationRules.allowList,
2030
+ invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,
2031
+ messages: restOfMessages
2032
+ };
2033
+ const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {
2034
+ method: "POST",
2035
+ headers: {
2036
+ "Content-Type": "application/json",
2037
+ "X-CopilotCloud-Public-API-Key": copilotCloudPublicApiKey
2038
+ },
2039
+ body: JSON.stringify(body)
2040
+ });
2041
+ if (guardrailsResult.ok) {
2042
+ const resultJson = await guardrailsResult.json();
2043
+ onResult(resultJson);
2044
+ } else {
2045
+ onError(await guardrailsResult.json());
2046
+ }
2047
+ }
2048
+ }, "invokeGuardrails");
1930
2049
  var CopilotResolver = class {
1931
2050
  async hello() {
1932
2051
  return "Hello World";
1933
2052
  }
1934
2053
  async generateCopilotResponse(ctx, data, properties) {
2054
+ let logger2 = ctx.logger.child({
2055
+ component: "CopilotResolver.generateCopilotResponse"
2056
+ });
2057
+ logger2.debug({
2058
+ data
2059
+ }, "Generating Copilot response");
2060
+ const copilotRuntime = ctx._copilotkit.runtime;
2061
+ const serviceAdapter = ctx._copilotkit.serviceAdapter;
1935
2062
  if (properties) {
1936
- ctx._copilotkit.properties = {
1937
- ...ctx._copilotkit.properties,
2063
+ logger2.debug("Properties provided, merging with context properties");
2064
+ ctx.properties = {
2065
+ ...ctx.properties,
1938
2066
  ...properties
1939
2067
  };
1940
2068
  }
1941
- const copilotRuntime = ctx._copilotkit.runtime;
1942
- const serviceAdapter = ctx._copilotkit.serviceAdapter;
1943
- const responseStatus = new import_rxjs2.Subject();
1944
- const { eventSource, threadId = (0, import_nanoid3.nanoid)(), runId } = await copilotRuntime.process({
2069
+ let copilotCloudPublicApiKey = null;
2070
+ let copilotCloudBaseUrl;
2071
+ if (data.cloud) {
2072
+ logger2 = logger2.child({
2073
+ cloud: true
2074
+ });
2075
+ logger2.debug("Cloud configuration provided, checking for public API key in headers");
2076
+ const key = ctx.request.headers.get("x-copilotcloud-public-api-key");
2077
+ if (key) {
2078
+ logger2.debug("Public API key found in headers");
2079
+ copilotCloudPublicApiKey = key;
2080
+ } else {
2081
+ logger2.error("Public API key not found in headers");
2082
+ throw new import_graphql.GraphQLError("X-CopilotCloud-Public-API-Key header is required");
2083
+ }
2084
+ if (process.env.COPILOT_CLOUD_BASE_URL) {
2085
+ copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;
2086
+ } else if (ctx._copilotkit.baseUrl) {
2087
+ copilotCloudBaseUrl = ctx._copilotkit.baseUrl;
2088
+ } else {
2089
+ copilotCloudBaseUrl = "https://api.cloud.copilotkit.ai";
2090
+ }
2091
+ logger2 = logger2.child({
2092
+ copilotCloudBaseUrl
2093
+ });
2094
+ }
2095
+ logger2.debug("Setting up subjects");
2096
+ const responseStatus$ = new import_rxjs2.ReplaySubject();
2097
+ const interruptStreaming$ = new import_rxjs2.ReplaySubject();
2098
+ const guardrailsResult$ = new import_rxjs2.ReplaySubject();
2099
+ let outputMessages = [];
2100
+ let resolveOutputMessagesPromise;
2101
+ let rejectOutputMessagesPromise;
2102
+ const outputMessagesPromise = new Promise((resolve, reject) => {
2103
+ resolveOutputMessagesPromise = resolve;
2104
+ rejectOutputMessagesPromise = reject;
2105
+ });
2106
+ logger2.debug("Processing");
2107
+ const { eventSource, threadId = (0, import_nanoid5.nanoid)(), runId, actions } = await copilotRuntime.process({
1945
2108
  serviceAdapter,
1946
2109
  messages: data.messages,
1947
2110
  actions: data.frontend.actions,
1948
2111
  threadId: data.threadId,
1949
2112
  runId: data.runId,
1950
- publicApiKey: void 0
2113
+ publicApiKey: void 0,
2114
+ properties: ctx.properties || {},
2115
+ outputMessagesPromise
1951
2116
  });
2117
+ logger2.debug("Event source created, creating response");
1952
2118
  const response = {
1953
2119
  threadId,
1954
2120
  runId,
1955
- status: (0, import_rxjs2.firstValueFrom)(responseStatus),
2121
+ status: (0, import_rxjs2.firstValueFrom)(responseStatus$),
1956
2122
  messages: new import_graphql_yoga.Repeater(async (pushMessage, stopStreamingMessages) => {
1957
- const eventStream = eventSource.process(copilotRuntime.actions).pipe(
2123
+ var _a, _b;
2124
+ logger2.debug("Messages repeater created");
2125
+ if ((_a = data.cloud) == null ? void 0 : _a.guardrails) {
2126
+ logger2 = logger2.child({
2127
+ guardrails: true
2128
+ });
2129
+ logger2.debug("Guardrails is enabled, validating input");
2130
+ invokeGuardrails({
2131
+ baseUrl: copilotCloudBaseUrl,
2132
+ copilotCloudPublicApiKey,
2133
+ data,
2134
+ onResult: (result) => {
2135
+ logger2.debug({
2136
+ status: result.status
2137
+ }, "Guardrails validation done");
2138
+ guardrailsResult$.next(result);
2139
+ if (result.status === "denied") {
2140
+ responseStatus$.next(new GuardrailsValidationFailureResponse({
2141
+ guardrailsReason: result.reason
2142
+ }));
2143
+ interruptStreaming$.next({
2144
+ reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`
2145
+ });
2146
+ outputMessages = [
2147
+ (0, import_class_transformer2.plainToInstance)(TextMessage, {
2148
+ id: (0, import_nanoid5.nanoid)(),
2149
+ createdAt: /* @__PURE__ */ new Date(),
2150
+ content: result.reason,
2151
+ role: MessageRole.assistant
2152
+ })
2153
+ ];
2154
+ resolveOutputMessagesPromise(outputMessages);
2155
+ }
2156
+ },
2157
+ onError: (err) => {
2158
+ logger2.error({
2159
+ err
2160
+ }, "Error in guardrails validation");
2161
+ responseStatus$.next(new UnknownErrorResponse({
2162
+ description: `An unknown error has occurred in the guardrails validation`
2163
+ }));
2164
+ interruptStreaming$.next({
2165
+ reason: `Interrupted due to unknown error in guardrails validation`
2166
+ });
2167
+ rejectOutputMessagesPromise(err);
2168
+ }
2169
+ });
2170
+ }
2171
+ let eventStreamSubscription;
2172
+ const eventStream = eventSource.process({
2173
+ serversideActions: actions,
2174
+ guardrailsResult$: ((_b = data.cloud) == null ? void 0 : _b.guardrails) ? guardrailsResult$ : null
2175
+ }).pipe(
1958
2176
  // shareReplay() ensures that later subscribers will see the whole stream instead of
1959
2177
  // just the events that were emitted after the subscriber was added.
1960
- (0, import_rxjs2.shareReplay)()
2178
+ (0, import_rxjs2.shareReplay)(),
2179
+ (0, import_rxjs2.finalize)(() => {
2180
+ logger2.debug("Event stream finalized");
2181
+ })
1961
2182
  );
1962
- eventStream.subscribe({
2183
+ logger2.debug("Event stream created, subscribing to event stream");
2184
+ eventStreamSubscription = eventStream.subscribe({
1963
2185
  next: async (event) => {
1964
2186
  switch (event.type) {
1965
2187
  case RuntimeEventTypes.TextMessageStart:
@@ -1970,23 +2192,67 @@ var CopilotResolver = class {
1970
2192
  (0, import_rxjs2.takeWhile)((e) => e.type != RuntimeEventTypes.TextMessageEnd)
1971
2193
  );
1972
2194
  const streamingTextStatus = new import_rxjs2.Subject();
2195
+ const messageId = (0, import_nanoid5.nanoid)();
1973
2196
  pushMessage({
1974
- id: (0, import_nanoid3.nanoid)(),
2197
+ id: messageId,
1975
2198
  status: (0, import_rxjs2.firstValueFrom)(streamingTextStatus),
1976
2199
  createdAt: /* @__PURE__ */ new Date(),
1977
2200
  role: MessageRole.assistant,
1978
2201
  content: new import_graphql_yoga.Repeater(async (pushTextChunk, stopStreamingText) => {
1979
- await textMessageContentStream.forEach(async (e) => {
1980
- if (e.type == RuntimeEventTypes.TextMessageContent) {
1981
- await pushTextChunk(e.content);
2202
+ logger2.debug("Text message content repeater created");
2203
+ const textChunks = [];
2204
+ let textSubscription;
2205
+ interruptStreaming$.pipe((0, import_rxjs2.shareReplay)(), (0, import_rxjs2.take)(1), (0, import_rxjs2.tap)(({ reason, messageId: messageId2 }) => {
2206
+ logger2.debug({
2207
+ reason,
2208
+ messageId: messageId2
2209
+ }, "Text streaming interrupted");
2210
+ streamingTextStatus.next((0, import_class_transformer2.plainToInstance)(FailedMessageStatus, {
2211
+ reason
2212
+ }));
2213
+ responseStatus$.next(new MessageStreamInterruptedResponse({
2214
+ messageId: messageId2
2215
+ }));
2216
+ stopStreamingText();
2217
+ textSubscription == null ? void 0 : textSubscription.unsubscribe();
2218
+ })).subscribe();
2219
+ logger2.debug("Subscribing to text message content stream");
2220
+ textSubscription = textMessageContentStream.subscribe({
2221
+ next: async (e) => {
2222
+ if (e.type == RuntimeEventTypes.TextMessageContent) {
2223
+ await pushTextChunk(e.content);
2224
+ textChunks.push(e.content);
2225
+ }
2226
+ },
2227
+ error: (err) => {
2228
+ logger2.error({
2229
+ err
2230
+ }, "Error in text message content stream");
2231
+ interruptStreaming$.next({
2232
+ reason: "Error streaming message content",
2233
+ messageId
2234
+ });
2235
+ stopStreamingText();
2236
+ textSubscription == null ? void 0 : textSubscription.unsubscribe();
2237
+ },
2238
+ complete: () => {
2239
+ logger2.debug("Text message content stream completed");
2240
+ streamingTextStatus.next(new SuccessMessageStatus());
2241
+ stopStreamingText();
2242
+ textSubscription == null ? void 0 : textSubscription.unsubscribe();
2243
+ outputMessages.push((0, import_class_transformer2.plainToInstance)(TextMessage, {
2244
+ id: messageId,
2245
+ createdAt: /* @__PURE__ */ new Date(),
2246
+ content: textChunks.join(""),
2247
+ role: MessageRole.assistant
2248
+ }));
1982
2249
  }
1983
2250
  });
1984
- stopStreamingText();
1985
- streamingTextStatus.next(new SuccessMessageStatus());
1986
2251
  })
1987
2252
  });
1988
2253
  break;
1989
2254
  case RuntimeEventTypes.ActionExecutionStart:
2255
+ logger2.debug("Action execution start event received");
1990
2256
  const actionExecutionArgumentStream = eventStream.pipe((0, import_rxjs2.skipWhile)((e) => e !== event), (0, import_rxjs2.takeWhile)((e) => e.type != RuntimeEventTypes.ActionExecutionEnd));
1991
2257
  const streamingArgumentsStatus = new import_rxjs2.Subject();
1992
2258
  pushMessage({
@@ -1996,32 +2262,87 @@ var CopilotResolver = class {
1996
2262
  name: event.actionName,
1997
2263
  scope: event.scope,
1998
2264
  arguments: new import_graphql_yoga.Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
1999
- await actionExecutionArgumentStream.forEach(async (e) => {
2000
- if (e.type == RuntimeEventTypes.ActionExecutionArgs) {
2001
- await pushArgumentsChunk(e.args);
2265
+ logger2.debug("Action execution argument stream created");
2266
+ const argumentChunks = [];
2267
+ let actionExecutionArgumentSubscription;
2268
+ actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({
2269
+ next: async (e) => {
2270
+ if (e.type == RuntimeEventTypes.ActionExecutionArgs) {
2271
+ await pushArgumentsChunk(e.args);
2272
+ argumentChunks.push(e.args);
2273
+ }
2274
+ },
2275
+ error: (err) => {
2276
+ logger2.error({
2277
+ err
2278
+ }, "Error in action execution argument stream");
2279
+ streamingArgumentsStatus.next((0, import_class_transformer2.plainToInstance)(FailedMessageStatus, {
2280
+ reason: "An unknown error has occurred in the action execution argument stream"
2281
+ }));
2282
+ stopStreamingArguments();
2283
+ actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
2284
+ },
2285
+ complete: () => {
2286
+ logger2.debug("Action execution argument stream completed");
2287
+ streamingArgumentsStatus.next(new SuccessMessageStatus());
2288
+ stopStreamingArguments();
2289
+ actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
2290
+ outputMessages.push((0, import_class_transformer2.plainToInstance)(ActionExecutionMessage, {
2291
+ id: event.actionExecutionId,
2292
+ createdAt: /* @__PURE__ */ new Date(),
2293
+ name: event.actionName,
2294
+ scope: event.scope,
2295
+ arguments: argumentChunks.join("")
2296
+ }));
2002
2297
  }
2003
2298
  });
2004
- stopStreamingArguments();
2005
- streamingArgumentsStatus.next(new SuccessMessageStatus());
2006
2299
  })
2007
2300
  });
2008
2301
  break;
2009
2302
  case RuntimeEventTypes.ActionExecutionResult:
2303
+ logger2.debug({
2304
+ result: event.result
2305
+ }, "Action execution result event received");
2010
2306
  pushMessage({
2011
- id: (0, import_nanoid3.nanoid)(),
2307
+ id: (0, import_nanoid5.nanoid)(),
2012
2308
  status: new SuccessMessageStatus(),
2013
2309
  createdAt: /* @__PURE__ */ new Date(),
2014
2310
  actionExecutionId: event.actionExecutionId,
2015
2311
  actionName: event.actionName,
2016
2312
  result: event.result
2017
2313
  });
2314
+ outputMessages.push((0, import_class_transformer2.plainToInstance)(ResultMessage, {
2315
+ id: (0, import_nanoid5.nanoid)(),
2316
+ createdAt: /* @__PURE__ */ new Date(),
2317
+ actionExecutionId: event.actionExecutionId,
2318
+ actionName: event.actionName,
2319
+ result: event.result
2320
+ }));
2018
2321
  break;
2019
2322
  }
2020
2323
  },
2021
- error: (err) => console.error("Error in event source", err),
2022
- complete: () => {
2023
- responseStatus.next(new SuccessResponseStatus());
2324
+ error: (err) => {
2325
+ logger2.error({
2326
+ err
2327
+ }, "Error in event stream");
2328
+ responseStatus$.next(new UnknownErrorResponse({
2329
+ description: `An unknown error has occurred in the event stream`
2330
+ }));
2331
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
2332
+ stopStreamingMessages();
2333
+ rejectOutputMessagesPromise(err);
2334
+ },
2335
+ complete: async () => {
2336
+ var _a2;
2337
+ logger2.debug("Event stream completed");
2338
+ if ((_a2 = data.cloud) == null ? void 0 : _a2.guardrails) {
2339
+ logger2.debug("Guardrails is enabled, waiting for guardrails result");
2340
+ await (0, import_rxjs2.firstValueFrom)(guardrailsResult$);
2341
+ }
2342
+ responseStatus$.next(new SuccessResponseStatus());
2343
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
2024
2344
  stopStreamingMessages();
2345
+ resolveOutputMessagesPromise(outputMessages);
2025
2346
  }
2026
2347
  });
2027
2348
  })
@@ -2040,7 +2361,7 @@ _ts_decorate11([
2040
2361
  (0, import_type_graphql12.Mutation)(() => CopilotResponse),
2041
2362
  _ts_param(0, (0, import_type_graphql12.Ctx)()),
2042
2363
  _ts_param(1, (0, import_type_graphql12.Arg)("data")),
2043
- _ts_param(2, (0, import_type_graphql12.Arg)("properties", () => import_graphql_scalars.GraphQLJSONObject, {
2364
+ _ts_param(2, (0, import_type_graphql12.Arg)("properties", () => import_graphql_scalars2.GraphQLJSONObject, {
2044
2365
  nullable: true
2045
2366
  })),
2046
2367
  _ts_metadata11("design:type", Function),
@@ -2057,51 +2378,99 @@ CopilotResolver = _ts_decorate11([
2057
2378
 
2058
2379
  // src/lib/integrations/shared.ts
2059
2380
  var import_plugin_defer_stream = require("@graphql-yoga/plugin-defer-stream");
2060
- async function createContext(initialContext, copilotKitContext) {
2381
+
2382
+ // src/lib/logger.ts
2383
+ var import_pino = __toESM(require("pino"));
2384
+ var import_pino_pretty = __toESM(require("pino-pretty"));
2385
+ function createLogger(options) {
2386
+ const { level, component } = options || {};
2387
+ const stream = (0, import_pino_pretty.default)({
2388
+ colorize: true
2389
+ });
2390
+ const logger2 = (0, import_pino.default)({
2391
+ level: process.env.LOG_LEVEL || level || "error",
2392
+ redact: {
2393
+ paths: [
2394
+ "pid",
2395
+ "hostname"
2396
+ ],
2397
+ remove: true
2398
+ }
2399
+ }, stream);
2400
+ if (component) {
2401
+ return logger2.child({
2402
+ component
2403
+ });
2404
+ } else {
2405
+ return logger2;
2406
+ }
2407
+ }
2408
+ __name(createLogger, "createLogger");
2409
+
2410
+ // src/lib/integrations/shared.ts
2411
+ var logger = createLogger();
2412
+ async function createContext(initialContext, copilotKitContext, contextLogger, properties = {}) {
2413
+ logger.debug({
2414
+ copilotKitContext
2415
+ }, "Creating GraphQL context");
2061
2416
  const ctx = {
2062
2417
  ...initialContext,
2063
2418
  _copilotkit: {
2064
2419
  ...copilotKitContext
2065
- }
2420
+ },
2421
+ properties: {
2422
+ ...properties
2423
+ },
2424
+ logger: contextLogger
2066
2425
  };
2067
2426
  return ctx;
2068
2427
  }
2069
2428
  __name(createContext, "createContext");
2070
2429
  function buildSchema(options = {}) {
2430
+ logger.debug("Building GraphQL schema...");
2071
2431
  const schema = (0, import_type_graphql13.buildSchemaSync)({
2072
2432
  resolvers: [
2073
2433
  CopilotResolver
2074
2434
  ],
2075
2435
  emitSchemaFile: options.emitSchemaFile
2076
2436
  });
2437
+ logger.debug("GraphQL schema built successfully");
2077
2438
  return schema;
2078
2439
  }
2079
2440
  __name(buildSchema, "buildSchema");
2080
2441
  function getCommonConfig(options) {
2442
+ const logLevel = process.env.LOG_LEVEL || options.logLevel || "error";
2443
+ const logger2 = createLogger({
2444
+ level: logLevel,
2445
+ component: "getCommonConfig"
2446
+ });
2447
+ logger2.debug("Getting common config");
2448
+ const contextLogger = createLogger({
2449
+ level: logLevel
2450
+ });
2081
2451
  return {
2452
+ logging: createLogger({
2453
+ component: "Yoga GraphQL",
2454
+ level: logLevel
2455
+ }),
2082
2456
  schema: buildSchema(),
2083
2457
  plugins: [
2084
2458
  (0, import_plugin_defer_stream.useDeferStream)()
2085
2459
  ],
2086
- context: (ctx) => createContext(ctx, {
2087
- runtime: options.runtime,
2088
- serviceAdapter: options.serviceAdapter,
2089
- properties: {}
2090
- })
2460
+ context: (ctx) => createContext(ctx, options, contextLogger, options.properties)
2091
2461
  };
2092
2462
  }
2093
2463
  __name(getCommonConfig, "getCommonConfig");
2094
2464
 
2095
2465
  // src/lib/integrations/nextjs/app-router.ts
2096
2466
  var import_graphql_yoga2 = require("graphql-yoga");
2097
- function copilotRuntimeNextJSAppRouterEndpoint({ runtime, endpoint, serviceAdapter }) {
2098
- const commonConfig = getCommonConfig({
2099
- runtime,
2100
- serviceAdapter
2101
- });
2467
+ function copilotRuntimeNextJSAppRouterEndpoint(options) {
2468
+ const commonConfig = getCommonConfig(options);
2469
+ const logger2 = commonConfig.logging;
2470
+ logger2.debug("Creating NextJS App Router endpoint");
2102
2471
  const yoga = (0, import_graphql_yoga2.createYoga)({
2103
2472
  ...commonConfig,
2104
- graphqlEndpoint: endpoint,
2473
+ graphqlEndpoint: options.endpoint,
2105
2474
  fetchAPI: {
2106
2475
  Response: globalThis.Response
2107
2476
  }
@@ -2122,14 +2491,13 @@ var config = {
2122
2491
  bodyParser: false
2123
2492
  }
2124
2493
  };
2125
- function copilotRuntimeNextJSPagesRouterEndpoint({ runtime, endpoint, serviceAdapter }) {
2126
- const commonConfig = getCommonConfig({
2127
- runtime,
2128
- serviceAdapter
2129
- });
2494
+ function copilotRuntimeNextJSPagesRouterEndpoint(options) {
2495
+ const commonConfig = getCommonConfig(options);
2496
+ const logger2 = commonConfig.logging;
2497
+ logger2.debug("Creating NextJS Pages Router endpoint");
2130
2498
  const yoga = (0, import_graphql_yoga3.createYoga)({
2131
2499
  ...commonConfig,
2132
- graphqlEndpoint: endpoint
2500
+ graphqlEndpoint: options.endpoint
2133
2501
  });
2134
2502
  return yoga;
2135
2503
  }
@@ -2137,28 +2505,27 @@ __name(copilotRuntimeNextJSPagesRouterEndpoint, "copilotRuntimeNextJSPagesRouter
2137
2505
 
2138
2506
  // src/lib/integrations/node-http/index.ts
2139
2507
  var import_graphql_yoga4 = require("graphql-yoga");
2140
- function copilotRuntimeNodeHttpEndpoint({ runtime, endpoint, serviceAdapter }) {
2141
- const commonConfig = getCommonConfig({
2142
- runtime,
2143
- serviceAdapter
2144
- });
2508
+ function copilotRuntimeNodeHttpEndpoint(options) {
2509
+ const commonConfig = getCommonConfig(options);
2510
+ const logger2 = commonConfig.logging;
2511
+ logger2.debug("Creating Node HTTP endpoint");
2145
2512
  const yoga = (0, import_graphql_yoga4.createYoga)({
2146
2513
  ...commonConfig,
2147
- graphqlEndpoint: endpoint
2514
+ graphqlEndpoint: options.endpoint
2148
2515
  });
2149
2516
  return yoga;
2150
2517
  }
2151
2518
  __name(copilotRuntimeNodeHttpEndpoint, "copilotRuntimeNodeHttpEndpoint");
2152
2519
  // Annotate the CommonJS export names for ESM import in node:
2153
2520
  0 && (module.exports = {
2154
- CopilotBackend,
2155
- CopilotCloud,
2156
2521
  CopilotRuntime,
2157
2522
  GoogleGenerativeAIAdapter,
2523
+ GuardrailsValidationFailureResponse,
2158
2524
  LangChainAdapter,
2525
+ MessageStreamInterruptedResponse,
2159
2526
  OpenAIAdapter,
2160
2527
  OpenAIAssistantAdapter,
2161
- RemoteCopilotCloud,
2528
+ UnknownErrorResponse,
2162
2529
  buildSchema,
2163
2530
  config,
2164
2531
  copilotRuntimeNextJSAppRouterEndpoint,