@copilotkit/runtime 0.37.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 (105) hide show
  1. package/.eslintrc.js +7 -0
  2. package/.turbo/turbo-build.log +70 -0
  3. package/CHANGELOG.md +1 -0
  4. package/__snapshots__/schema/schema.graphql +178 -0
  5. package/dist/chunk-2CCVVJDU.mjs +56 -0
  6. package/dist/chunk-2CCVVJDU.mjs.map +1 -0
  7. package/dist/chunk-4UA4RB4C.mjs +185 -0
  8. package/dist/chunk-4UA4RB4C.mjs.map +1 -0
  9. package/dist/chunk-5HGYI6EG.mjs +678 -0
  10. package/dist/chunk-5HGYI6EG.mjs.map +1 -0
  11. package/dist/chunk-7IFP53C6.mjs +169 -0
  12. package/dist/chunk-7IFP53C6.mjs.map +1 -0
  13. package/dist/chunk-BLTAUVRP.mjs +30 -0
  14. package/dist/chunk-BLTAUVRP.mjs.map +1 -0
  15. package/dist/chunk-NFCPM5AM.mjs +43 -0
  16. package/dist/chunk-NFCPM5AM.mjs.map +1 -0
  17. package/dist/chunk-XPAUPJMW.mjs +1051 -0
  18. package/dist/chunk-XPAUPJMW.mjs.map +1 -0
  19. package/dist/graphql/types/base/index.d.ts +6 -0
  20. package/dist/graphql/types/base/index.js +63 -0
  21. package/dist/graphql/types/base/index.js.map +1 -0
  22. package/dist/graphql/types/base/index.mjs +7 -0
  23. package/dist/graphql/types/base/index.mjs.map +1 -0
  24. package/dist/graphql/types/converted/index.d.ts +2 -0
  25. package/dist/graphql/types/converted/index.js +88 -0
  26. package/dist/graphql/types/converted/index.js.map +1 -0
  27. package/dist/graphql/types/converted/index.mjs +12 -0
  28. package/dist/graphql/types/converted/index.mjs.map +1 -0
  29. package/dist/index-aa091e3c.d.ts +49 -0
  30. package/dist/index-f0875df3.d.ts +197 -0
  31. package/dist/index.d.ts +15 -0
  32. package/dist/index.js +2171 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/index.mjs +49 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/langchain-adapter-9ce103f3.d.ts +200 -0
  37. package/dist/langserve-fd5066ee.d.ts +96 -0
  38. package/dist/lib/index.d.ts +15 -0
  39. package/dist/lib/index.js +2170 -0
  40. package/dist/lib/index.js.map +1 -0
  41. package/dist/lib/index.mjs +46 -0
  42. package/dist/lib/index.mjs.map +1 -0
  43. package/dist/lib/integrations/index.d.ts +9 -0
  44. package/dist/lib/integrations/index.js +1024 -0
  45. package/dist/lib/integrations/index.js.map +1 -0
  46. package/dist/lib/integrations/index.mjs +24 -0
  47. package/dist/lib/integrations/index.mjs.map +1 -0
  48. package/dist/lib/integrations/node-http/index.d.ts +8 -0
  49. package/dist/lib/integrations/node-http/index.js +969 -0
  50. package/dist/lib/integrations/node-http/index.js.map +1 -0
  51. package/dist/lib/integrations/node-http/index.mjs +10 -0
  52. package/dist/lib/integrations/node-http/index.mjs.map +1 -0
  53. package/dist/pages-router-b6bc6c60.d.ts +30 -0
  54. package/dist/service-adapters/index.d.ts +11 -0
  55. package/dist/service-adapters/index.js +912 -0
  56. package/dist/service-adapters/index.js.map +1 -0
  57. package/dist/service-adapters/index.mjs +18 -0
  58. package/dist/service-adapters/index.mjs.map +1 -0
  59. package/jest.config.js +5 -0
  60. package/package.json +63 -0
  61. package/scripts/generate-gql-schema.ts +13 -0
  62. package/src/graphql/inputs/action.input.ts +13 -0
  63. package/src/graphql/inputs/cloud-guardrails.input.ts +19 -0
  64. package/src/graphql/inputs/cloud.input.ts +8 -0
  65. package/src/graphql/inputs/context-property.input.ts +10 -0
  66. package/src/graphql/inputs/custom-property.input.ts +15 -0
  67. package/src/graphql/inputs/frontend.input.ts +11 -0
  68. package/src/graphql/inputs/generate-copilot-response.input.ts +22 -0
  69. package/src/graphql/inputs/message.input.ts +50 -0
  70. package/src/graphql/resolvers/copilot.resolver.ts +147 -0
  71. package/src/graphql/types/base/index.ts +10 -0
  72. package/src/graphql/types/converted/index.ts +29 -0
  73. package/src/graphql/types/copilot-response.type.ts +75 -0
  74. package/src/graphql/types/enums.ts +22 -0
  75. package/src/graphql/types/guardrails-result.type.ts +20 -0
  76. package/src/graphql/types/message-status.type.ts +40 -0
  77. package/src/graphql/types/response-status.type.ts +52 -0
  78. package/src/index.ts +2 -0
  79. package/src/lib/copilot-cloud.ts +63 -0
  80. package/src/lib/copilot-runtime.ts +261 -0
  81. package/src/lib/guardrails.ts +3 -0
  82. package/src/lib/index.ts +7 -0
  83. package/src/lib/integrations/index.ts +4 -0
  84. package/src/lib/integrations/nextjs/app-router.ts +29 -0
  85. package/src/lib/integrations/nextjs/pages-router.ts +36 -0
  86. package/src/lib/integrations/node-http/index.ts +23 -0
  87. package/src/lib/integrations/shared.ts +68 -0
  88. package/src/service-adapters/conversion.ts +47 -0
  89. package/src/service-adapters/events.ts +197 -0
  90. package/src/service-adapters/experimental/groq/groq-adapter.ts +124 -0
  91. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +75 -0
  92. package/src/service-adapters/google/google-genai-adapter.ts +149 -0
  93. package/src/service-adapters/google/utils.ts +94 -0
  94. package/src/service-adapters/index.ts +6 -0
  95. package/src/service-adapters/langchain/langchain-adapter.ts +82 -0
  96. package/src/service-adapters/langchain/langserve.ts +81 -0
  97. package/src/service-adapters/langchain/types.ts +14 -0
  98. package/src/service-adapters/langchain/utils.ts +235 -0
  99. package/src/service-adapters/openai/openai-adapter.ts +142 -0
  100. package/src/service-adapters/openai/openai-assistant-adapter.ts +260 -0
  101. package/src/service-adapters/openai/utils.ts +164 -0
  102. package/src/service-adapters/service-adapter.ts +29 -0
  103. package/tsconfig.json +11 -0
  104. package/tsup.config.ts +17 -0
  105. package/typedoc.json +4 -0
@@ -0,0 +1,2170 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/lib/index.ts
31
+ var lib_exports = {};
32
+ __export(lib_exports, {
33
+ CopilotBackend: () => CopilotBackend,
34
+ CopilotCloud: () => CopilotCloud,
35
+ CopilotRuntime: () => CopilotRuntime,
36
+ GoogleGenerativeAIAdapter: () => GoogleGenerativeAIAdapter,
37
+ LangChainAdapter: () => LangChainAdapter,
38
+ OpenAIAdapter: () => OpenAIAdapter,
39
+ OpenAIAssistantAdapter: () => OpenAIAssistantAdapter,
40
+ RemoteCopilotCloud: () => RemoteCopilotCloud,
41
+ buildSchema: () => buildSchema,
42
+ config: () => config,
43
+ copilotRuntimeNextJSAppRouterEndpoint: () => copilotRuntimeNextJSAppRouterEndpoint,
44
+ copilotRuntimeNextJSPagesRouterEndpoint: () => copilotRuntimeNextJSPagesRouterEndpoint,
45
+ copilotRuntimeNodeHttpEndpoint: () => copilotRuntimeNodeHttpEndpoint,
46
+ createContext: () => createContext,
47
+ flattenToolCallsNoDuplicates: () => flattenToolCallsNoDuplicates,
48
+ getCommonConfig: () => getCommonConfig
49
+ });
50
+ module.exports = __toCommonJS(lib_exports);
51
+
52
+ // src/lib/copilot-runtime.ts
53
+ var import_shared2 = require("@copilotkit/shared");
54
+
55
+ // src/service-adapters/openai/openai-adapter.ts
56
+ var import_openai = __toESM(require("openai"));
57
+
58
+ // src/graphql/types/base/index.ts
59
+ var import_type_graphql = require("type-graphql");
60
+ function _ts_decorate(decorators, target, key, desc) {
61
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
62
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
63
+ r = Reflect.decorate(decorators, target, key, desc);
64
+ else
65
+ for (var i = decorators.length - 1; i >= 0; i--)
66
+ if (d = decorators[i])
67
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
68
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
69
+ }
70
+ __name(_ts_decorate, "_ts_decorate");
71
+ function _ts_metadata(k, v) {
72
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
73
+ return Reflect.metadata(k, v);
74
+ }
75
+ __name(_ts_metadata, "_ts_metadata");
76
+ var BaseMessage = class {
77
+ id;
78
+ createdAt;
79
+ };
80
+ __name(BaseMessage, "BaseMessage");
81
+ _ts_decorate([
82
+ (0, import_type_graphql.Field)(() => String),
83
+ _ts_metadata("design:type", String)
84
+ ], BaseMessage.prototype, "id", void 0);
85
+ _ts_decorate([
86
+ (0, import_type_graphql.Field)(() => Date),
87
+ _ts_metadata("design:type", typeof Date === "undefined" ? Object : Date)
88
+ ], BaseMessage.prototype, "createdAt", void 0);
89
+ BaseMessage = _ts_decorate([
90
+ (0, import_type_graphql.InputType)()
91
+ ], BaseMessage);
92
+
93
+ // src/graphql/types/converted/index.ts
94
+ var TextMessage = class extends BaseMessage {
95
+ content;
96
+ role;
97
+ };
98
+ __name(TextMessage, "TextMessage");
99
+ var ActionExecutionMessage = class extends BaseMessage {
100
+ name;
101
+ arguments;
102
+ scope;
103
+ };
104
+ __name(ActionExecutionMessage, "ActionExecutionMessage");
105
+ var ResultMessage = class extends BaseMessage {
106
+ actionExecutionId;
107
+ actionName;
108
+ result;
109
+ };
110
+ __name(ResultMessage, "ResultMessage");
111
+
112
+ // src/service-adapters/openai/utils.ts
113
+ var import_js_tiktoken = require("js-tiktoken");
114
+ function limitMessagesToTokenCount(messages, tools, model, maxTokens) {
115
+ maxTokens || (maxTokens = maxTokensForOpenAIModel(model));
116
+ const result = [];
117
+ const toolsNumTokens = countToolsTokens(model, tools);
118
+ if (toolsNumTokens > maxTokens) {
119
+ throw new Error(`Too many tokens in function definitions: ${toolsNumTokens} > ${maxTokens}`);
120
+ }
121
+ maxTokens -= toolsNumTokens;
122
+ for (const message of messages) {
123
+ if (message.role === "system") {
124
+ const numTokens = countMessageTokens(model, message);
125
+ maxTokens -= numTokens;
126
+ if (maxTokens < 0) {
127
+ throw new Error("Not enough tokens for system message.");
128
+ }
129
+ }
130
+ }
131
+ let cutoff = false;
132
+ const reversedMessages = [
133
+ ...messages
134
+ ].reverse();
135
+ for (const message of reversedMessages) {
136
+ if (message.role === "system") {
137
+ result.unshift(message);
138
+ continue;
139
+ } else if (cutoff) {
140
+ continue;
141
+ }
142
+ let numTokens = countMessageTokens(model, message);
143
+ if (maxTokens < numTokens) {
144
+ cutoff = true;
145
+ continue;
146
+ }
147
+ result.unshift(message);
148
+ maxTokens -= numTokens;
149
+ }
150
+ return result;
151
+ }
152
+ __name(limitMessagesToTokenCount, "limitMessagesToTokenCount");
153
+ function maxTokensForOpenAIModel(model) {
154
+ return maxTokensByModel[model] || DEFAULT_MAX_TOKENS;
155
+ }
156
+ __name(maxTokensForOpenAIModel, "maxTokensForOpenAIModel");
157
+ var DEFAULT_MAX_TOKENS = 128e3;
158
+ var maxTokensByModel = {
159
+ // GPT-4
160
+ "gpt-4o": 128e3,
161
+ "gpt-4o-2024-05-13": 128e3,
162
+ "gpt-4-turbo": 128e3,
163
+ "gpt-4-turbo-2024-04-09": 128e3,
164
+ "gpt-4-0125-preview": 128e3,
165
+ "gpt-4-turbo-preview": 128e3,
166
+ "gpt-4-1106-preview": 128e3,
167
+ "gpt-4-vision-preview": 128e3,
168
+ "gpt-4-1106-vision-preview": 128e3,
169
+ "gpt-4-32k": 32768,
170
+ "gpt-4-32k-0613": 32768,
171
+ "gpt-4-32k-0314": 32768,
172
+ "gpt-4": 8192,
173
+ "gpt-4-0613": 8192,
174
+ "gpt-4-0314": 8192,
175
+ // GPT-3.5
176
+ "gpt-3.5-turbo-0125": 16385,
177
+ "gpt-3.5-turbo": 16385,
178
+ "gpt-3.5-turbo-1106": 16385,
179
+ "gpt-3.5-turbo-instruct": 4096,
180
+ "gpt-3.5-turbo-16k": 16385,
181
+ "gpt-3.5-turbo-0613": 4096,
182
+ "gpt-3.5-turbo-16k-0613": 16385,
183
+ "gpt-3.5-turbo-0301": 4097
184
+ };
185
+ function countToolsTokens(model, tools) {
186
+ if (tools.length === 0) {
187
+ return 0;
188
+ }
189
+ const json = JSON.stringify(tools);
190
+ return countTokens(model, json);
191
+ }
192
+ __name(countToolsTokens, "countToolsTokens");
193
+ function countMessageTokens(model, message) {
194
+ return countTokens(model, message.content || "");
195
+ }
196
+ __name(countMessageTokens, "countMessageTokens");
197
+ function countTokens(model, text) {
198
+ let enc;
199
+ try {
200
+ enc = (0, import_js_tiktoken.encodingForModel)(model);
201
+ } catch (e) {
202
+ enc = (0, import_js_tiktoken.encodingForModel)("gpt-4");
203
+ }
204
+ return enc.encode(text).length;
205
+ }
206
+ __name(countTokens, "countTokens");
207
+ function convertActionInputToOpenAITool(action) {
208
+ return {
209
+ type: "function",
210
+ function: {
211
+ name: action.name,
212
+ description: action.description,
213
+ parameters: JSON.parse(action.jsonSchema)
214
+ }
215
+ };
216
+ }
217
+ __name(convertActionInputToOpenAITool, "convertActionInputToOpenAITool");
218
+ function convertMessageToOpenAIMessage(message) {
219
+ if (message instanceof TextMessage) {
220
+ return {
221
+ role: message.role,
222
+ content: message.content
223
+ };
224
+ } else if (message instanceof ActionExecutionMessage) {
225
+ return {
226
+ role: "assistant",
227
+ tool_calls: [
228
+ {
229
+ id: message.id,
230
+ type: "function",
231
+ function: {
232
+ name: message.name,
233
+ arguments: JSON.stringify(message.arguments)
234
+ }
235
+ }
236
+ ]
237
+ };
238
+ } else if (message instanceof ResultMessage) {
239
+ return {
240
+ role: "tool",
241
+ content: message.result,
242
+ tool_call_id: message.actionExecutionId
243
+ };
244
+ }
245
+ }
246
+ __name(convertMessageToOpenAIMessage, "convertMessageToOpenAIMessage");
247
+ function convertSystemMessageToAssistantAPI(message) {
248
+ return {
249
+ ...message,
250
+ ...message.role === "system" && {
251
+ role: "assistant",
252
+ content: "THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: " + message.content
253
+ }
254
+ };
255
+ }
256
+ __name(convertSystemMessageToAssistantAPI, "convertSystemMessageToAssistantAPI");
257
+
258
+ // src/service-adapters/openai/openai-adapter.ts
259
+ var DEFAULT_MODEL = "gpt-4o";
260
+ var OpenAIAdapter = class {
261
+ model = DEFAULT_MODEL;
262
+ _openai;
263
+ get openai() {
264
+ return this._openai;
265
+ }
266
+ constructor(params) {
267
+ this._openai = (params == null ? void 0 : params.openai) || new import_openai.default({});
268
+ if (params == null ? void 0 : params.model) {
269
+ this.model = params.model;
270
+ }
271
+ }
272
+ async process({ model = this.model, messages, actions, eventSource }) {
273
+ const tools = actions.map(convertActionInputToOpenAITool);
274
+ let openaiMessages = messages.map(convertMessageToOpenAIMessage);
275
+ openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
276
+ const stream = this.openai.beta.chat.completions.stream({
277
+ model,
278
+ stream: true,
279
+ messages: openaiMessages,
280
+ ...tools.length > 0 && {
281
+ tools
282
+ }
283
+ });
284
+ eventSource.stream(async (eventStream$) => {
285
+ var _a, _b;
286
+ let mode = null;
287
+ for await (const chunk of stream) {
288
+ const toolCall = (_a = chunk.choices[0].delta.tool_calls) == null ? void 0 : _a[0];
289
+ const content = chunk.choices[0].delta.content;
290
+ if (mode === "message" && (toolCall == null ? void 0 : toolCall.id)) {
291
+ mode = null;
292
+ eventStream$.sendTextMessageEnd();
293
+ } else if (mode === "function" && (toolCall === void 0 || (toolCall == null ? void 0 : toolCall.id))) {
294
+ mode = null;
295
+ eventStream$.sendActionExecutionEnd();
296
+ }
297
+ if (mode === null) {
298
+ if (toolCall == null ? void 0 : toolCall.id) {
299
+ mode = "function";
300
+ eventStream$.sendActionExecutionStart(toolCall.id, toolCall.function.name);
301
+ } else if (content) {
302
+ mode = "message";
303
+ eventStream$.sendTextMessageStart(chunk.id);
304
+ }
305
+ }
306
+ if (mode === "message" && content) {
307
+ eventStream$.sendTextMessageContent(content);
308
+ } else if (mode === "function" && ((_b = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _b.arguments)) {
309
+ eventStream$.sendActionExecutionArgs(toolCall.function.arguments);
310
+ }
311
+ }
312
+ if (mode === "message") {
313
+ eventStream$.sendTextMessageEnd();
314
+ } else if (mode === "function") {
315
+ eventStream$.sendActionExecutionEnd();
316
+ }
317
+ eventStream$.complete();
318
+ });
319
+ return {};
320
+ }
321
+ };
322
+ __name(OpenAIAdapter, "OpenAIAdapter");
323
+
324
+ // src/service-adapters/openai/openai-assistant-adapter.ts
325
+ var import_openai2 = __toESM(require("openai"));
326
+ var OpenAIAssistantAdapter = class {
327
+ openai;
328
+ codeInterpreterEnabled;
329
+ assistantId;
330
+ fileSearchEnabled;
331
+ constructor(params) {
332
+ this.openai = params.openai || new import_openai2.default({});
333
+ this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;
334
+ this.fileSearchEnabled = params.fileSearchEnabled === false || true;
335
+ this.assistantId = params.assistantId;
336
+ }
337
+ async process({ messages, actions, eventSource, threadId, runId }) {
338
+ threadId || (threadId = (await this.openai.beta.threads.create()).id);
339
+ const lastMessage = messages.at(-1);
340
+ let nextRunId = void 0;
341
+ if (lastMessage instanceof ResultMessage && runId) {
342
+ nextRunId = await this.submitToolOutputs(threadId, runId, messages, eventSource);
343
+ } else if (lastMessage instanceof TextMessage) {
344
+ nextRunId = await this.submitUserMessage(threadId, messages, actions, eventSource);
345
+ } else {
346
+ throw new Error("No actionable message found in the messages");
347
+ }
348
+ return {
349
+ threadId,
350
+ runId: nextRunId
351
+ };
352
+ }
353
+ async submitToolOutputs(threadId, runId, messages, eventSource) {
354
+ let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);
355
+ if (!run.required_action) {
356
+ throw new Error("No tool outputs required");
357
+ }
358
+ const toolCallsIds = run.required_action.submit_tool_outputs.tool_calls.map((toolCall) => toolCall.id);
359
+ const resultMessages = messages.filter((message) => message instanceof ResultMessage && toolCallsIds.includes(message.actionExecutionId));
360
+ if (toolCallsIds.length != resultMessages.length) {
361
+ throw new Error("Number of function results does not match the number of tool calls");
362
+ }
363
+ const toolOutputs = resultMessages.map((message) => {
364
+ return {
365
+ tool_call_id: message.actionExecutionId,
366
+ output: message.result
367
+ };
368
+ });
369
+ const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {
370
+ tool_outputs: toolOutputs
371
+ });
372
+ await this.streamResponse(stream, eventSource);
373
+ return runId;
374
+ }
375
+ async submitUserMessage(threadId, messages, actions, eventSource) {
376
+ messages = [
377
+ ...messages
378
+ ];
379
+ const instructionsMessage = messages.shift();
380
+ const instructions = instructionsMessage instanceof TextMessage ? instructionsMessage.content : "";
381
+ const userMessage = messages.map(convertMessageToOpenAIMessage).map(convertSystemMessageToAssistantAPI).at(-1);
382
+ if (userMessage.role !== "user") {
383
+ throw new Error("No user message found");
384
+ }
385
+ await this.openai.beta.threads.messages.create(threadId, {
386
+ role: "user",
387
+ content: userMessage.content
388
+ });
389
+ const openaiTools = actions.map(convertActionInputToOpenAITool);
390
+ const tools = [
391
+ ...openaiTools,
392
+ ...this.codeInterpreterEnabled ? [
393
+ {
394
+ type: "code_interpreter"
395
+ }
396
+ ] : [],
397
+ ...this.fileSearchEnabled ? [
398
+ {
399
+ type: "file_search"
400
+ }
401
+ ] : []
402
+ ];
403
+ let stream = this.openai.beta.threads.runs.stream(threadId, {
404
+ assistant_id: this.assistantId,
405
+ instructions,
406
+ tools
407
+ });
408
+ await this.streamResponse(stream, eventSource);
409
+ return getRunIdFromStream(stream);
410
+ }
411
+ async streamResponse(stream, eventSource) {
412
+ eventSource.stream(async (eventStream$) => {
413
+ var _a, _b, _c, _d, _e, _f;
414
+ let inFunctionCall = false;
415
+ for await (const chunk of stream) {
416
+ switch (chunk.event) {
417
+ case "thread.message.created":
418
+ if (inFunctionCall) {
419
+ eventStream$.sendActionExecutionEnd();
420
+ }
421
+ eventStream$.sendTextMessageStart(chunk.data.id);
422
+ break;
423
+ case "thread.message.delta":
424
+ if (((_a = chunk.data.delta.content) == null ? void 0 : _a[0].type) === "text") {
425
+ eventStream$.sendTextMessageContent((_b = chunk.data.delta.content) == null ? void 0 : _b[0].text.value);
426
+ }
427
+ break;
428
+ case "thread.message.completed":
429
+ eventStream$.sendTextMessageEnd();
430
+ break;
431
+ case "thread.run.step.delta":
432
+ let toolCallId;
433
+ let toolCallName;
434
+ let toolCallArgs;
435
+ if (chunk.data.delta.step_details.type === "tool_calls" && ((_c = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _c[0].type) === "function") {
436
+ toolCallId = (_d = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _d[0].id;
437
+ toolCallName = (_e = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _e[0].function.name;
438
+ toolCallArgs = (_f = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _f[0].function.arguments;
439
+ }
440
+ if (toolCallName && toolCallId) {
441
+ if (inFunctionCall) {
442
+ eventStream$.sendActionExecutionEnd();
443
+ }
444
+ inFunctionCall = true;
445
+ eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
446
+ } else if (toolCallArgs) {
447
+ eventStream$.sendActionExecutionArgs(toolCallArgs);
448
+ }
449
+ break;
450
+ }
451
+ }
452
+ if (inFunctionCall) {
453
+ eventStream$.sendActionExecutionEnd();
454
+ }
455
+ eventStream$.complete();
456
+ });
457
+ }
458
+ };
459
+ __name(OpenAIAssistantAdapter, "OpenAIAssistantAdapter");
460
+ function getRunIdFromStream(stream) {
461
+ return new Promise((resolve, reject) => {
462
+ let runIdGetter = /* @__PURE__ */ __name((event) => {
463
+ if (event.event === "thread.run.created") {
464
+ const runId = event.data.id;
465
+ stream.off("event", runIdGetter);
466
+ resolve(runId);
467
+ }
468
+ }, "runIdGetter");
469
+ stream.on("event", runIdGetter);
470
+ });
471
+ }
472
+ __name(getRunIdFromStream, "getRunIdFromStream");
473
+
474
+ // src/service-adapters/google/google-genai-adapter.ts
475
+ var import_generative_ai = require("@google/generative-ai");
476
+
477
+ // src/service-adapters/google/utils.ts
478
+ function convertMessageToGoogleGenAIMessage(message) {
479
+ if (message instanceof TextMessage) {
480
+ const role = {
481
+ user: "user",
482
+ assistant: "model",
483
+ system: "user"
484
+ }[message.role];
485
+ const text = message.role === "system" ? "THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: " + message.content : message.content;
486
+ return {
487
+ role,
488
+ parts: [
489
+ {
490
+ text
491
+ }
492
+ ]
493
+ };
494
+ } else if (message instanceof ActionExecutionMessage) {
495
+ return {
496
+ role: "model",
497
+ parts: [
498
+ {
499
+ functionCall: {
500
+ name: message.name,
501
+ args: message.arguments
502
+ }
503
+ }
504
+ ]
505
+ };
506
+ } else if (message instanceof ResultMessage) {
507
+ return {
508
+ role: "model",
509
+ parts: [
510
+ {
511
+ functionResponse: {
512
+ name: message.actionName,
513
+ response: {
514
+ name: message.actionName,
515
+ content: tryParseJson(message.result)
516
+ }
517
+ }
518
+ }
519
+ ]
520
+ };
521
+ }
522
+ }
523
+ __name(convertMessageToGoogleGenAIMessage, "convertMessageToGoogleGenAIMessage");
524
+ function transformActionToGoogleGenAITool(action) {
525
+ const name = action.name;
526
+ const description = action.description;
527
+ const parameters = JSON.parse(action.jsonSchema);
528
+ const transformProperties = /* @__PURE__ */ __name((props) => {
529
+ for (const key in props) {
530
+ if (props[key].type) {
531
+ props[key].type = props[key].type.toUpperCase();
532
+ }
533
+ if (props[key].properties) {
534
+ transformProperties(props[key].properties);
535
+ }
536
+ }
537
+ }, "transformProperties");
538
+ transformProperties(parameters);
539
+ return {
540
+ functionDeclarations: [
541
+ {
542
+ name,
543
+ description,
544
+ parameters
545
+ }
546
+ ]
547
+ };
548
+ }
549
+ __name(transformActionToGoogleGenAITool, "transformActionToGoogleGenAITool");
550
+ function tryParseJson(str) {
551
+ if (!str) {
552
+ return "";
553
+ }
554
+ try {
555
+ return JSON.parse(str);
556
+ } catch (e) {
557
+ return str;
558
+ }
559
+ }
560
+ __name(tryParseJson, "tryParseJson");
561
+
562
+ // src/service-adapters/google/google-genai-adapter.ts
563
+ var import_nanoid = require("nanoid");
564
+ var GoogleGenerativeAIAdapter = class {
565
+ model;
566
+ constructor(options) {
567
+ if (options == null ? void 0 : options.model) {
568
+ this.model = options.model;
569
+ } else {
570
+ const genAI = new import_generative_ai.GoogleGenerativeAI(process.env["GOOGLE_API_KEY"]);
571
+ this.model = genAI.getGenerativeModel({
572
+ model: "gemini-pro"
573
+ });
574
+ }
575
+ }
576
+ async process(request) {
577
+ const { messages, actions, eventSource } = request;
578
+ const history = messages.slice(1, -1).map(convertMessageToGoogleGenAIMessage);
579
+ const currentMessage = convertMessageToGoogleGenAIMessage(messages.at(-1));
580
+ if (!currentMessage) {
581
+ throw new Error("No current message");
582
+ }
583
+ let systemMessage;
584
+ const firstMessage = messages.at(0);
585
+ if (firstMessage instanceof TextMessage && firstMessage.role === "system") {
586
+ systemMessage = firstMessage.content.trim();
587
+ } else {
588
+ throw new Error("First message is not a system message");
589
+ }
590
+ const tools = actions.map(transformActionToGoogleGenAITool);
591
+ const isFirstGenGeminiPro = this.model.model === "gemini-pro" || this.model.model === "models/gemini-pro";
592
+ const chat = this.model.startChat({
593
+ history: [
594
+ ...history,
595
+ // gemini-pro does not support system instructions, so we need to add them to the history
596
+ ...isFirstGenGeminiPro ? [
597
+ {
598
+ role: "user",
599
+ parts: [
600
+ {
601
+ text: systemMessage
602
+ }
603
+ ]
604
+ }
605
+ ] : []
606
+ ],
607
+ // only gemini-1.5-pro-latest and later supports setting system instructions
608
+ ...isFirstGenGeminiPro ? {} : {
609
+ systemInstruction: {
610
+ role: "user",
611
+ parts: [
612
+ {
613
+ text: systemMessage
614
+ }
615
+ ]
616
+ }
617
+ },
618
+ tools
619
+ });
620
+ const result = await chat.sendMessageStream(currentMessage.parts);
621
+ eventSource.stream(async (eventStream$) => {
622
+ let isTextMessage = false;
623
+ for await (const chunk of result.stream) {
624
+ const chunkText = chunk.text();
625
+ if (!isTextMessage) {
626
+ isTextMessage = true;
627
+ eventStream$.sendTextMessageStart((0, import_nanoid.nanoid)());
628
+ }
629
+ eventStream$.sendTextMessageContent(chunkText);
630
+ }
631
+ if (isTextMessage) {
632
+ eventStream$.sendTextMessageEnd();
633
+ }
634
+ let calls = (await result.response).functionCalls();
635
+ if (calls) {
636
+ for (let call of calls) {
637
+ eventStream$.sendActionExecution((0, import_nanoid.nanoid)(), call.name, JSON.stringify(replaceNewlinesInObject(call.args)));
638
+ }
639
+ }
640
+ eventStream$.complete();
641
+ });
642
+ return {};
643
+ }
644
+ };
645
+ __name(GoogleGenerativeAIAdapter, "GoogleGenerativeAIAdapter");
646
+ function replaceNewlinesInObject(obj) {
647
+ if (typeof obj === "string") {
648
+ return obj.replace(/\\\\n/g, "\n");
649
+ } else if (Array.isArray(obj)) {
650
+ return obj.map(replaceNewlinesInObject);
651
+ } else if (typeof obj === "object" && obj !== null) {
652
+ const newObj = {};
653
+ for (const key in obj) {
654
+ if (obj.hasOwnProperty(key)) {
655
+ newObj[key] = replaceNewlinesInObject(obj[key]);
656
+ }
657
+ }
658
+ return newObj;
659
+ }
660
+ return obj;
661
+ }
662
+ __name(replaceNewlinesInObject, "replaceNewlinesInObject");
663
+
664
+ // src/service-adapters/langchain/utils.ts
665
+ var import_messages = require("@langchain/core/messages");
666
+ var import_tools = require("@langchain/core/tools");
667
+ var import_zod = require("zod");
668
+ var import_nanoid2 = require("nanoid");
669
+ function convertMessageToLangChainMessage(message) {
670
+ if (message instanceof TextMessage) {
671
+ if (message.role == "user") {
672
+ return new import_messages.HumanMessage(message.content);
673
+ } else if (message.role == "assistant") {
674
+ return new import_messages.AIMessage(message.content);
675
+ } else if (message.role === "system") {
676
+ return new import_messages.SystemMessage(message.content);
677
+ }
678
+ } else if (message instanceof ActionExecutionMessage) {
679
+ return new import_messages.AIMessage({
680
+ content: "",
681
+ tool_calls: [
682
+ {
683
+ id: message.id,
684
+ args: message.arguments,
685
+ name: message.name
686
+ }
687
+ ]
688
+ });
689
+ } else if (message instanceof ResultMessage) {
690
+ return new import_messages.ToolMessage({
691
+ content: message.result,
692
+ tool_call_id: message.actionExecutionId
693
+ });
694
+ }
695
+ }
696
+ __name(convertMessageToLangChainMessage, "convertMessageToLangChainMessage");
697
+ function convertJsonSchemaToZodSchema(jsonSchema, required) {
698
+ if (jsonSchema.type === "object") {
699
+ const spec = {};
700
+ for (const [key, value] of Object.entries(jsonSchema.properties)) {
701
+ spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);
702
+ }
703
+ let schema = import_zod.z.object(spec);
704
+ return !required ? schema.optional() : schema;
705
+ } else if (jsonSchema.type === "string") {
706
+ let schema = import_zod.z.string().describe(jsonSchema.description);
707
+ return !required ? schema.optional() : schema;
708
+ } else if (jsonSchema.type === "number") {
709
+ let schema = import_zod.z.number().describe(jsonSchema.description);
710
+ return !required ? schema.optional() : schema;
711
+ } else if (jsonSchema.type === "boolean") {
712
+ let schema = import_zod.z.boolean().describe(jsonSchema.description);
713
+ return !required ? schema.optional() : schema;
714
+ } else if (jsonSchema.type === "array") {
715
+ let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, false);
716
+ let schema = import_zod.z.array(itemSchema);
717
+ return !required ? schema.optional() : schema;
718
+ }
719
+ }
720
+ __name(convertJsonSchemaToZodSchema, "convertJsonSchemaToZodSchema");
721
+ function convertActionInputToLangChainTool(actionInput) {
722
+ return new import_tools.DynamicStructuredTool({
723
+ name: actionInput.name,
724
+ description: actionInput.description,
725
+ schema: convertJsonSchemaToZodSchema(JSON.parse(actionInput.jsonSchema), true),
726
+ func: async () => {
727
+ return "";
728
+ }
729
+ });
730
+ }
731
+ __name(convertActionInputToLangChainTool, "convertActionInputToLangChainTool");
732
+ async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
733
+ var _a, _b, _c, _d, _e, _f, _g, _h;
734
+ if (typeof result === "string") {
735
+ if (!actionExecution) {
736
+ eventStream$.sendTextMessage((0, import_nanoid2.nanoid)(), result);
737
+ } else {
738
+ eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);
739
+ }
740
+ } else if (result instanceof import_messages.AIMessage) {
741
+ if (result.content) {
742
+ eventStream$.sendTextMessage((0, import_nanoid2.nanoid)(), result.content);
743
+ }
744
+ for (const toolCall of result.tool_calls) {
745
+ eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid2.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
746
+ }
747
+ } else if (result instanceof import_messages.BaseMessageChunk) {
748
+ if ((_a = result.lc_kwargs) == null ? void 0 : _a.content) {
749
+ eventStream$.sendTextMessage((0, import_nanoid2.nanoid)(), result.content);
750
+ }
751
+ if ((_b = result.lc_kwargs) == null ? void 0 : _b.tool_calls) {
752
+ for (const toolCall of (_c = result.lc_kwargs) == null ? void 0 : _c.tool_calls) {
753
+ eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid2.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
754
+ }
755
+ }
756
+ } else if ("getReader" in result) {
757
+ let reader = result.getReader();
758
+ let mode = null;
759
+ while (true) {
760
+ try {
761
+ const { done, value } = await reader.read();
762
+ let toolCallName = void 0;
763
+ let toolCallId = void 0;
764
+ let toolCallArgs = void 0;
765
+ let hasToolCall = false;
766
+ let content = value.content;
767
+ if (value instanceof import_messages.AIMessageChunk) {
768
+ let chunk = (_d = value.tool_call_chunks) == null ? void 0 : _d[0];
769
+ toolCallName = chunk == null ? void 0 : chunk.name;
770
+ toolCallId = chunk == null ? void 0 : chunk.id;
771
+ toolCallArgs = chunk == null ? void 0 : chunk.args;
772
+ hasToolCall = chunk != void 0;
773
+ } else if (value instanceof import_messages.BaseMessageChunk) {
774
+ let chunk = (_f = (_e = value.additional_kwargs) == null ? void 0 : _e.tool_calls) == null ? void 0 : _f[0];
775
+ toolCallName = (_g = chunk == null ? void 0 : chunk.function) == null ? void 0 : _g.name;
776
+ toolCallId = chunk == null ? void 0 : chunk.id;
777
+ toolCallArgs = (_h = chunk == null ? void 0 : chunk.function) == null ? void 0 : _h.arguments;
778
+ hasToolCall = (chunk == null ? void 0 : chunk.function) != void 0;
779
+ }
780
+ if (mode === "message" && (toolCallId || done)) {
781
+ mode = null;
782
+ eventStream$.sendTextMessageEnd();
783
+ } else if (mode === "function" && (!hasToolCall || done)) {
784
+ mode = null;
785
+ eventStream$.sendActionExecutionEnd();
786
+ }
787
+ if (done) {
788
+ break;
789
+ }
790
+ if (mode === null) {
791
+ if (hasToolCall) {
792
+ mode = "function";
793
+ eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
794
+ } else if (content) {
795
+ mode = "message";
796
+ eventStream$.sendTextMessageStart((0, import_nanoid2.nanoid)());
797
+ }
798
+ }
799
+ if (mode === "message" && content) {
800
+ eventStream$.sendTextMessageContent(content);
801
+ } else if (mode === "function" && toolCallArgs) {
802
+ eventStream$.sendActionExecutionArgs(toolCallArgs);
803
+ }
804
+ } catch (error) {
805
+ console.error("Error reading from stream", error);
806
+ break;
807
+ }
808
+ }
809
+ } else if (actionExecution) {
810
+ eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, JSON.stringify(result));
811
+ } else {
812
+ throw new Error("Invalid return type from LangChain function.");
813
+ }
814
+ eventStream$.complete();
815
+ }
816
+ __name(streamLangChainResponse, "streamLangChainResponse");
817
+
818
+ // src/service-adapters/langchain/langchain-adapter.ts
819
+ var LangChainAdapter = class {
820
+ options;
821
+ /**
822
+ * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.
823
+ */
824
+ constructor(options) {
825
+ this.options = options;
826
+ }
827
+ async process({ eventSource, model, actions, messages, threadId, runId }) {
828
+ const result = await this.options.chainFn({
829
+ messages: messages.map(convertMessageToLangChainMessage),
830
+ tools: actions.map(convertActionInputToLangChainTool),
831
+ model,
832
+ threadId,
833
+ runId
834
+ });
835
+ eventSource.stream(async (eventStream$) => {
836
+ await streamLangChainResponse({
837
+ result,
838
+ eventStream$
839
+ });
840
+ });
841
+ return {};
842
+ }
843
+ };
844
+ __name(LangChainAdapter, "LangChainAdapter");
845
+
846
+ // src/service-adapters/langchain/langserve.ts
847
+ var import_remote = require("langchain/runnables/remote");
848
+ var RemoteChain = class {
849
+ constructor(options) {
850
+ this.name = options.name;
851
+ this.description = options.description;
852
+ this.chainUrl = options.chainUrl;
853
+ this.parameters = options.parameters;
854
+ this.parameterType = options.parameterType || "multi";
855
+ }
856
+ async toAction() {
857
+ if (!this.parameters) {
858
+ await this.inferLangServeParameters();
859
+ }
860
+ return {
861
+ name: this.name,
862
+ description: this.description,
863
+ parameters: this.parameters,
864
+ handler: async (args) => {
865
+ const runnable = new import_remote.RemoteRunnable({
866
+ url: this.chainUrl
867
+ });
868
+ let input;
869
+ if (this.parameterType === "single") {
870
+ input = args[Object.keys(args)[0]];
871
+ } else {
872
+ input = args;
873
+ }
874
+ return await runnable.invoke(input);
875
+ }
876
+ };
877
+ }
878
+ async inferLangServeParameters() {
879
+ const supportedTypes = [
880
+ "string",
881
+ "number",
882
+ "boolean"
883
+ ];
884
+ let schemaUrl = this.chainUrl.replace(/\/+$/, "") + "/input_schema";
885
+ let schema = await fetch(schemaUrl).then((res) => res.json()).catch(() => {
886
+ throw new Error("Failed to fetch langserve schema at " + schemaUrl);
887
+ });
888
+ if (supportedTypes.includes(schema.type)) {
889
+ this.parameterType = "single";
890
+ this.parameters = [
891
+ {
892
+ name: "input",
893
+ type: schema.type,
894
+ description: "The input to the chain"
895
+ }
896
+ ];
897
+ } else if (schema.type === "object") {
898
+ this.parameterType = "multi";
899
+ this.parameters = Object.keys(schema.properties).map((key) => {
900
+ var _a;
901
+ let property = schema.properties[key];
902
+ if (!supportedTypes.includes(property.type)) {
903
+ throw new Error("Unsupported schema type");
904
+ }
905
+ return {
906
+ name: key,
907
+ type: property.type,
908
+ description: property.description || "",
909
+ required: ((_a = schema.required) == null ? void 0 : _a.includes(key)) || false
910
+ };
911
+ });
912
+ } else {
913
+ throw new Error("Unsupported schema type");
914
+ }
915
+ }
916
+ };
917
+ __name(RemoteChain, "RemoteChain");
918
+
919
+ // src/lib/copilot-cloud.ts
920
+ var import_shared = require("@copilotkit/shared");
921
+ var CopilotCloud = class {
922
+ };
923
+ __name(CopilotCloud, "CopilotCloud");
924
+ var RemoteCopilotCloud = class extends CopilotCloud {
925
+ cloudApiUrl;
926
+ constructor(cloudApiUrl = import_shared.COPILOT_CLOUD_API_URL) {
927
+ super();
928
+ this.cloudApiUrl = cloudApiUrl;
929
+ }
930
+ async checkGuardrailsInput({ cloud, publicApiKey, messages }) {
931
+ const url = `${this.cloudApiUrl}/${import_shared.COPILOT_CLOUD_VERSION}/copilotkit/guardrails/input`;
932
+ const response = await fetch(url, {
933
+ method: "PUT",
934
+ headers: {
935
+ "Content-Type": "application/json",
936
+ [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey
937
+ },
938
+ body: JSON.stringify({
939
+ messages,
940
+ cloud
941
+ })
942
+ });
943
+ if (!response.ok) {
944
+ let message = response.statusText;
945
+ try {
946
+ const json2 = await response.json();
947
+ if (json2.message) {
948
+ message = json2.message;
949
+ }
950
+ } catch (error) {
951
+ }
952
+ throw new Error("Failed to check input guardrails: " + message);
953
+ }
954
+ const json = await response.json();
955
+ return {
956
+ status: json.status,
957
+ reason: json.reason
958
+ };
959
+ }
960
+ };
961
+ __name(RemoteCopilotCloud, "RemoteCopilotCloud");
962
+
963
+ // src/service-adapters/events.ts
964
+ var import_rxjs = require("rxjs");
965
+ var RuntimeEventTypes;
966
+ (function(RuntimeEventTypes2) {
967
+ RuntimeEventTypes2["TextMessageStart"] = "TextMessageStart";
968
+ RuntimeEventTypes2["TextMessageContent"] = "TextMessageContent";
969
+ RuntimeEventTypes2["TextMessageEnd"] = "TextMessageEnd";
970
+ RuntimeEventTypes2["ActionExecutionStart"] = "ActionExecutionStart";
971
+ RuntimeEventTypes2["ActionExecutionArgs"] = "ActionExecutionArgs";
972
+ RuntimeEventTypes2["ActionExecutionEnd"] = "ActionExecutionEnd";
973
+ RuntimeEventTypes2["ActionExecutionResult"] = "ActionExecutionResult";
974
+ })(RuntimeEventTypes || (RuntimeEventTypes = {}));
975
+ var RuntimeEventSubject = class extends import_rxjs.ReplaySubject {
976
+ constructor() {
977
+ super();
978
+ }
979
+ sendTextMessageStart(messageId) {
980
+ this.next({
981
+ type: "TextMessageStart",
982
+ messageId
983
+ });
984
+ }
985
+ sendTextMessageContent(content) {
986
+ this.next({
987
+ type: "TextMessageContent",
988
+ content
989
+ });
990
+ }
991
+ sendTextMessageEnd() {
992
+ this.next({
993
+ type: "TextMessageEnd"
994
+ });
995
+ }
996
+ sendTextMessage(messageId, content) {
997
+ this.sendTextMessageStart(messageId);
998
+ this.sendTextMessageContent(content);
999
+ this.sendTextMessageEnd();
1000
+ }
1001
+ sendActionExecutionStart(actionExecutionId, actionName) {
1002
+ this.next({
1003
+ type: "ActionExecutionStart",
1004
+ actionExecutionId,
1005
+ actionName
1006
+ });
1007
+ }
1008
+ sendActionExecutionArgs(args) {
1009
+ this.next({
1010
+ type: "ActionExecutionArgs",
1011
+ args
1012
+ });
1013
+ }
1014
+ sendActionExecutionEnd() {
1015
+ this.next({
1016
+ type: "ActionExecutionEnd"
1017
+ });
1018
+ }
1019
+ sendActionExecution(actionExecutionId, toolName, args) {
1020
+ this.sendActionExecutionStart(actionExecutionId, toolName);
1021
+ this.sendActionExecutionArgs(args);
1022
+ this.sendActionExecutionEnd();
1023
+ }
1024
+ sendActionExecutionResult(actionExecutionId, actionName, result) {
1025
+ this.next({
1026
+ type: "ActionExecutionResult",
1027
+ actionName,
1028
+ actionExecutionId,
1029
+ result
1030
+ });
1031
+ }
1032
+ };
1033
+ __name(RuntimeEventSubject, "RuntimeEventSubject");
1034
+ var RuntimeEventSource = class {
1035
+ eventStream$ = new RuntimeEventSubject();
1036
+ callback;
1037
+ async stream(callback) {
1038
+ this.callback = callback;
1039
+ }
1040
+ process(serversideActions) {
1041
+ this.callback(this.eventStream$).catch((error) => {
1042
+ console.error("Error in event source callback", error);
1043
+ });
1044
+ return this.eventStream$.pipe(
1045
+ // mark tools for server side execution
1046
+ (0, import_rxjs.map)((event) => {
1047
+ if (event.type === "ActionExecutionStart") {
1048
+ event.scope = serversideActions.find((action) => action.name === event.actionName) ? "server" : "client";
1049
+ }
1050
+ return event;
1051
+ }),
1052
+ // track state
1053
+ (0, import_rxjs.scan)((acc, event) => {
1054
+ if (event.type === "ActionExecutionStart") {
1055
+ acc.callActionServerSide = event.scope === "server";
1056
+ acc.args = "";
1057
+ acc.actionExecutionId = event.actionExecutionId;
1058
+ if (acc.callActionServerSide) {
1059
+ acc.action = serversideActions.find((action) => action.name === event.actionName);
1060
+ }
1061
+ } else if (event.type === "ActionExecutionArgs") {
1062
+ acc.args += event.args;
1063
+ }
1064
+ acc.event = event;
1065
+ return acc;
1066
+ }, {
1067
+ event: null,
1068
+ callActionServerSide: false,
1069
+ args: "",
1070
+ actionExecutionId: null,
1071
+ action: null
1072
+ }),
1073
+ (0, import_rxjs.concatMap)((eventWithState) => {
1074
+ if (eventWithState.event.type === "ActionExecutionEnd" && eventWithState.callActionServerSide) {
1075
+ const toolCallEventStream$ = new RuntimeEventSubject();
1076
+ executeAction(toolCallEventStream$, eventWithState.action, eventWithState.args, eventWithState.actionExecutionId).catch((error) => {
1077
+ console.error(error);
1078
+ });
1079
+ return (0, import_rxjs.concat)((0, import_rxjs.of)(eventWithState.event), toolCallEventStream$);
1080
+ } else {
1081
+ return (0, import_rxjs.of)(eventWithState.event);
1082
+ }
1083
+ })
1084
+ );
1085
+ }
1086
+ };
1087
+ __name(RuntimeEventSource, "RuntimeEventSource");
1088
+ async function executeAction(eventStream$, action, actionArguments, actionExecutionId) {
1089
+ let args = [];
1090
+ if (actionArguments) {
1091
+ args = JSON.parse(actionArguments);
1092
+ }
1093
+ const result = await action.handler(args);
1094
+ await streamLangChainResponse({
1095
+ result,
1096
+ eventStream$,
1097
+ actionExecution: {
1098
+ name: action.name,
1099
+ id: actionExecutionId
1100
+ }
1101
+ });
1102
+ }
1103
+ __name(executeAction, "executeAction");
1104
+
1105
+ // src/service-adapters/conversion.ts
1106
+ var import_class_transformer = require("class-transformer");
1107
+ function convertGqlInputToMessages(inputMessages) {
1108
+ const messages = [];
1109
+ for (const message of inputMessages) {
1110
+ if (message.textMessage) {
1111
+ messages.push((0, import_class_transformer.plainToInstance)(TextMessage, {
1112
+ id: message.id,
1113
+ createdAt: message.createdAt,
1114
+ role: message.textMessage.role,
1115
+ content: message.textMessage.content
1116
+ }));
1117
+ } else if (message.actionExecutionMessage) {
1118
+ messages.push((0, import_class_transformer.plainToInstance)(ActionExecutionMessage, {
1119
+ id: message.id,
1120
+ createdAt: message.createdAt,
1121
+ name: message.actionExecutionMessage.name,
1122
+ arguments: JSON.parse(message.actionExecutionMessage.arguments),
1123
+ scope: message.actionExecutionMessage.scope
1124
+ }));
1125
+ } else if (message.resultMessage) {
1126
+ messages.push((0, import_class_transformer.plainToInstance)(ResultMessage, {
1127
+ id: message.id,
1128
+ createdAt: message.createdAt,
1129
+ actionExecutionId: message.resultMessage.actionExecutionId,
1130
+ actionName: message.resultMessage.actionName,
1131
+ result: message.resultMessage.result
1132
+ }));
1133
+ }
1134
+ }
1135
+ return messages;
1136
+ }
1137
+ __name(convertGqlInputToMessages, "convertGqlInputToMessages");
1138
+
1139
+ // src/lib/copilot-runtime.ts
1140
+ var CopilotRuntime = class {
1141
+ actions = [];
1142
+ langserve = [];
1143
+ debug = false;
1144
+ copilotCloud;
1145
+ constructor(params) {
1146
+ this.actions = (params == null ? void 0 : params.actions) || [];
1147
+ for (const chain of (params == null ? void 0 : params.langserve) || []) {
1148
+ const remoteChain = new RemoteChain(chain);
1149
+ this.langserve.push(remoteChain.toAction());
1150
+ }
1151
+ this.debug = (params == null ? void 0 : params.debug) || false;
1152
+ this.copilotCloud = (params == null ? void 0 : params.copilotCloud) || new RemoteCopilotCloud();
1153
+ }
1154
+ addAction(action) {
1155
+ this.removeAction(action.name);
1156
+ this.actions.push(action);
1157
+ }
1158
+ removeAction(actionName) {
1159
+ this.actions = this.actions.filter((f) => f.name !== actionName);
1160
+ }
1161
+ async process({ serviceAdapter, messages, actions: clientSideActionsInput, threadId, runId, publicApiKey }) {
1162
+ const langserveFunctions = [];
1163
+ for (const chainPromise of this.langserve) {
1164
+ try {
1165
+ const chain = await chainPromise;
1166
+ langserveFunctions.push(chain);
1167
+ } catch (error) {
1168
+ console.error("Error loading langserve chain:", error);
1169
+ }
1170
+ }
1171
+ const serverSideActionsInput = [
1172
+ ...this.actions,
1173
+ ...langserveFunctions
1174
+ ].map((action) => ({
1175
+ name: action.name,
1176
+ description: action.description,
1177
+ jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters))
1178
+ }));
1179
+ const actions = flattenToolCallsNoDuplicates([
1180
+ ...serverSideActionsInput,
1181
+ ...clientSideActionsInput
1182
+ ]);
1183
+ try {
1184
+ const eventSource = new RuntimeEventSource();
1185
+ const result = await serviceAdapter.process({
1186
+ messages: convertGqlInputToMessages(messages),
1187
+ actions,
1188
+ threadId,
1189
+ runId,
1190
+ eventSource
1191
+ });
1192
+ return {
1193
+ threadId: result.threadId,
1194
+ runId: result.runId,
1195
+ eventSource
1196
+ };
1197
+ } catch (error) {
1198
+ console.error("Error getting response:", error);
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ };
1203
+ __name(CopilotRuntime, "CopilotRuntime");
1204
+ function flattenToolCallsNoDuplicates(toolsByPriority) {
1205
+ let allTools = [];
1206
+ const allToolNames = [];
1207
+ for (const tool of toolsByPriority) {
1208
+ if (!allToolNames.includes(tool.name)) {
1209
+ allTools.push(tool);
1210
+ allToolNames.push(tool.name);
1211
+ }
1212
+ }
1213
+ return allTools;
1214
+ }
1215
+ __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
1216
+ var CopilotBackend = class extends CopilotRuntime {
1217
+ };
1218
+ __name(CopilotBackend, "CopilotBackend");
1219
+
1220
+ // src/lib/integrations/shared.ts
1221
+ var import_type_graphql13 = require("type-graphql");
1222
+
1223
+ // src/graphql/resolvers/copilot.resolver.ts
1224
+ var import_type_graphql12 = require("type-graphql");
1225
+ var import_rxjs2 = require("rxjs");
1226
+
1227
+ // src/graphql/inputs/generate-copilot-response.input.ts
1228
+ var import_type_graphql8 = require("type-graphql");
1229
+
1230
+ // src/graphql/inputs/message.input.ts
1231
+ var import_type_graphql3 = require("type-graphql");
1232
+
1233
+ // src/graphql/types/enums.ts
1234
+ var import_type_graphql2 = require("type-graphql");
1235
+ var MessageRole;
1236
+ (function(MessageRole2) {
1237
+ MessageRole2["user"] = "user";
1238
+ MessageRole2["assistant"] = "assistant";
1239
+ MessageRole2["system"] = "system";
1240
+ })(MessageRole || (MessageRole = {}));
1241
+ var ActionExecutionScope;
1242
+ (function(ActionExecutionScope2) {
1243
+ ActionExecutionScope2["server"] = "server";
1244
+ ActionExecutionScope2["client"] = "client";
1245
+ })(ActionExecutionScope || (ActionExecutionScope = {}));
1246
+ (0, import_type_graphql2.registerEnumType)(MessageRole, {
1247
+ name: "MessageRole",
1248
+ description: "The role of the message"
1249
+ });
1250
+ (0, import_type_graphql2.registerEnumType)(ActionExecutionScope, {
1251
+ name: "ActionExecutionScope",
1252
+ description: "The scope of the action"
1253
+ });
1254
+
1255
+ // src/graphql/inputs/message.input.ts
1256
+ function _ts_decorate2(decorators, target, key, desc) {
1257
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1258
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1259
+ r = Reflect.decorate(decorators, target, key, desc);
1260
+ else
1261
+ for (var i = decorators.length - 1; i >= 0; i--)
1262
+ if (d = decorators[i])
1263
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1264
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1265
+ }
1266
+ __name(_ts_decorate2, "_ts_decorate");
1267
+ function _ts_metadata2(k, v) {
1268
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1269
+ return Reflect.metadata(k, v);
1270
+ }
1271
+ __name(_ts_metadata2, "_ts_metadata");
1272
+ var MessageInput = class extends BaseMessage {
1273
+ textMessage;
1274
+ actionExecutionMessage;
1275
+ resultMessage;
1276
+ };
1277
+ __name(MessageInput, "MessageInput");
1278
+ _ts_decorate2([
1279
+ (0, import_type_graphql3.Field)(() => TextMessageInput, {
1280
+ nullable: true
1281
+ }),
1282
+ _ts_metadata2("design:type", typeof TextMessageInput === "undefined" ? Object : TextMessageInput)
1283
+ ], MessageInput.prototype, "textMessage", void 0);
1284
+ _ts_decorate2([
1285
+ (0, import_type_graphql3.Field)(() => ActionExecutionMessageInput, {
1286
+ nullable: true
1287
+ }),
1288
+ _ts_metadata2("design:type", typeof ActionExecutionMessageInput === "undefined" ? Object : ActionExecutionMessageInput)
1289
+ ], MessageInput.prototype, "actionExecutionMessage", void 0);
1290
+ _ts_decorate2([
1291
+ (0, import_type_graphql3.Field)(() => ResultMessageInput, {
1292
+ nullable: true
1293
+ }),
1294
+ _ts_metadata2("design:type", typeof ResultMessageInput === "undefined" ? Object : ResultMessageInput)
1295
+ ], MessageInput.prototype, "resultMessage", void 0);
1296
+ MessageInput = _ts_decorate2([
1297
+ (0, import_type_graphql3.InputType)()
1298
+ ], MessageInput);
1299
+ var TextMessageInput = class {
1300
+ content;
1301
+ role;
1302
+ };
1303
+ __name(TextMessageInput, "TextMessageInput");
1304
+ _ts_decorate2([
1305
+ (0, import_type_graphql3.Field)(() => String),
1306
+ _ts_metadata2("design:type", String)
1307
+ ], TextMessageInput.prototype, "content", void 0);
1308
+ _ts_decorate2([
1309
+ (0, import_type_graphql3.Field)(() => MessageRole),
1310
+ _ts_metadata2("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
1311
+ ], TextMessageInput.prototype, "role", void 0);
1312
+ TextMessageInput = _ts_decorate2([
1313
+ (0, import_type_graphql3.InputType)()
1314
+ ], TextMessageInput);
1315
+ var ActionExecutionMessageInput = class {
1316
+ name;
1317
+ arguments;
1318
+ scope;
1319
+ };
1320
+ __name(ActionExecutionMessageInput, "ActionExecutionMessageInput");
1321
+ _ts_decorate2([
1322
+ (0, import_type_graphql3.Field)(() => String),
1323
+ _ts_metadata2("design:type", String)
1324
+ ], ActionExecutionMessageInput.prototype, "name", void 0);
1325
+ _ts_decorate2([
1326
+ (0, import_type_graphql3.Field)(() => String),
1327
+ _ts_metadata2("design:type", String)
1328
+ ], ActionExecutionMessageInput.prototype, "arguments", void 0);
1329
+ _ts_decorate2([
1330
+ (0, import_type_graphql3.Field)(() => ActionExecutionScope),
1331
+ _ts_metadata2("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
1332
+ ], ActionExecutionMessageInput.prototype, "scope", void 0);
1333
+ ActionExecutionMessageInput = _ts_decorate2([
1334
+ (0, import_type_graphql3.InputType)()
1335
+ ], ActionExecutionMessageInput);
1336
+ var ResultMessageInput = class {
1337
+ actionExecutionId;
1338
+ actionName;
1339
+ result;
1340
+ };
1341
+ __name(ResultMessageInput, "ResultMessageInput");
1342
+ _ts_decorate2([
1343
+ (0, import_type_graphql3.Field)(() => String),
1344
+ _ts_metadata2("design:type", String)
1345
+ ], ResultMessageInput.prototype, "actionExecutionId", void 0);
1346
+ _ts_decorate2([
1347
+ (0, import_type_graphql3.Field)(() => String),
1348
+ _ts_metadata2("design:type", String)
1349
+ ], ResultMessageInput.prototype, "actionName", void 0);
1350
+ _ts_decorate2([
1351
+ (0, import_type_graphql3.Field)(() => String),
1352
+ _ts_metadata2("design:type", String)
1353
+ ], ResultMessageInput.prototype, "result", void 0);
1354
+ ResultMessageInput = _ts_decorate2([
1355
+ (0, import_type_graphql3.InputType)()
1356
+ ], ResultMessageInput);
1357
+
1358
+ // src/graphql/inputs/frontend.input.ts
1359
+ var import_type_graphql5 = require("type-graphql");
1360
+
1361
+ // src/graphql/inputs/action.input.ts
1362
+ var import_type_graphql4 = require("type-graphql");
1363
+ function _ts_decorate3(decorators, target, key, desc) {
1364
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1365
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1366
+ r = Reflect.decorate(decorators, target, key, desc);
1367
+ else
1368
+ for (var i = decorators.length - 1; i >= 0; i--)
1369
+ if (d = decorators[i])
1370
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1371
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1372
+ }
1373
+ __name(_ts_decorate3, "_ts_decorate");
1374
+ function _ts_metadata3(k, v) {
1375
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1376
+ return Reflect.metadata(k, v);
1377
+ }
1378
+ __name(_ts_metadata3, "_ts_metadata");
1379
+ var ActionInput = class {
1380
+ name;
1381
+ description;
1382
+ jsonSchema;
1383
+ };
1384
+ __name(ActionInput, "ActionInput");
1385
+ _ts_decorate3([
1386
+ (0, import_type_graphql4.Field)(() => String),
1387
+ _ts_metadata3("design:type", String)
1388
+ ], ActionInput.prototype, "name", void 0);
1389
+ _ts_decorate3([
1390
+ (0, import_type_graphql4.Field)(() => String),
1391
+ _ts_metadata3("design:type", String)
1392
+ ], ActionInput.prototype, "description", void 0);
1393
+ _ts_decorate3([
1394
+ (0, import_type_graphql4.Field)(() => String),
1395
+ _ts_metadata3("design:type", String)
1396
+ ], ActionInput.prototype, "jsonSchema", void 0);
1397
+ ActionInput = _ts_decorate3([
1398
+ (0, import_type_graphql4.InputType)()
1399
+ ], ActionInput);
1400
+
1401
+ // src/graphql/inputs/frontend.input.ts
1402
+ function _ts_decorate4(decorators, target, key, desc) {
1403
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1404
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1405
+ r = Reflect.decorate(decorators, target, key, desc);
1406
+ else
1407
+ for (var i = decorators.length - 1; i >= 0; i--)
1408
+ if (d = decorators[i])
1409
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1410
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1411
+ }
1412
+ __name(_ts_decorate4, "_ts_decorate");
1413
+ function _ts_metadata4(k, v) {
1414
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1415
+ return Reflect.metadata(k, v);
1416
+ }
1417
+ __name(_ts_metadata4, "_ts_metadata");
1418
+ var FrontendInput = class {
1419
+ toDeprecate_fullContext;
1420
+ actions;
1421
+ };
1422
+ __name(FrontendInput, "FrontendInput");
1423
+ _ts_decorate4([
1424
+ (0, import_type_graphql5.Field)(() => String, {
1425
+ nullable: true
1426
+ }),
1427
+ _ts_metadata4("design:type", String)
1428
+ ], FrontendInput.prototype, "toDeprecate_fullContext", void 0);
1429
+ _ts_decorate4([
1430
+ (0, import_type_graphql5.Field)(() => [
1431
+ ActionInput
1432
+ ]),
1433
+ _ts_metadata4("design:type", Array)
1434
+ ], FrontendInput.prototype, "actions", void 0);
1435
+ FrontendInput = _ts_decorate4([
1436
+ (0, import_type_graphql5.InputType)()
1437
+ ], FrontendInput);
1438
+
1439
+ // src/graphql/inputs/cloud.input.ts
1440
+ var import_type_graphql7 = require("type-graphql");
1441
+
1442
+ // src/graphql/inputs/cloud-guardrails.input.ts
1443
+ var import_type_graphql6 = require("type-graphql");
1444
+ function _ts_decorate5(decorators, target, key, desc) {
1445
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1446
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1447
+ r = Reflect.decorate(decorators, target, key, desc);
1448
+ else
1449
+ for (var i = decorators.length - 1; i >= 0; i--)
1450
+ if (d = decorators[i])
1451
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1452
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1453
+ }
1454
+ __name(_ts_decorate5, "_ts_decorate");
1455
+ function _ts_metadata5(k, v) {
1456
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1457
+ return Reflect.metadata(k, v);
1458
+ }
1459
+ __name(_ts_metadata5, "_ts_metadata");
1460
+ var GuardrailsRuleInput = class {
1461
+ id;
1462
+ allowList = [];
1463
+ denyList = [];
1464
+ };
1465
+ __name(GuardrailsRuleInput, "GuardrailsRuleInput");
1466
+ _ts_decorate5([
1467
+ (0, import_type_graphql6.Field)(() => String),
1468
+ _ts_metadata5("design:type", String)
1469
+ ], GuardrailsRuleInput.prototype, "id", void 0);
1470
+ _ts_decorate5([
1471
+ (0, import_type_graphql6.Field)(() => [
1472
+ String
1473
+ ], {
1474
+ nullable: true
1475
+ }),
1476
+ _ts_metadata5("design:type", Array)
1477
+ ], GuardrailsRuleInput.prototype, "allowList", void 0);
1478
+ _ts_decorate5([
1479
+ (0, import_type_graphql6.Field)(() => [
1480
+ String
1481
+ ], {
1482
+ nullable: true
1483
+ }),
1484
+ _ts_metadata5("design:type", Array)
1485
+ ], GuardrailsRuleInput.prototype, "denyList", void 0);
1486
+ GuardrailsRuleInput = _ts_decorate5([
1487
+ (0, import_type_graphql6.InputType)()
1488
+ ], GuardrailsRuleInput);
1489
+ var GuardrailsInput = class {
1490
+ inputValidationRules = [];
1491
+ };
1492
+ __name(GuardrailsInput, "GuardrailsInput");
1493
+ _ts_decorate5([
1494
+ (0, import_type_graphql6.Field)(() => [
1495
+ GuardrailsRuleInput
1496
+ ], {
1497
+ nullable: true
1498
+ }),
1499
+ _ts_metadata5("design:type", Array)
1500
+ ], GuardrailsInput.prototype, "inputValidationRules", void 0);
1501
+ GuardrailsInput = _ts_decorate5([
1502
+ (0, import_type_graphql6.InputType)()
1503
+ ], GuardrailsInput);
1504
+
1505
+ // src/graphql/inputs/cloud.input.ts
1506
+ function _ts_decorate6(decorators, target, key, desc) {
1507
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1508
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1509
+ r = Reflect.decorate(decorators, target, key, desc);
1510
+ else
1511
+ for (var i = decorators.length - 1; i >= 0; i--)
1512
+ if (d = decorators[i])
1513
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1514
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1515
+ }
1516
+ __name(_ts_decorate6, "_ts_decorate");
1517
+ function _ts_metadata6(k, v) {
1518
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1519
+ return Reflect.metadata(k, v);
1520
+ }
1521
+ __name(_ts_metadata6, "_ts_metadata");
1522
+ var CloudInput = class {
1523
+ guardrails;
1524
+ };
1525
+ __name(CloudInput, "CloudInput");
1526
+ _ts_decorate6([
1527
+ (0, import_type_graphql7.Field)(() => GuardrailsInput),
1528
+ _ts_metadata6("design:type", typeof GuardrailsInput === "undefined" ? Object : GuardrailsInput)
1529
+ ], CloudInput.prototype, "guardrails", void 0);
1530
+ CloudInput = _ts_decorate6([
1531
+ (0, import_type_graphql7.InputType)()
1532
+ ], CloudInput);
1533
+
1534
+ // src/graphql/inputs/generate-copilot-response.input.ts
1535
+ function _ts_decorate7(decorators, target, key, desc) {
1536
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1537
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1538
+ r = Reflect.decorate(decorators, target, key, desc);
1539
+ else
1540
+ for (var i = decorators.length - 1; i >= 0; i--)
1541
+ if (d = decorators[i])
1542
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1543
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1544
+ }
1545
+ __name(_ts_decorate7, "_ts_decorate");
1546
+ function _ts_metadata7(k, v) {
1547
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1548
+ return Reflect.metadata(k, v);
1549
+ }
1550
+ __name(_ts_metadata7, "_ts_metadata");
1551
+ var GenerateCopilotResponseInput = class {
1552
+ threadId;
1553
+ runId;
1554
+ messages;
1555
+ frontend;
1556
+ cloud;
1557
+ };
1558
+ __name(GenerateCopilotResponseInput, "GenerateCopilotResponseInput");
1559
+ _ts_decorate7([
1560
+ (0, import_type_graphql8.Field)(() => String, {
1561
+ nullable: true
1562
+ }),
1563
+ _ts_metadata7("design:type", String)
1564
+ ], GenerateCopilotResponseInput.prototype, "threadId", void 0);
1565
+ _ts_decorate7([
1566
+ (0, import_type_graphql8.Field)(() => String, {
1567
+ nullable: true
1568
+ }),
1569
+ _ts_metadata7("design:type", String)
1570
+ ], GenerateCopilotResponseInput.prototype, "runId", void 0);
1571
+ _ts_decorate7([
1572
+ (0, import_type_graphql8.Field)(() => [
1573
+ MessageInput
1574
+ ]),
1575
+ _ts_metadata7("design:type", Array)
1576
+ ], GenerateCopilotResponseInput.prototype, "messages", void 0);
1577
+ _ts_decorate7([
1578
+ (0, import_type_graphql8.Field)(() => FrontendInput),
1579
+ _ts_metadata7("design:type", typeof FrontendInput === "undefined" ? Object : FrontendInput)
1580
+ ], GenerateCopilotResponseInput.prototype, "frontend", void 0);
1581
+ _ts_decorate7([
1582
+ (0, import_type_graphql8.Field)(() => CloudInput, {
1583
+ nullable: true
1584
+ }),
1585
+ _ts_metadata7("design:type", typeof CloudInput === "undefined" ? Object : CloudInput)
1586
+ ], GenerateCopilotResponseInput.prototype, "cloud", void 0);
1587
+ GenerateCopilotResponseInput = _ts_decorate7([
1588
+ (0, import_type_graphql8.InputType)()
1589
+ ], GenerateCopilotResponseInput);
1590
+
1591
+ // src/graphql/types/copilot-response.type.ts
1592
+ var import_type_graphql11 = require("type-graphql");
1593
+
1594
+ // src/graphql/types/message-status.type.ts
1595
+ var import_type_graphql9 = require("type-graphql");
1596
+ function _ts_decorate8(decorators, target, key, desc) {
1597
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1598
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1599
+ r = Reflect.decorate(decorators, target, key, desc);
1600
+ else
1601
+ for (var i = decorators.length - 1; i >= 0; i--)
1602
+ if (d = decorators[i])
1603
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1604
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1605
+ }
1606
+ __name(_ts_decorate8, "_ts_decorate");
1607
+ function _ts_metadata8(k, v) {
1608
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1609
+ return Reflect.metadata(k, v);
1610
+ }
1611
+ __name(_ts_metadata8, "_ts_metadata");
1612
+ var MessageStatusCode;
1613
+ (function(MessageStatusCode2) {
1614
+ MessageStatusCode2["Pending"] = "pending";
1615
+ MessageStatusCode2["Success"] = "success";
1616
+ MessageStatusCode2["Failed"] = "failed";
1617
+ })(MessageStatusCode || (MessageStatusCode = {}));
1618
+ (0, import_type_graphql9.registerEnumType)(MessageStatusCode, {
1619
+ name: "MessageStatusCode"
1620
+ });
1621
+ var BaseMessageStatus = /* @__PURE__ */ __name(class BaseMessageStatus2 {
1622
+ code;
1623
+ }, "BaseMessageStatus");
1624
+ _ts_decorate8([
1625
+ (0, import_type_graphql9.Field)(() => MessageStatusCode),
1626
+ _ts_metadata8("design:type", String)
1627
+ ], BaseMessageStatus.prototype, "code", void 0);
1628
+ BaseMessageStatus = _ts_decorate8([
1629
+ (0, import_type_graphql9.ObjectType)()
1630
+ ], BaseMessageStatus);
1631
+ var PendingMessageStatus = class extends BaseMessageStatus {
1632
+ code = "pending";
1633
+ };
1634
+ __name(PendingMessageStatus, "PendingMessageStatus");
1635
+ PendingMessageStatus = _ts_decorate8([
1636
+ (0, import_type_graphql9.ObjectType)()
1637
+ ], PendingMessageStatus);
1638
+ var SuccessMessageStatus = class extends BaseMessageStatus {
1639
+ code = "success";
1640
+ };
1641
+ __name(SuccessMessageStatus, "SuccessMessageStatus");
1642
+ SuccessMessageStatus = _ts_decorate8([
1643
+ (0, import_type_graphql9.ObjectType)()
1644
+ ], SuccessMessageStatus);
1645
+ var FailedMessageStatus = class extends BaseMessageStatus {
1646
+ code = "failed";
1647
+ reason;
1648
+ };
1649
+ __name(FailedMessageStatus, "FailedMessageStatus");
1650
+ _ts_decorate8([
1651
+ (0, import_type_graphql9.Field)(() => String),
1652
+ _ts_metadata8("design:type", String)
1653
+ ], FailedMessageStatus.prototype, "reason", void 0);
1654
+ FailedMessageStatus = _ts_decorate8([
1655
+ (0, import_type_graphql9.ObjectType)()
1656
+ ], FailedMessageStatus);
1657
+ var MessageStatusUnion = (0, import_type_graphql9.createUnionType)({
1658
+ name: "MessageStatus",
1659
+ types: () => [
1660
+ PendingMessageStatus,
1661
+ SuccessMessageStatus,
1662
+ FailedMessageStatus
1663
+ ]
1664
+ });
1665
+
1666
+ // src/graphql/types/response-status.type.ts
1667
+ var import_type_graphql10 = require("type-graphql");
1668
+ function _ts_decorate9(decorators, target, key, desc) {
1669
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1670
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1671
+ r = Reflect.decorate(decorators, target, key, desc);
1672
+ else
1673
+ for (var i = decorators.length - 1; i >= 0; i--)
1674
+ if (d = decorators[i])
1675
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1676
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1677
+ }
1678
+ __name(_ts_decorate9, "_ts_decorate");
1679
+ function _ts_metadata9(k, v) {
1680
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1681
+ return Reflect.metadata(k, v);
1682
+ }
1683
+ __name(_ts_metadata9, "_ts_metadata");
1684
+ var ResponseStatusCode;
1685
+ (function(ResponseStatusCode2) {
1686
+ ResponseStatusCode2["Pending"] = "pending";
1687
+ ResponseStatusCode2["Success"] = "success";
1688
+ ResponseStatusCode2["Failed"] = "failed";
1689
+ })(ResponseStatusCode || (ResponseStatusCode = {}));
1690
+ (0, import_type_graphql10.registerEnumType)(ResponseStatusCode, {
1691
+ name: "ResponseStatusCode"
1692
+ });
1693
+ var BaseResponseStatus = /* @__PURE__ */ __name(class BaseResponseStatus2 {
1694
+ code;
1695
+ }, "BaseResponseStatus");
1696
+ _ts_decorate9([
1697
+ (0, import_type_graphql10.Field)(() => ResponseStatusCode),
1698
+ _ts_metadata9("design:type", String)
1699
+ ], BaseResponseStatus.prototype, "code", void 0);
1700
+ BaseResponseStatus = _ts_decorate9([
1701
+ (0, import_type_graphql10.InterfaceType)({
1702
+ resolveType(value) {
1703
+ if (value.code === "success") {
1704
+ return SuccessResponseStatus;
1705
+ } else if (value.code === "failed") {
1706
+ return FailedResponseStatus;
1707
+ } else if (value.code === "pending") {
1708
+ return PendingResponseStatus;
1709
+ }
1710
+ return void 0;
1711
+ }
1712
+ }),
1713
+ (0, import_type_graphql10.ObjectType)()
1714
+ ], BaseResponseStatus);
1715
+ var PendingResponseStatus = class extends BaseResponseStatus {
1716
+ code = "pending";
1717
+ };
1718
+ __name(PendingResponseStatus, "PendingResponseStatus");
1719
+ PendingResponseStatus = _ts_decorate9([
1720
+ (0, import_type_graphql10.ObjectType)({
1721
+ implements: BaseResponseStatus
1722
+ })
1723
+ ], PendingResponseStatus);
1724
+ var SuccessResponseStatus = class extends BaseResponseStatus {
1725
+ code = "success";
1726
+ };
1727
+ __name(SuccessResponseStatus, "SuccessResponseStatus");
1728
+ SuccessResponseStatus = _ts_decorate9([
1729
+ (0, import_type_graphql10.ObjectType)({
1730
+ implements: BaseResponseStatus
1731
+ })
1732
+ ], SuccessResponseStatus);
1733
+ var FailedResponseStatus = class extends BaseResponseStatus {
1734
+ code = "failed";
1735
+ reason;
1736
+ };
1737
+ __name(FailedResponseStatus, "FailedResponseStatus");
1738
+ _ts_decorate9([
1739
+ (0, import_type_graphql10.Field)(() => String),
1740
+ _ts_metadata9("design:type", String)
1741
+ ], FailedResponseStatus.prototype, "reason", void 0);
1742
+ FailedResponseStatus = _ts_decorate9([
1743
+ (0, import_type_graphql10.ObjectType)({
1744
+ implements: BaseResponseStatus
1745
+ })
1746
+ ], FailedResponseStatus);
1747
+ var ResponseStatusUnion = (0, import_type_graphql10.createUnionType)({
1748
+ name: "ResponseStatus",
1749
+ types: () => [
1750
+ PendingResponseStatus,
1751
+ SuccessResponseStatus,
1752
+ FailedResponseStatus
1753
+ ]
1754
+ });
1755
+
1756
+ // src/graphql/types/copilot-response.type.ts
1757
+ function _ts_decorate10(decorators, target, key, desc) {
1758
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1759
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1760
+ r = Reflect.decorate(decorators, target, key, desc);
1761
+ else
1762
+ for (var i = decorators.length - 1; i >= 0; i--)
1763
+ if (d = decorators[i])
1764
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1765
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1766
+ }
1767
+ __name(_ts_decorate10, "_ts_decorate");
1768
+ function _ts_metadata10(k, v) {
1769
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1770
+ return Reflect.metadata(k, v);
1771
+ }
1772
+ __name(_ts_metadata10, "_ts_metadata");
1773
+ var BaseMessageOutput = /* @__PURE__ */ __name(class BaseMessageOutput2 {
1774
+ id;
1775
+ createdAt;
1776
+ status;
1777
+ }, "BaseMessageOutput");
1778
+ _ts_decorate10([
1779
+ (0, import_type_graphql11.Field)(() => String),
1780
+ _ts_metadata10("design:type", String)
1781
+ ], BaseMessageOutput.prototype, "id", void 0);
1782
+ _ts_decorate10([
1783
+ (0, import_type_graphql11.Field)(() => Date),
1784
+ _ts_metadata10("design:type", typeof Date === "undefined" ? Object : Date)
1785
+ ], BaseMessageOutput.prototype, "createdAt", void 0);
1786
+ _ts_decorate10([
1787
+ (0, import_type_graphql11.Field)(() => MessageStatusUnion),
1788
+ _ts_metadata10("design:type", Object)
1789
+ ], BaseMessageOutput.prototype, "status", void 0);
1790
+ BaseMessageOutput = _ts_decorate10([
1791
+ (0, import_type_graphql11.InterfaceType)({
1792
+ resolveType(value) {
1793
+ if (value.hasOwnProperty("content")) {
1794
+ return TextMessageOutput;
1795
+ } else if (value.hasOwnProperty("name")) {
1796
+ return ActionExecutionMessageOutput;
1797
+ } else if (value.hasOwnProperty("result")) {
1798
+ return ResultMessageOutput;
1799
+ }
1800
+ return void 0;
1801
+ }
1802
+ })
1803
+ ], BaseMessageOutput);
1804
+ var TextMessageOutput = class {
1805
+ role;
1806
+ content;
1807
+ };
1808
+ __name(TextMessageOutput, "TextMessageOutput");
1809
+ _ts_decorate10([
1810
+ (0, import_type_graphql11.Field)(() => MessageRole),
1811
+ _ts_metadata10("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
1812
+ ], TextMessageOutput.prototype, "role", void 0);
1813
+ _ts_decorate10([
1814
+ (0, import_type_graphql11.Field)(() => [
1815
+ String
1816
+ ]),
1817
+ _ts_metadata10("design:type", Array)
1818
+ ], TextMessageOutput.prototype, "content", void 0);
1819
+ TextMessageOutput = _ts_decorate10([
1820
+ (0, import_type_graphql11.ObjectType)({
1821
+ implements: BaseMessageOutput
1822
+ })
1823
+ ], TextMessageOutput);
1824
+ var ActionExecutionMessageOutput = class {
1825
+ name;
1826
+ scope;
1827
+ arguments;
1828
+ };
1829
+ __name(ActionExecutionMessageOutput, "ActionExecutionMessageOutput");
1830
+ _ts_decorate10([
1831
+ (0, import_type_graphql11.Field)(() => String),
1832
+ _ts_metadata10("design:type", String)
1833
+ ], ActionExecutionMessageOutput.prototype, "name", void 0);
1834
+ _ts_decorate10([
1835
+ (0, import_type_graphql11.Field)(() => ActionExecutionScope),
1836
+ _ts_metadata10("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
1837
+ ], ActionExecutionMessageOutput.prototype, "scope", void 0);
1838
+ _ts_decorate10([
1839
+ (0, import_type_graphql11.Field)(() => [
1840
+ String
1841
+ ]),
1842
+ _ts_metadata10("design:type", Array)
1843
+ ], ActionExecutionMessageOutput.prototype, "arguments", void 0);
1844
+ ActionExecutionMessageOutput = _ts_decorate10([
1845
+ (0, import_type_graphql11.ObjectType)({
1846
+ implements: BaseMessageOutput
1847
+ })
1848
+ ], ActionExecutionMessageOutput);
1849
+ var ResultMessageOutput = class {
1850
+ actionExecutionId;
1851
+ actionName;
1852
+ result;
1853
+ };
1854
+ __name(ResultMessageOutput, "ResultMessageOutput");
1855
+ _ts_decorate10([
1856
+ (0, import_type_graphql11.Field)(() => String),
1857
+ _ts_metadata10("design:type", String)
1858
+ ], ResultMessageOutput.prototype, "actionExecutionId", void 0);
1859
+ _ts_decorate10([
1860
+ (0, import_type_graphql11.Field)(() => String),
1861
+ _ts_metadata10("design:type", String)
1862
+ ], ResultMessageOutput.prototype, "actionName", void 0);
1863
+ _ts_decorate10([
1864
+ (0, import_type_graphql11.Field)(() => String),
1865
+ _ts_metadata10("design:type", String)
1866
+ ], ResultMessageOutput.prototype, "result", void 0);
1867
+ ResultMessageOutput = _ts_decorate10([
1868
+ (0, import_type_graphql11.ObjectType)({
1869
+ implements: BaseMessageOutput
1870
+ })
1871
+ ], ResultMessageOutput);
1872
+ var CopilotResponse = class {
1873
+ threadId;
1874
+ status;
1875
+ runId;
1876
+ messages;
1877
+ };
1878
+ __name(CopilotResponse, "CopilotResponse");
1879
+ _ts_decorate10([
1880
+ (0, import_type_graphql11.Field)(() => String),
1881
+ _ts_metadata10("design:type", String)
1882
+ ], CopilotResponse.prototype, "threadId", void 0);
1883
+ _ts_decorate10([
1884
+ (0, import_type_graphql11.Field)(() => ResponseStatusUnion),
1885
+ _ts_metadata10("design:type", Object)
1886
+ ], CopilotResponse.prototype, "status", void 0);
1887
+ _ts_decorate10([
1888
+ (0, import_type_graphql11.Field)({
1889
+ nullable: true
1890
+ }),
1891
+ _ts_metadata10("design:type", String)
1892
+ ], CopilotResponse.prototype, "runId", void 0);
1893
+ _ts_decorate10([
1894
+ (0, import_type_graphql11.Field)(() => [
1895
+ BaseMessageOutput
1896
+ ]),
1897
+ _ts_metadata10("design:type", Array)
1898
+ ], CopilotResponse.prototype, "messages", void 0);
1899
+ CopilotResponse = _ts_decorate10([
1900
+ (0, import_type_graphql11.ObjectType)()
1901
+ ], CopilotResponse);
1902
+
1903
+ // src/graphql/resolvers/copilot.resolver.ts
1904
+ var import_graphql_yoga = require("graphql-yoga");
1905
+ var import_nanoid3 = require("nanoid");
1906
+ var import_graphql_scalars = require("graphql-scalars");
1907
+ function _ts_decorate11(decorators, target, key, desc) {
1908
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1909
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1910
+ r = Reflect.decorate(decorators, target, key, desc);
1911
+ else
1912
+ for (var i = decorators.length - 1; i >= 0; i--)
1913
+ if (d = decorators[i])
1914
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1915
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1916
+ }
1917
+ __name(_ts_decorate11, "_ts_decorate");
1918
+ function _ts_metadata11(k, v) {
1919
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
1920
+ return Reflect.metadata(k, v);
1921
+ }
1922
+ __name(_ts_metadata11, "_ts_metadata");
1923
+ function _ts_param(paramIndex, decorator) {
1924
+ return function(target, key) {
1925
+ decorator(target, key, paramIndex);
1926
+ };
1927
+ }
1928
+ __name(_ts_param, "_ts_param");
1929
+ var CopilotResolver = class {
1930
+ async hello() {
1931
+ return "Hello World";
1932
+ }
1933
+ async generateCopilotResponse(ctx, data, properties) {
1934
+ if (properties) {
1935
+ ctx._copilotkit.properties = {
1936
+ ...ctx._copilotkit.properties,
1937
+ ...properties
1938
+ };
1939
+ }
1940
+ const copilotRuntime = ctx._copilotkit.runtime;
1941
+ const serviceAdapter = ctx._copilotkit.serviceAdapter;
1942
+ const responseStatus = new import_rxjs2.Subject();
1943
+ const { eventSource, threadId = (0, import_nanoid3.nanoid)(), runId } = await copilotRuntime.process({
1944
+ serviceAdapter,
1945
+ messages: data.messages,
1946
+ actions: data.frontend.actions,
1947
+ threadId: data.threadId,
1948
+ runId: data.runId,
1949
+ publicApiKey: void 0
1950
+ });
1951
+ const response = {
1952
+ threadId,
1953
+ runId,
1954
+ status: (0, import_rxjs2.firstValueFrom)(responseStatus),
1955
+ messages: new import_graphql_yoga.Repeater(async (pushMessage, stopStreamingMessages) => {
1956
+ const eventStream = eventSource.process(copilotRuntime.actions).pipe(
1957
+ // shareReplay() ensures that later subscribers will see the whole stream instead of
1958
+ // just the events that were emitted after the subscriber was added.
1959
+ (0, import_rxjs2.shareReplay)()
1960
+ );
1961
+ eventStream.subscribe({
1962
+ next: async (event) => {
1963
+ switch (event.type) {
1964
+ case RuntimeEventTypes.TextMessageStart:
1965
+ const textMessageContentStream = eventStream.pipe(
1966
+ // skip until this message start event
1967
+ (0, import_rxjs2.skipWhile)((e) => e !== event),
1968
+ // take until the message end event
1969
+ (0, import_rxjs2.takeWhile)((e) => e.type != RuntimeEventTypes.TextMessageEnd)
1970
+ );
1971
+ const streamingTextStatus = new import_rxjs2.Subject();
1972
+ pushMessage({
1973
+ id: (0, import_nanoid3.nanoid)(),
1974
+ status: (0, import_rxjs2.firstValueFrom)(streamingTextStatus),
1975
+ createdAt: /* @__PURE__ */ new Date(),
1976
+ role: MessageRole.assistant,
1977
+ content: new import_graphql_yoga.Repeater(async (pushTextChunk, stopStreamingText) => {
1978
+ await textMessageContentStream.forEach(async (e) => {
1979
+ if (e.type == RuntimeEventTypes.TextMessageContent) {
1980
+ await pushTextChunk(e.content);
1981
+ }
1982
+ });
1983
+ stopStreamingText();
1984
+ streamingTextStatus.next(new SuccessMessageStatus());
1985
+ })
1986
+ });
1987
+ break;
1988
+ case RuntimeEventTypes.ActionExecutionStart:
1989
+ const actionExecutionArgumentStream = eventStream.pipe((0, import_rxjs2.skipWhile)((e) => e !== event), (0, import_rxjs2.takeWhile)((e) => e.type != RuntimeEventTypes.ActionExecutionEnd));
1990
+ const streamingArgumentsStatus = new import_rxjs2.Subject();
1991
+ pushMessage({
1992
+ id: event.actionExecutionId,
1993
+ status: (0, import_rxjs2.firstValueFrom)(streamingArgumentsStatus),
1994
+ createdAt: /* @__PURE__ */ new Date(),
1995
+ name: event.actionName,
1996
+ scope: event.scope,
1997
+ arguments: new import_graphql_yoga.Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
1998
+ await actionExecutionArgumentStream.forEach(async (e) => {
1999
+ if (e.type == RuntimeEventTypes.ActionExecutionArgs) {
2000
+ await pushArgumentsChunk(e.args);
2001
+ }
2002
+ });
2003
+ stopStreamingArguments();
2004
+ streamingArgumentsStatus.next(new SuccessMessageStatus());
2005
+ })
2006
+ });
2007
+ break;
2008
+ case RuntimeEventTypes.ActionExecutionResult:
2009
+ pushMessage({
2010
+ id: (0, import_nanoid3.nanoid)(),
2011
+ status: new SuccessMessageStatus(),
2012
+ createdAt: /* @__PURE__ */ new Date(),
2013
+ actionExecutionId: event.actionExecutionId,
2014
+ actionName: event.actionName,
2015
+ result: event.result
2016
+ });
2017
+ break;
2018
+ }
2019
+ },
2020
+ error: (err) => console.error("Error in event source", err),
2021
+ complete: () => {
2022
+ responseStatus.next(new SuccessResponseStatus());
2023
+ stopStreamingMessages();
2024
+ }
2025
+ });
2026
+ })
2027
+ };
2028
+ return response;
2029
+ }
2030
+ };
2031
+ __name(CopilotResolver, "CopilotResolver");
2032
+ _ts_decorate11([
2033
+ (0, import_type_graphql12.Query)(() => String),
2034
+ _ts_metadata11("design:type", Function),
2035
+ _ts_metadata11("design:paramtypes", []),
2036
+ _ts_metadata11("design:returntype", Promise)
2037
+ ], CopilotResolver.prototype, "hello", null);
2038
+ _ts_decorate11([
2039
+ (0, import_type_graphql12.Mutation)(() => CopilotResponse),
2040
+ _ts_param(0, (0, import_type_graphql12.Ctx)()),
2041
+ _ts_param(1, (0, import_type_graphql12.Arg)("data")),
2042
+ _ts_param(2, (0, import_type_graphql12.Arg)("properties", () => import_graphql_scalars.GraphQLJSONObject, {
2043
+ nullable: true
2044
+ })),
2045
+ _ts_metadata11("design:type", Function),
2046
+ _ts_metadata11("design:paramtypes", [
2047
+ typeof GraphQLContext === "undefined" ? Object : GraphQLContext,
2048
+ typeof GenerateCopilotResponseInput === "undefined" ? Object : GenerateCopilotResponseInput,
2049
+ typeof CopilotRequestContextProperties === "undefined" ? Object : CopilotRequestContextProperties
2050
+ ]),
2051
+ _ts_metadata11("design:returntype", Promise)
2052
+ ], CopilotResolver.prototype, "generateCopilotResponse", null);
2053
+ CopilotResolver = _ts_decorate11([
2054
+ (0, import_type_graphql12.Resolver)(() => CopilotResponse)
2055
+ ], CopilotResolver);
2056
+
2057
+ // src/lib/integrations/shared.ts
2058
+ var import_plugin_defer_stream = require("@graphql-yoga/plugin-defer-stream");
2059
+ async function createContext(initialContext, copilotKitContext) {
2060
+ const ctx = {
2061
+ ...initialContext,
2062
+ _copilotkit: {
2063
+ ...copilotKitContext
2064
+ }
2065
+ };
2066
+ return ctx;
2067
+ }
2068
+ __name(createContext, "createContext");
2069
+ function buildSchema(options = {}) {
2070
+ const schema = (0, import_type_graphql13.buildSchemaSync)({
2071
+ resolvers: [
2072
+ CopilotResolver
2073
+ ],
2074
+ emitSchemaFile: options.emitSchemaFile
2075
+ });
2076
+ return schema;
2077
+ }
2078
+ __name(buildSchema, "buildSchema");
2079
+ function getCommonConfig(options) {
2080
+ return {
2081
+ schema: buildSchema(),
2082
+ plugins: [
2083
+ (0, import_plugin_defer_stream.useDeferStream)()
2084
+ ],
2085
+ context: (ctx) => createContext(ctx, {
2086
+ runtime: options.runtime,
2087
+ serviceAdapter: options.serviceAdapter,
2088
+ properties: {}
2089
+ })
2090
+ };
2091
+ }
2092
+ __name(getCommonConfig, "getCommonConfig");
2093
+
2094
+ // src/lib/integrations/nextjs/app-router.ts
2095
+ var import_graphql_yoga2 = require("graphql-yoga");
2096
+ function copilotRuntimeNextJSAppRouterEndpoint({ runtime, endpoint, serviceAdapter }) {
2097
+ const commonConfig = getCommonConfig({
2098
+ runtime,
2099
+ serviceAdapter
2100
+ });
2101
+ const yoga = (0, import_graphql_yoga2.createYoga)({
2102
+ ...commonConfig,
2103
+ graphqlEndpoint: endpoint,
2104
+ fetchAPI: {
2105
+ Response: globalThis.Response
2106
+ }
2107
+ });
2108
+ return {
2109
+ handleRequest: yoga,
2110
+ GET: yoga,
2111
+ POST: yoga,
2112
+ OPTIONS: yoga
2113
+ };
2114
+ }
2115
+ __name(copilotRuntimeNextJSAppRouterEndpoint, "copilotRuntimeNextJSAppRouterEndpoint");
2116
+
2117
+ // src/lib/integrations/nextjs/pages-router.ts
2118
+ var import_graphql_yoga3 = require("graphql-yoga");
2119
+ var config = {
2120
+ api: {
2121
+ bodyParser: false
2122
+ }
2123
+ };
2124
+ function copilotRuntimeNextJSPagesRouterEndpoint({ runtime, endpoint, serviceAdapter }) {
2125
+ const commonConfig = getCommonConfig({
2126
+ runtime,
2127
+ serviceAdapter
2128
+ });
2129
+ const yoga = (0, import_graphql_yoga3.createYoga)({
2130
+ ...commonConfig,
2131
+ graphqlEndpoint: endpoint
2132
+ });
2133
+ return yoga;
2134
+ }
2135
+ __name(copilotRuntimeNextJSPagesRouterEndpoint, "copilotRuntimeNextJSPagesRouterEndpoint");
2136
+
2137
+ // src/lib/integrations/node-http/index.ts
2138
+ var import_graphql_yoga4 = require("graphql-yoga");
2139
+ function copilotRuntimeNodeHttpEndpoint({ runtime, endpoint, serviceAdapter }) {
2140
+ const commonConfig = getCommonConfig({
2141
+ runtime,
2142
+ serviceAdapter
2143
+ });
2144
+ const yoga = (0, import_graphql_yoga4.createYoga)({
2145
+ ...commonConfig,
2146
+ graphqlEndpoint: endpoint
2147
+ });
2148
+ return yoga;
2149
+ }
2150
+ __name(copilotRuntimeNodeHttpEndpoint, "copilotRuntimeNodeHttpEndpoint");
2151
+ // Annotate the CommonJS export names for ESM import in node:
2152
+ 0 && (module.exports = {
2153
+ CopilotBackend,
2154
+ CopilotCloud,
2155
+ CopilotRuntime,
2156
+ GoogleGenerativeAIAdapter,
2157
+ LangChainAdapter,
2158
+ OpenAIAdapter,
2159
+ OpenAIAssistantAdapter,
2160
+ RemoteCopilotCloud,
2161
+ buildSchema,
2162
+ config,
2163
+ copilotRuntimeNextJSAppRouterEndpoint,
2164
+ copilotRuntimeNextJSPagesRouterEndpoint,
2165
+ copilotRuntimeNodeHttpEndpoint,
2166
+ createContext,
2167
+ flattenToolCallsNoDuplicates,
2168
+ getCommonConfig
2169
+ });
2170
+ //# sourceMappingURL=index.js.map