@copilotkit/runtime 1.5.8 → 1.5.10-next.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 (82) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/__snapshots__/schema/schema.graphql +273 -0
  3. package/dist/chunk-44O2JGUY.mjs +12 -0
  4. package/dist/chunk-44O2JGUY.mjs.map +1 -0
  5. package/dist/chunk-5SDH2PVU.mjs +3395 -0
  6. package/dist/chunk-5SDH2PVU.mjs.map +1 -0
  7. package/dist/chunk-CLGKEUOA.mjs +1408 -0
  8. package/dist/chunk-CLGKEUOA.mjs.map +1 -0
  9. package/dist/chunk-D2WLFQS6.mjs +43 -0
  10. package/dist/chunk-D2WLFQS6.mjs.map +1 -0
  11. package/dist/chunk-DFOKBSIS.mjs +1 -0
  12. package/dist/chunk-DFOKBSIS.mjs.map +1 -0
  13. package/dist/chunk-OZLXON7T.mjs +25 -0
  14. package/dist/chunk-OZLXON7T.mjs.map +1 -0
  15. package/dist/chunk-RFF5IIZJ.mjs +66 -0
  16. package/dist/chunk-RFF5IIZJ.mjs.map +1 -0
  17. package/dist/chunk-T4EYPND5.mjs +25 -0
  18. package/dist/chunk-T4EYPND5.mjs.map +1 -0
  19. package/dist/chunk-U3V2BCGI.mjs +152 -0
  20. package/dist/chunk-U3V2BCGI.mjs.map +1 -0
  21. package/dist/chunk-YTXDY7ZM.mjs +80 -0
  22. package/dist/chunk-YTXDY7ZM.mjs.map +1 -0
  23. package/dist/copilot-runtime-36700e00.d.ts +196 -0
  24. package/dist/graphql/types/base/index.d.ts +6 -0
  25. package/dist/graphql/types/base/index.js +63 -0
  26. package/dist/graphql/types/base/index.js.map +1 -0
  27. package/dist/graphql/types/base/index.mjs +8 -0
  28. package/dist/graphql/types/base/index.mjs.map +1 -0
  29. package/dist/graphql/types/converted/index.d.ts +2 -0
  30. package/dist/graphql/types/converted/index.js +124 -0
  31. package/dist/graphql/types/converted/index.js.map +1 -0
  32. package/dist/graphql/types/converted/index.mjs +17 -0
  33. package/dist/graphql/types/converted/index.mjs.map +1 -0
  34. package/dist/groq-adapter-696b5d29.d.ts +281 -0
  35. package/dist/index-cc2b17be.d.ts +87 -0
  36. package/dist/index.d.ts +23 -0
  37. package/dist/index.js +5153 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/index.mjs +76 -0
  40. package/dist/index.mjs.map +1 -0
  41. package/dist/langserve-9125a12e.d.ts +176 -0
  42. package/dist/lib/cloud/index.d.ts +6 -0
  43. package/dist/lib/cloud/index.js +18 -0
  44. package/dist/lib/cloud/index.js.map +1 -0
  45. package/dist/lib/cloud/index.mjs +1 -0
  46. package/dist/lib/cloud/index.mjs.map +1 -0
  47. package/dist/lib/index.d.ts +20 -0
  48. package/dist/lib/index.js +4801 -0
  49. package/dist/lib/index.js.map +1 -0
  50. package/dist/lib/index.mjs +58 -0
  51. package/dist/lib/index.mjs.map +1 -0
  52. package/dist/lib/integrations/index.d.ts +33 -0
  53. package/dist/lib/integrations/index.js +2166 -0
  54. package/dist/lib/integrations/index.js.map +1 -0
  55. package/dist/lib/integrations/index.mjs +34 -0
  56. package/dist/lib/integrations/index.mjs.map +1 -0
  57. package/dist/lib/integrations/nest/index.d.ts +14 -0
  58. package/dist/lib/integrations/nest/index.js +2075 -0
  59. package/dist/lib/integrations/nest/index.js.map +1 -0
  60. package/dist/lib/integrations/nest/index.mjs +13 -0
  61. package/dist/lib/integrations/nest/index.mjs.map +1 -0
  62. package/dist/lib/integrations/node-express/index.d.ts +14 -0
  63. package/dist/lib/integrations/node-express/index.js +2075 -0
  64. package/dist/lib/integrations/node-express/index.js.map +1 -0
  65. package/dist/lib/integrations/node-express/index.mjs +13 -0
  66. package/dist/lib/integrations/node-express/index.mjs.map +1 -0
  67. package/dist/lib/integrations/node-http/index.d.ts +14 -0
  68. package/dist/lib/integrations/node-http/index.js +2061 -0
  69. package/dist/lib/integrations/node-http/index.js.map +1 -0
  70. package/dist/lib/integrations/node-http/index.mjs +12 -0
  71. package/dist/lib/integrations/node-http/index.mjs.map +1 -0
  72. package/dist/service-adapters/index.d.ts +84 -0
  73. package/dist/service-adapters/index.js +1448 -0
  74. package/dist/service-adapters/index.js.map +1 -0
  75. package/dist/service-adapters/index.mjs +26 -0
  76. package/dist/service-adapters/index.mjs.map +1 -0
  77. package/dist/utils/index.d.ts +49 -0
  78. package/dist/utils/index.js +174 -0
  79. package/dist/utils/index.js.map +1 -0
  80. package/dist/utils/index.mjs +12 -0
  81. package/dist/utils/index.mjs.map +1 -0
  82. package/package.json +2 -2
@@ -0,0 +1,4801 @@
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 __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from3, except, desc) => {
16
+ if (from3 && typeof from3 === "object" || typeof from3 === "function") {
17
+ for (let key of __getOwnPropNames(from3))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // package.json
34
+ var require_package = __commonJS({
35
+ "package.json"(exports, module2) {
36
+ module2.exports = {
37
+ name: "@copilotkit/runtime",
38
+ private: false,
39
+ homepage: "https://github.com/CopilotKit/CopilotKit",
40
+ repository: {
41
+ type: "git",
42
+ url: "https://github.com/CopilotKit/CopilotKit.git"
43
+ },
44
+ publishConfig: {
45
+ access: "public"
46
+ },
47
+ version: "1.5.10-next.0",
48
+ sideEffects: false,
49
+ main: "./dist/index.js",
50
+ module: "./dist/index.mjs",
51
+ exports: {
52
+ ".": "./dist/index.js"
53
+ },
54
+ types: "./dist/index.d.ts",
55
+ license: "MIT",
56
+ scripts: {
57
+ build: 'tsup --onSuccess "pnpm run generate-graphql-schema"',
58
+ dev: 'tsup --watch --onSuccess "pnpm run generate-graphql-schema"',
59
+ test: "jest --passWithNoTests",
60
+ "check-types": "tsc --noEmit",
61
+ clean: "rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__",
62
+ "generate-graphql-schema": "rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts",
63
+ "link:global": "pnpm link --global",
64
+ "unlink:global": "pnpm unlink --global"
65
+ },
66
+ devDependencies: {
67
+ "@swc/core": "1.5.28",
68
+ "@types/express": "^4.17.21",
69
+ "@types/jest": "^29.5.4",
70
+ "@types/node": "^18.11.17",
71
+ "@whatwg-node/server": "^0.9.34",
72
+ eslint: "^8.56.0",
73
+ "eslint-config-custom": "workspace:*",
74
+ jest: "^29.6.4",
75
+ nodemon: "^3.1.3",
76
+ "ts-jest": "^29.1.1",
77
+ "ts-node": "^10.9.2",
78
+ tsconfig: "workspace:*",
79
+ tsup: "^6.7.0",
80
+ typescript: "^5.2.3",
81
+ "zod-to-json-schema": "^3.23.5"
82
+ },
83
+ dependencies: {
84
+ "@anthropic-ai/sdk": "^0.27.3",
85
+ "@copilotkit/shared": "workspace:*",
86
+ "@graphql-yoga/plugin-defer-stream": "^3.3.1",
87
+ "@langchain/community": "^0.0.53",
88
+ "@langchain/core": "^0.3.13",
89
+ "@langchain/google-gauth": "^0.1.0",
90
+ "@langchain/langgraph-sdk": "^0.0.16",
91
+ "@langchain/openai": "^0.0.28",
92
+ "class-transformer": "^0.5.1",
93
+ express: "^4.19.2",
94
+ graphql: "^16.8.1",
95
+ "graphql-scalars": "^1.23.0",
96
+ "graphql-yoga": "^5.3.1",
97
+ "groq-sdk": "^0.5.0",
98
+ langchain: "^0.3.3",
99
+ openai: "^4.50.0",
100
+ "partial-json": "^0.1.7",
101
+ pino: "^9.2.0",
102
+ "pino-pretty": "^11.2.1",
103
+ "reflect-metadata": "^0.2.2",
104
+ rxjs: "^7.8.1",
105
+ "type-graphql": "2.0.0-rc.1",
106
+ zod: "^3.23.3"
107
+ },
108
+ keywords: [
109
+ "copilotkit",
110
+ "copilot",
111
+ "react",
112
+ "nextjs",
113
+ "nodejs",
114
+ "ai",
115
+ "assistant",
116
+ "javascript",
117
+ "automation",
118
+ "textarea"
119
+ ]
120
+ };
121
+ }
122
+ });
123
+
124
+ // src/lib/index.ts
125
+ var lib_exports = {};
126
+ __export(lib_exports, {
127
+ CopilotRuntime: () => CopilotRuntime,
128
+ GoogleGenerativeAIAdapter: () => GoogleGenerativeAIAdapter,
129
+ GroqAdapter: () => GroqAdapter,
130
+ LangChainAdapter: () => LangChainAdapter,
131
+ OpenAIAdapter: () => OpenAIAdapter,
132
+ OpenAIAssistantAdapter: () => OpenAIAssistantAdapter,
133
+ UnifyAdapter: () => UnifyAdapter,
134
+ buildSchema: () => buildSchema,
135
+ config: () => config,
136
+ copilotKitEndpoint: () => copilotKitEndpoint,
137
+ copilotRuntimeNestEndpoint: () => copilotRuntimeNestEndpoint,
138
+ copilotRuntimeNextJSAppRouterEndpoint: () => copilotRuntimeNextJSAppRouterEndpoint,
139
+ copilotRuntimeNextJSPagesRouterEndpoint: () => copilotRuntimeNextJSPagesRouterEndpoint,
140
+ copilotRuntimeNodeExpressEndpoint: () => copilotRuntimeNodeExpressEndpoint,
141
+ copilotRuntimeNodeHttpEndpoint: () => copilotRuntimeNodeHttpEndpoint,
142
+ createContext: () => createContext,
143
+ flattenToolCallsNoDuplicates: () => flattenToolCallsNoDuplicates,
144
+ getCommonConfig: () => getCommonConfig,
145
+ langGraphPlatformEndpoint: () => langGraphPlatformEndpoint,
146
+ resolveEndpointType: () => resolveEndpointType
147
+ });
148
+ module.exports = __toCommonJS(lib_exports);
149
+
150
+ // src/lib/runtime/copilot-runtime.ts
151
+ var import_shared9 = require("@copilotkit/shared");
152
+
153
+ // src/service-adapters/langchain/langserve.ts
154
+ var import_remote = require("langchain/runnables/remote");
155
+ var RemoteChain = class {
156
+ name;
157
+ description;
158
+ chainUrl;
159
+ parameters;
160
+ parameterType;
161
+ constructor(options) {
162
+ this.name = options.name;
163
+ this.description = options.description;
164
+ this.chainUrl = options.chainUrl;
165
+ this.parameters = options.parameters;
166
+ this.parameterType = options.parameterType || "multi";
167
+ }
168
+ async toAction() {
169
+ if (!this.parameters) {
170
+ await this.inferLangServeParameters();
171
+ }
172
+ return {
173
+ name: this.name,
174
+ description: this.description,
175
+ parameters: this.parameters,
176
+ handler: async (args) => {
177
+ const runnable = new import_remote.RemoteRunnable({
178
+ url: this.chainUrl
179
+ });
180
+ let input;
181
+ if (this.parameterType === "single") {
182
+ input = args[Object.keys(args)[0]];
183
+ } else {
184
+ input = args;
185
+ }
186
+ return await runnable.invoke(input);
187
+ }
188
+ };
189
+ }
190
+ async inferLangServeParameters() {
191
+ const supportedTypes = [
192
+ "string",
193
+ "number",
194
+ "boolean"
195
+ ];
196
+ let schemaUrl = this.chainUrl.replace(/\/+$/, "") + "/input_schema";
197
+ let schema = await fetch(schemaUrl).then((res) => res.json()).catch(() => {
198
+ throw new Error("Failed to fetch langserve schema at " + schemaUrl);
199
+ });
200
+ if (supportedTypes.includes(schema.type)) {
201
+ this.parameterType = "single";
202
+ this.parameters = [
203
+ {
204
+ name: "input",
205
+ type: schema.type,
206
+ description: "The input to the chain"
207
+ }
208
+ ];
209
+ } else if (schema.type === "object") {
210
+ this.parameterType = "multi";
211
+ this.parameters = Object.keys(schema.properties).map((key) => {
212
+ var _a;
213
+ let property = schema.properties[key];
214
+ if (!supportedTypes.includes(property.type)) {
215
+ throw new Error("Unsupported schema type");
216
+ }
217
+ return {
218
+ name: key,
219
+ type: property.type,
220
+ description: property.description || "",
221
+ required: ((_a = schema.required) == null ? void 0 : _a.includes(key)) || false
222
+ };
223
+ });
224
+ } else {
225
+ throw new Error("Unsupported schema type");
226
+ }
227
+ }
228
+ };
229
+ __name(RemoteChain, "RemoteChain");
230
+
231
+ // src/service-adapters/openai/openai-adapter.ts
232
+ var import_openai = __toESM(require("openai"));
233
+
234
+ // src/service-adapters/openai/utils.ts
235
+ function limitMessagesToTokenCount(messages, tools, model, maxTokens) {
236
+ maxTokens || (maxTokens = maxTokensForOpenAIModel(model));
237
+ const result = [];
238
+ const toolsNumTokens = countToolsTokens(model, tools);
239
+ if (toolsNumTokens > maxTokens) {
240
+ throw new Error(`Too many tokens in function definitions: ${toolsNumTokens} > ${maxTokens}`);
241
+ }
242
+ maxTokens -= toolsNumTokens;
243
+ for (const message of messages) {
244
+ if (message.role === "system") {
245
+ const numTokens = countMessageTokens(model, message);
246
+ maxTokens -= numTokens;
247
+ if (maxTokens < 0) {
248
+ throw new Error("Not enough tokens for system message.");
249
+ }
250
+ }
251
+ }
252
+ let cutoff = false;
253
+ const reversedMessages = [
254
+ ...messages
255
+ ].reverse();
256
+ for (const message of reversedMessages) {
257
+ if (message.role === "system") {
258
+ result.unshift(message);
259
+ continue;
260
+ } else if (cutoff) {
261
+ continue;
262
+ }
263
+ let numTokens = countMessageTokens(model, message);
264
+ if (maxTokens < numTokens) {
265
+ cutoff = true;
266
+ continue;
267
+ }
268
+ result.unshift(message);
269
+ maxTokens -= numTokens;
270
+ }
271
+ return result;
272
+ }
273
+ __name(limitMessagesToTokenCount, "limitMessagesToTokenCount");
274
+ function maxTokensForOpenAIModel(model) {
275
+ return maxTokensByModel[model] || DEFAULT_MAX_TOKENS;
276
+ }
277
+ __name(maxTokensForOpenAIModel, "maxTokensForOpenAIModel");
278
+ var DEFAULT_MAX_TOKENS = 128e3;
279
+ var maxTokensByModel = {
280
+ // GPT-4
281
+ "gpt-4o": 128e3,
282
+ "gpt-4o-2024-05-13": 128e3,
283
+ "gpt-4-turbo": 128e3,
284
+ "gpt-4-turbo-2024-04-09": 128e3,
285
+ "gpt-4-0125-preview": 128e3,
286
+ "gpt-4-turbo-preview": 128e3,
287
+ "gpt-4-1106-preview": 128e3,
288
+ "gpt-4-vision-preview": 128e3,
289
+ "gpt-4-1106-vision-preview": 128e3,
290
+ "gpt-4-32k": 32768,
291
+ "gpt-4-32k-0613": 32768,
292
+ "gpt-4-32k-0314": 32768,
293
+ "gpt-4": 8192,
294
+ "gpt-4-0613": 8192,
295
+ "gpt-4-0314": 8192,
296
+ // GPT-3.5
297
+ "gpt-3.5-turbo-0125": 16385,
298
+ "gpt-3.5-turbo": 16385,
299
+ "gpt-3.5-turbo-1106": 16385,
300
+ "gpt-3.5-turbo-instruct": 4096,
301
+ "gpt-3.5-turbo-16k": 16385,
302
+ "gpt-3.5-turbo-0613": 4096,
303
+ "gpt-3.5-turbo-16k-0613": 16385,
304
+ "gpt-3.5-turbo-0301": 4097
305
+ };
306
+ function countToolsTokens(model, tools) {
307
+ if (tools.length === 0) {
308
+ return 0;
309
+ }
310
+ const json = JSON.stringify(tools);
311
+ return countTokens(model, json);
312
+ }
313
+ __name(countToolsTokens, "countToolsTokens");
314
+ function countMessageTokens(model, message) {
315
+ return countTokens(model, message.content || "");
316
+ }
317
+ __name(countMessageTokens, "countMessageTokens");
318
+ function countTokens(model, text) {
319
+ return text.length / 3;
320
+ }
321
+ __name(countTokens, "countTokens");
322
+ function convertActionInputToOpenAITool(action) {
323
+ return {
324
+ type: "function",
325
+ function: {
326
+ name: action.name,
327
+ description: action.description,
328
+ parameters: JSON.parse(action.jsonSchema)
329
+ }
330
+ };
331
+ }
332
+ __name(convertActionInputToOpenAITool, "convertActionInputToOpenAITool");
333
+ function convertMessageToOpenAIMessage(message) {
334
+ if (message.isTextMessage()) {
335
+ return {
336
+ role: message.role,
337
+ content: message.content
338
+ };
339
+ } else if (message.isActionExecutionMessage()) {
340
+ return {
341
+ role: "assistant",
342
+ tool_calls: [
343
+ {
344
+ id: message.id,
345
+ type: "function",
346
+ function: {
347
+ name: message.name,
348
+ arguments: JSON.stringify(message.arguments)
349
+ }
350
+ }
351
+ ]
352
+ };
353
+ } else if (message.isResultMessage()) {
354
+ return {
355
+ role: "tool",
356
+ content: message.result,
357
+ tool_call_id: message.actionExecutionId
358
+ };
359
+ }
360
+ }
361
+ __name(convertMessageToOpenAIMessage, "convertMessageToOpenAIMessage");
362
+ function convertSystemMessageToAssistantAPI(message) {
363
+ return {
364
+ ...message,
365
+ ...message.role === "system" && {
366
+ role: "assistant",
367
+ content: "THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: " + message.content
368
+ }
369
+ };
370
+ }
371
+ __name(convertSystemMessageToAssistantAPI, "convertSystemMessageToAssistantAPI");
372
+
373
+ // src/service-adapters/openai/openai-adapter.ts
374
+ var import_shared = require("@copilotkit/shared");
375
+ var DEFAULT_MODEL = "gpt-4o";
376
+ var OpenAIAdapter = class {
377
+ model = DEFAULT_MODEL;
378
+ disableParallelToolCalls = false;
379
+ _openai;
380
+ get openai() {
381
+ return this._openai;
382
+ }
383
+ constructor(params) {
384
+ this._openai = (params == null ? void 0 : params.openai) || new import_openai.default({});
385
+ if (params == null ? void 0 : params.model) {
386
+ this.model = params.model;
387
+ }
388
+ this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
389
+ }
390
+ async process(request) {
391
+ const { threadId, model = this.model, messages, actions, eventSource, forwardedParameters } = request;
392
+ const tools = actions.map(convertActionInputToOpenAITool);
393
+ let openaiMessages = messages.map(convertMessageToOpenAIMessage);
394
+ openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
395
+ let toolChoice = forwardedParameters == null ? void 0 : forwardedParameters.toolChoice;
396
+ if ((forwardedParameters == null ? void 0 : forwardedParameters.toolChoice) === "function") {
397
+ toolChoice = {
398
+ type: "function",
399
+ function: {
400
+ name: forwardedParameters.toolChoiceFunctionName
401
+ }
402
+ };
403
+ }
404
+ const stream = this.openai.beta.chat.completions.stream({
405
+ model,
406
+ stream: true,
407
+ messages: openaiMessages,
408
+ ...tools.length > 0 && {
409
+ tools
410
+ },
411
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
412
+ max_tokens: forwardedParameters.maxTokens
413
+ },
414
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.stop) && {
415
+ stop: forwardedParameters.stop
416
+ },
417
+ ...toolChoice && {
418
+ tool_choice: toolChoice
419
+ },
420
+ ...this.disableParallelToolCalls && {
421
+ parallel_tool_calls: false
422
+ },
423
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.temperature) && {
424
+ temperature: forwardedParameters.temperature
425
+ }
426
+ });
427
+ eventSource.stream(async (eventStream$) => {
428
+ var _a, _b;
429
+ let mode = null;
430
+ let currentMessageId;
431
+ let currentToolCallId;
432
+ for await (const chunk of stream) {
433
+ if (chunk.choices.length === 0) {
434
+ continue;
435
+ }
436
+ const toolCall = (_a = chunk.choices[0].delta.tool_calls) == null ? void 0 : _a[0];
437
+ const content = chunk.choices[0].delta.content;
438
+ if (mode === "message" && (toolCall == null ? void 0 : toolCall.id)) {
439
+ mode = null;
440
+ eventStream$.sendTextMessageEnd({
441
+ messageId: currentMessageId
442
+ });
443
+ } else if (mode === "function" && (toolCall === void 0 || (toolCall == null ? void 0 : toolCall.id))) {
444
+ mode = null;
445
+ eventStream$.sendActionExecutionEnd({
446
+ actionExecutionId: currentToolCallId
447
+ });
448
+ }
449
+ if (mode === null) {
450
+ if (toolCall == null ? void 0 : toolCall.id) {
451
+ mode = "function";
452
+ currentToolCallId = toolCall.id;
453
+ eventStream$.sendActionExecutionStart({
454
+ actionExecutionId: currentToolCallId,
455
+ parentMessageId: chunk.id,
456
+ actionName: toolCall.function.name
457
+ });
458
+ } else if (content) {
459
+ mode = "message";
460
+ currentMessageId = chunk.id;
461
+ eventStream$.sendTextMessageStart({
462
+ messageId: currentMessageId
463
+ });
464
+ }
465
+ }
466
+ if (mode === "message" && content) {
467
+ eventStream$.sendTextMessageContent({
468
+ messageId: currentMessageId,
469
+ content
470
+ });
471
+ } else if (mode === "function" && ((_b = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _b.arguments)) {
472
+ eventStream$.sendActionExecutionArgs({
473
+ actionExecutionId: currentToolCallId,
474
+ args: toolCall.function.arguments
475
+ });
476
+ }
477
+ }
478
+ if (mode === "message") {
479
+ eventStream$.sendTextMessageEnd({
480
+ messageId: currentMessageId
481
+ });
482
+ } else if (mode === "function") {
483
+ eventStream$.sendActionExecutionEnd({
484
+ actionExecutionId: currentToolCallId
485
+ });
486
+ }
487
+ eventStream$.complete();
488
+ });
489
+ return {
490
+ threadId: threadId || (0, import_shared.randomId)()
491
+ };
492
+ }
493
+ };
494
+ __name(OpenAIAdapter, "OpenAIAdapter");
495
+
496
+ // src/service-adapters/langchain/utils.ts
497
+ var import_messages = require("@langchain/core/messages");
498
+ var import_tools = require("@langchain/core/tools");
499
+ var import_shared2 = require("@copilotkit/shared");
500
+ function convertMessageToLangChainMessage(message) {
501
+ if (message.isTextMessage()) {
502
+ if (message.role == "user") {
503
+ return new import_messages.HumanMessage(message.content);
504
+ } else if (message.role == "assistant") {
505
+ return new import_messages.AIMessage(message.content);
506
+ } else if (message.role === "system") {
507
+ return new import_messages.SystemMessage(message.content);
508
+ }
509
+ } else if (message.isActionExecutionMessage()) {
510
+ return new import_messages.AIMessage({
511
+ content: "",
512
+ tool_calls: [
513
+ {
514
+ id: message.id,
515
+ args: message.arguments,
516
+ name: message.name
517
+ }
518
+ ]
519
+ });
520
+ } else if (message.isResultMessage()) {
521
+ return new import_messages.ToolMessage({
522
+ content: message.result,
523
+ tool_call_id: message.actionExecutionId
524
+ });
525
+ }
526
+ }
527
+ __name(convertMessageToLangChainMessage, "convertMessageToLangChainMessage");
528
+ function convertActionInputToLangChainTool(actionInput) {
529
+ return new import_tools.DynamicStructuredTool({
530
+ name: actionInput.name,
531
+ description: actionInput.description,
532
+ schema: (0, import_shared2.convertJsonSchemaToZodSchema)(JSON.parse(actionInput.jsonSchema), true),
533
+ func: async () => {
534
+ return "";
535
+ }
536
+ });
537
+ }
538
+ __name(convertActionInputToLangChainTool, "convertActionInputToLangChainTool");
539
+ function isAIMessage(message) {
540
+ return Object.prototype.toString.call(message) === "[object AIMessage]";
541
+ }
542
+ __name(isAIMessage, "isAIMessage");
543
+ function isAIMessageChunk(message) {
544
+ return Object.prototype.toString.call(message) === "[object AIMessageChunk]";
545
+ }
546
+ __name(isAIMessageChunk, "isAIMessageChunk");
547
+ function isBaseMessageChunk(message) {
548
+ return Object.prototype.toString.call(message) === "[object BaseMessageChunk]";
549
+ }
550
+ __name(isBaseMessageChunk, "isBaseMessageChunk");
551
+ function maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution) {
552
+ if (actionExecution) {
553
+ eventStream$.sendActionExecutionResult({
554
+ actionExecutionId: actionExecution.id,
555
+ actionName: actionExecution.name,
556
+ result: "Sending a message"
557
+ });
558
+ }
559
+ }
560
+ __name(maybeSendActionExecutionResultIsMessage, "maybeSendActionExecutionResultIsMessage");
561
+ async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
562
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
563
+ if (typeof result === "string") {
564
+ if (!actionExecution) {
565
+ eventStream$.sendTextMessage((0, import_shared2.randomId)(), result);
566
+ } else {
567
+ eventStream$.sendActionExecutionResult({
568
+ actionExecutionId: actionExecution.id,
569
+ actionName: actionExecution.name,
570
+ result
571
+ });
572
+ }
573
+ } else if (isAIMessage(result)) {
574
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
575
+ if (result.content) {
576
+ eventStream$.sendTextMessage((0, import_shared2.randomId)(), result.content);
577
+ }
578
+ for (const toolCall of result.tool_calls) {
579
+ eventStream$.sendActionExecution({
580
+ actionExecutionId: toolCall.id || (0, import_shared2.randomId)(),
581
+ actionName: toolCall.name,
582
+ args: JSON.stringify(toolCall.args)
583
+ });
584
+ }
585
+ } else if (isBaseMessageChunk(result)) {
586
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
587
+ if ((_a = result.lc_kwargs) == null ? void 0 : _a.content) {
588
+ eventStream$.sendTextMessage((0, import_shared2.randomId)(), result.content);
589
+ }
590
+ if ((_b = result.lc_kwargs) == null ? void 0 : _b.tool_calls) {
591
+ for (const toolCall of (_c = result.lc_kwargs) == null ? void 0 : _c.tool_calls) {
592
+ eventStream$.sendActionExecution({
593
+ actionExecutionId: toolCall.id || (0, import_shared2.randomId)(),
594
+ actionName: toolCall.name,
595
+ args: JSON.stringify(toolCall.args)
596
+ });
597
+ }
598
+ }
599
+ } else if (result && "getReader" in result) {
600
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
601
+ let reader = result.getReader();
602
+ let mode = null;
603
+ let currentMessageId;
604
+ const toolCallDetails = {
605
+ name: null,
606
+ id: null,
607
+ index: null,
608
+ prevIndex: null
609
+ };
610
+ while (true) {
611
+ try {
612
+ const { done, value } = await reader.read();
613
+ let toolCallName = void 0;
614
+ let toolCallId = void 0;
615
+ let toolCallArgs = void 0;
616
+ let hasToolCall = false;
617
+ let content = "";
618
+ if (value && value.content) {
619
+ content = Array.isArray(value.content) ? ((_d = value.content[0]) == null ? void 0 : _d.text) ?? "" : value.content;
620
+ }
621
+ if (isAIMessageChunk(value)) {
622
+ let chunk = (_e = value.tool_call_chunks) == null ? void 0 : _e[0];
623
+ toolCallArgs = chunk == null ? void 0 : chunk.args;
624
+ hasToolCall = chunk != void 0;
625
+ if (chunk == null ? void 0 : chunk.name)
626
+ toolCallDetails.name = chunk.name;
627
+ if ((chunk == null ? void 0 : chunk.index) != null) {
628
+ toolCallDetails.index = chunk.index;
629
+ if (toolCallDetails.prevIndex == null)
630
+ toolCallDetails.prevIndex = chunk.index;
631
+ }
632
+ if (chunk == null ? void 0 : chunk.id)
633
+ toolCallDetails.id = chunk.index != null ? `${chunk.id}-idx-${chunk.index}` : chunk.id;
634
+ toolCallName = toolCallDetails.name;
635
+ toolCallId = toolCallDetails.id;
636
+ } else if (isBaseMessageChunk(value)) {
637
+ let chunk = (_g = (_f = value.additional_kwargs) == null ? void 0 : _f.tool_calls) == null ? void 0 : _g[0];
638
+ toolCallName = (_h = chunk == null ? void 0 : chunk.function) == null ? void 0 : _h.name;
639
+ toolCallId = chunk == null ? void 0 : chunk.id;
640
+ toolCallArgs = (_i = chunk == null ? void 0 : chunk.function) == null ? void 0 : _i.arguments;
641
+ hasToolCall = (chunk == null ? void 0 : chunk.function) != void 0;
642
+ }
643
+ if (mode === "message" && (toolCallId || done)) {
644
+ mode = null;
645
+ eventStream$.sendTextMessageEnd({
646
+ messageId: currentMessageId
647
+ });
648
+ } else if (mode === "function" && (!hasToolCall || done)) {
649
+ mode = null;
650
+ eventStream$.sendActionExecutionEnd({
651
+ actionExecutionId: toolCallId
652
+ });
653
+ }
654
+ if (done) {
655
+ break;
656
+ }
657
+ if (mode === null) {
658
+ if (hasToolCall && toolCallId && toolCallName) {
659
+ mode = "function";
660
+ eventStream$.sendActionExecutionStart({
661
+ actionExecutionId: toolCallId,
662
+ actionName: toolCallName,
663
+ parentMessageId: (_j = value.lc_kwargs) == null ? void 0 : _j.id
664
+ });
665
+ } else if (content) {
666
+ mode = "message";
667
+ currentMessageId = ((_k = value.lc_kwargs) == null ? void 0 : _k.id) || (0, import_shared2.randomId)();
668
+ eventStream$.sendTextMessageStart({
669
+ messageId: currentMessageId
670
+ });
671
+ }
672
+ }
673
+ if (mode === "message" && content) {
674
+ eventStream$.sendTextMessageContent({
675
+ messageId: currentMessageId,
676
+ content
677
+ });
678
+ } else if (mode === "function" && toolCallArgs) {
679
+ if (toolCallDetails.index !== toolCallDetails.prevIndex) {
680
+ eventStream$.sendActionExecutionEnd({
681
+ actionExecutionId: toolCallId
682
+ });
683
+ eventStream$.sendActionExecutionStart({
684
+ actionExecutionId: toolCallId,
685
+ actionName: toolCallName,
686
+ parentMessageId: (_l = value.lc_kwargs) == null ? void 0 : _l.id
687
+ });
688
+ toolCallDetails.prevIndex = toolCallDetails.index;
689
+ }
690
+ eventStream$.sendActionExecutionArgs({
691
+ actionExecutionId: toolCallId,
692
+ args: toolCallArgs
693
+ });
694
+ }
695
+ } catch (error) {
696
+ console.error("Error reading from stream", error);
697
+ break;
698
+ }
699
+ }
700
+ } else if (actionExecution) {
701
+ eventStream$.sendActionExecutionResult({
702
+ actionExecutionId: actionExecution.id,
703
+ actionName: actionExecution.name,
704
+ result: encodeResult(result)
705
+ });
706
+ } else {
707
+ throw new Error("Invalid return type from LangChain function.");
708
+ }
709
+ eventStream$.complete();
710
+ }
711
+ __name(streamLangChainResponse, "streamLangChainResponse");
712
+ function encodeResult(result) {
713
+ if (result === void 0) {
714
+ return "";
715
+ } else if (typeof result === "string") {
716
+ return result;
717
+ } else {
718
+ return JSON.stringify(result);
719
+ }
720
+ }
721
+ __name(encodeResult, "encodeResult");
722
+
723
+ // src/service-adapters/langchain/langchain-adapter.ts
724
+ var import_shared3 = require("@copilotkit/shared");
725
+ var import_promises = require("@langchain/core/callbacks/promises");
726
+ var LangChainAdapter = class {
727
+ options;
728
+ /**
729
+ * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.
730
+ */
731
+ constructor(options) {
732
+ this.options = options;
733
+ }
734
+ async process(request) {
735
+ try {
736
+ const { eventSource, model, actions, messages, runId } = request;
737
+ const threadId = request.threadId ?? (0, import_shared3.randomId)();
738
+ const result = await this.options.chainFn({
739
+ messages: messages.map(convertMessageToLangChainMessage),
740
+ tools: actions.map(convertActionInputToLangChainTool),
741
+ model,
742
+ threadId,
743
+ runId
744
+ });
745
+ eventSource.stream(async (eventStream$) => {
746
+ await streamLangChainResponse({
747
+ result,
748
+ eventStream$
749
+ });
750
+ });
751
+ return {
752
+ threadId
753
+ };
754
+ } finally {
755
+ await (0, import_promises.awaitAllCallbacks)();
756
+ }
757
+ }
758
+ };
759
+ __name(LangChainAdapter, "LangChainAdapter");
760
+
761
+ // src/service-adapters/google/google-genai-adapter.ts
762
+ var import_google_gauth = require("@langchain/google-gauth");
763
+ var GoogleGenerativeAIAdapter = class extends LangChainAdapter {
764
+ constructor(options) {
765
+ super({
766
+ chainFn: async ({ messages, tools, threadId }) => {
767
+ const model = new import_google_gauth.ChatGoogle({
768
+ modelName: (options == null ? void 0 : options.model) ?? "gemini-1.5-pro",
769
+ apiVersion: "v1beta"
770
+ }).bindTools(tools);
771
+ return model.stream(messages, {
772
+ metadata: {
773
+ conversation_id: threadId
774
+ }
775
+ });
776
+ }
777
+ });
778
+ }
779
+ };
780
+ __name(GoogleGenerativeAIAdapter, "GoogleGenerativeAIAdapter");
781
+
782
+ // src/service-adapters/openai/openai-assistant-adapter.ts
783
+ var import_openai2 = __toESM(require("openai"));
784
+ var OpenAIAssistantAdapter = class {
785
+ openai;
786
+ codeInterpreterEnabled;
787
+ assistantId;
788
+ fileSearchEnabled;
789
+ disableParallelToolCalls;
790
+ constructor(params) {
791
+ this.openai = params.openai || new import_openai2.default({});
792
+ this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;
793
+ this.fileSearchEnabled = params.fileSearchEnabled === false || true;
794
+ this.assistantId = params.assistantId;
795
+ this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
796
+ }
797
+ async process(request) {
798
+ const { messages, actions, eventSource, runId, forwardedParameters } = request;
799
+ let threadId = request.threadId || (await this.openai.beta.threads.create()).id;
800
+ const lastMessage = messages.at(-1);
801
+ let nextRunId = void 0;
802
+ if (lastMessage.isResultMessage() && runId) {
803
+ nextRunId = await this.submitToolOutputs(threadId, runId, messages, eventSource);
804
+ } else if (lastMessage.isTextMessage()) {
805
+ nextRunId = await this.submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters);
806
+ } else {
807
+ throw new Error("No actionable message found in the messages");
808
+ }
809
+ return {
810
+ threadId,
811
+ runId: nextRunId
812
+ };
813
+ }
814
+ async submitToolOutputs(threadId, runId, messages, eventSource) {
815
+ let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);
816
+ if (!run.required_action) {
817
+ throw new Error("No tool outputs required");
818
+ }
819
+ const toolCallsIds = run.required_action.submit_tool_outputs.tool_calls.map((toolCall) => toolCall.id);
820
+ const resultMessages = messages.filter((message) => message.isResultMessage() && toolCallsIds.includes(message.actionExecutionId));
821
+ if (toolCallsIds.length != resultMessages.length) {
822
+ throw new Error("Number of function results does not match the number of tool calls");
823
+ }
824
+ const toolOutputs = resultMessages.map((message) => {
825
+ return {
826
+ tool_call_id: message.actionExecutionId,
827
+ output: message.result
828
+ };
829
+ });
830
+ const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {
831
+ tool_outputs: toolOutputs,
832
+ ...this.disableParallelToolCalls && {
833
+ parallel_tool_calls: false
834
+ }
835
+ });
836
+ await this.streamResponse(stream, eventSource);
837
+ return runId;
838
+ }
839
+ async submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters) {
840
+ messages = [
841
+ ...messages
842
+ ];
843
+ const instructionsMessage = messages.shift();
844
+ const instructions = instructionsMessage.isTextMessage() ? instructionsMessage.content : "";
845
+ const userMessage = messages.map(convertMessageToOpenAIMessage).map(convertSystemMessageToAssistantAPI).at(-1);
846
+ if (userMessage.role !== "user") {
847
+ throw new Error("No user message found");
848
+ }
849
+ await this.openai.beta.threads.messages.create(threadId, {
850
+ role: "user",
851
+ content: userMessage.content
852
+ });
853
+ const openaiTools = actions.map(convertActionInputToOpenAITool);
854
+ const tools = [
855
+ ...openaiTools,
856
+ ...this.codeInterpreterEnabled ? [
857
+ {
858
+ type: "code_interpreter"
859
+ }
860
+ ] : [],
861
+ ...this.fileSearchEnabled ? [
862
+ {
863
+ type: "file_search"
864
+ }
865
+ ] : []
866
+ ];
867
+ let stream = this.openai.beta.threads.runs.stream(threadId, {
868
+ assistant_id: this.assistantId,
869
+ instructions,
870
+ tools,
871
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
872
+ max_completion_tokens: forwardedParameters.maxTokens
873
+ },
874
+ ...this.disableParallelToolCalls && {
875
+ parallel_tool_calls: false
876
+ }
877
+ });
878
+ await this.streamResponse(stream, eventSource);
879
+ return getRunIdFromStream(stream);
880
+ }
881
+ async streamResponse(stream, eventSource) {
882
+ eventSource.stream(async (eventStream$) => {
883
+ var _a, _b, _c, _d, _e, _f;
884
+ let inFunctionCall = false;
885
+ let currentMessageId;
886
+ let currentToolCallId;
887
+ for await (const chunk of stream) {
888
+ switch (chunk.event) {
889
+ case "thread.message.created":
890
+ if (inFunctionCall) {
891
+ eventStream$.sendActionExecutionEnd({
892
+ actionExecutionId: currentToolCallId
893
+ });
894
+ }
895
+ currentMessageId = chunk.data.id;
896
+ eventStream$.sendTextMessageStart({
897
+ messageId: currentMessageId
898
+ });
899
+ break;
900
+ case "thread.message.delta":
901
+ if (((_a = chunk.data.delta.content) == null ? void 0 : _a[0].type) === "text") {
902
+ eventStream$.sendTextMessageContent({
903
+ messageId: currentMessageId,
904
+ content: (_b = chunk.data.delta.content) == null ? void 0 : _b[0].text.value
905
+ });
906
+ }
907
+ break;
908
+ case "thread.message.completed":
909
+ eventStream$.sendTextMessageEnd({
910
+ messageId: currentMessageId
911
+ });
912
+ break;
913
+ case "thread.run.step.delta":
914
+ let toolCallId;
915
+ let toolCallName;
916
+ let toolCallArgs;
917
+ if (chunk.data.delta.step_details.type === "tool_calls" && ((_c = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _c[0].type) === "function") {
918
+ toolCallId = (_d = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _d[0].id;
919
+ toolCallName = (_e = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _e[0].function.name;
920
+ toolCallArgs = (_f = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _f[0].function.arguments;
921
+ }
922
+ if (toolCallName && toolCallId) {
923
+ if (inFunctionCall) {
924
+ eventStream$.sendActionExecutionEnd({
925
+ actionExecutionId: currentToolCallId
926
+ });
927
+ }
928
+ inFunctionCall = true;
929
+ currentToolCallId = toolCallId;
930
+ eventStream$.sendActionExecutionStart({
931
+ actionExecutionId: currentToolCallId,
932
+ parentMessageId: chunk.data.id,
933
+ actionName: toolCallName
934
+ });
935
+ } else if (toolCallArgs) {
936
+ eventStream$.sendActionExecutionArgs({
937
+ actionExecutionId: currentToolCallId,
938
+ args: toolCallArgs
939
+ });
940
+ }
941
+ break;
942
+ }
943
+ }
944
+ if (inFunctionCall) {
945
+ eventStream$.sendActionExecutionEnd({
946
+ actionExecutionId: currentToolCallId
947
+ });
948
+ }
949
+ eventStream$.complete();
950
+ });
951
+ }
952
+ };
953
+ __name(OpenAIAssistantAdapter, "OpenAIAssistantAdapter");
954
+ function getRunIdFromStream(stream) {
955
+ return new Promise((resolve, reject) => {
956
+ let runIdGetter = /* @__PURE__ */ __name((event) => {
957
+ if (event.event === "thread.run.created") {
958
+ const runId = event.data.id;
959
+ stream.off("event", runIdGetter);
960
+ resolve(runId);
961
+ }
962
+ }, "runIdGetter");
963
+ stream.on("event", runIdGetter);
964
+ });
965
+ }
966
+ __name(getRunIdFromStream, "getRunIdFromStream");
967
+
968
+ // src/service-adapters/unify/unify-adapter.ts
969
+ var import_openai3 = __toESM(require("openai"));
970
+ var import_shared4 = require("@copilotkit/shared");
971
+ var UnifyAdapter = class {
972
+ apiKey;
973
+ model;
974
+ start;
975
+ constructor(options) {
976
+ if (options == null ? void 0 : options.apiKey) {
977
+ this.apiKey = options.apiKey;
978
+ } else {
979
+ this.apiKey = "UNIFY_API_KEY";
980
+ }
981
+ this.model = options == null ? void 0 : options.model;
982
+ this.start = true;
983
+ }
984
+ async process(request) {
985
+ const tools = request.actions.map(convertActionInputToOpenAITool);
986
+ const openai = new import_openai3.default({
987
+ apiKey: this.apiKey,
988
+ baseURL: "https://api.unify.ai/v0/"
989
+ });
990
+ const forwardedParameters = request.forwardedParameters;
991
+ const messages = request.messages.map(convertMessageToOpenAIMessage);
992
+ const stream = await openai.chat.completions.create({
993
+ model: this.model,
994
+ messages,
995
+ stream: true,
996
+ ...tools.length > 0 && {
997
+ tools
998
+ },
999
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.temperature) && {
1000
+ temperature: forwardedParameters.temperature
1001
+ }
1002
+ });
1003
+ let model = null;
1004
+ let currentMessageId;
1005
+ let currentToolCallId;
1006
+ request.eventSource.stream(async (eventStream$) => {
1007
+ var _a, _b;
1008
+ let mode = null;
1009
+ for await (const chunk of stream) {
1010
+ if (this.start) {
1011
+ model = chunk.model;
1012
+ currentMessageId = (0, import_shared4.randomId)();
1013
+ eventStream$.sendTextMessageStart({
1014
+ messageId: currentMessageId
1015
+ });
1016
+ eventStream$.sendTextMessageContent({
1017
+ messageId: currentMessageId,
1018
+ content: `Model used: ${model}
1019
+ `
1020
+ });
1021
+ eventStream$.sendTextMessageEnd({
1022
+ messageId: currentMessageId
1023
+ });
1024
+ this.start = false;
1025
+ }
1026
+ const toolCall = (_a = chunk.choices[0].delta.tool_calls) == null ? void 0 : _a[0];
1027
+ const content = chunk.choices[0].delta.content;
1028
+ if (mode === "message" && (toolCall == null ? void 0 : toolCall.id)) {
1029
+ mode = null;
1030
+ eventStream$.sendTextMessageEnd({
1031
+ messageId: currentMessageId
1032
+ });
1033
+ } else if (mode === "function" && (toolCall === void 0 || (toolCall == null ? void 0 : toolCall.id))) {
1034
+ mode = null;
1035
+ eventStream$.sendActionExecutionEnd({
1036
+ actionExecutionId: currentToolCallId
1037
+ });
1038
+ }
1039
+ if (mode === null) {
1040
+ if (toolCall == null ? void 0 : toolCall.id) {
1041
+ mode = "function";
1042
+ currentToolCallId = toolCall.id;
1043
+ eventStream$.sendActionExecutionStart({
1044
+ actionExecutionId: currentToolCallId,
1045
+ actionName: toolCall.function.name
1046
+ });
1047
+ } else if (content) {
1048
+ mode = "message";
1049
+ currentMessageId = chunk.id;
1050
+ eventStream$.sendTextMessageStart({
1051
+ messageId: currentMessageId
1052
+ });
1053
+ }
1054
+ }
1055
+ if (mode === "message" && content) {
1056
+ eventStream$.sendTextMessageContent({
1057
+ messageId: currentMessageId,
1058
+ content
1059
+ });
1060
+ } else if (mode === "function" && ((_b = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _b.arguments)) {
1061
+ eventStream$.sendActionExecutionArgs({
1062
+ actionExecutionId: currentToolCallId,
1063
+ args: toolCall.function.arguments
1064
+ });
1065
+ }
1066
+ }
1067
+ if (mode === "message") {
1068
+ eventStream$.sendTextMessageEnd({
1069
+ messageId: currentMessageId
1070
+ });
1071
+ } else if (mode === "function") {
1072
+ eventStream$.sendActionExecutionEnd({
1073
+ actionExecutionId: currentToolCallId
1074
+ });
1075
+ }
1076
+ eventStream$.complete();
1077
+ });
1078
+ return {
1079
+ threadId: request.threadId || (0, import_shared4.randomId)()
1080
+ };
1081
+ }
1082
+ };
1083
+ __name(UnifyAdapter, "UnifyAdapter");
1084
+
1085
+ // src/service-adapters/groq/groq-adapter.ts
1086
+ var import_groq_sdk = require("groq-sdk");
1087
+ var import_shared5 = require("@copilotkit/shared");
1088
+ var DEFAULT_MODEL2 = "llama3-groq-70b-8192-tool-use-preview";
1089
+ var GroqAdapter = class {
1090
+ model = DEFAULT_MODEL2;
1091
+ disableParallelToolCalls = false;
1092
+ _groq;
1093
+ get groq() {
1094
+ return this._groq;
1095
+ }
1096
+ constructor(params) {
1097
+ this._groq = (params == null ? void 0 : params.groq) || new import_groq_sdk.Groq({});
1098
+ if (params == null ? void 0 : params.model) {
1099
+ this.model = params.model;
1100
+ }
1101
+ this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
1102
+ }
1103
+ async process(request) {
1104
+ const { threadId, model = this.model, messages, actions, eventSource, forwardedParameters } = request;
1105
+ const tools = actions.map(convertActionInputToOpenAITool);
1106
+ let openaiMessages = messages.map(convertMessageToOpenAIMessage);
1107
+ openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
1108
+ let toolChoice = forwardedParameters == null ? void 0 : forwardedParameters.toolChoice;
1109
+ if ((forwardedParameters == null ? void 0 : forwardedParameters.toolChoice) === "function") {
1110
+ toolChoice = {
1111
+ type: "function",
1112
+ function: {
1113
+ name: forwardedParameters.toolChoiceFunctionName
1114
+ }
1115
+ };
1116
+ }
1117
+ const stream = await this.groq.chat.completions.create({
1118
+ model,
1119
+ stream: true,
1120
+ messages: openaiMessages,
1121
+ ...tools.length > 0 && {
1122
+ tools
1123
+ },
1124
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
1125
+ max_tokens: forwardedParameters.maxTokens
1126
+ },
1127
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.stop) && {
1128
+ stop: forwardedParameters.stop
1129
+ },
1130
+ ...toolChoice && {
1131
+ tool_choice: toolChoice
1132
+ },
1133
+ ...this.disableParallelToolCalls && {
1134
+ parallel_tool_calls: false
1135
+ },
1136
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.temperature) && {
1137
+ temperature: forwardedParameters.temperature
1138
+ }
1139
+ });
1140
+ eventSource.stream(async (eventStream$) => {
1141
+ var _a, _b;
1142
+ let mode = null;
1143
+ let currentMessageId;
1144
+ let currentToolCallId;
1145
+ for await (const chunk of stream) {
1146
+ const toolCall = (_a = chunk.choices[0].delta.tool_calls) == null ? void 0 : _a[0];
1147
+ const content = chunk.choices[0].delta.content;
1148
+ if (mode === "message" && (toolCall == null ? void 0 : toolCall.id)) {
1149
+ mode = null;
1150
+ eventStream$.sendTextMessageEnd({
1151
+ messageId: currentMessageId
1152
+ });
1153
+ } else if (mode === "function" && (toolCall === void 0 || (toolCall == null ? void 0 : toolCall.id))) {
1154
+ mode = null;
1155
+ eventStream$.sendActionExecutionEnd({
1156
+ actionExecutionId: currentToolCallId
1157
+ });
1158
+ }
1159
+ if (mode === null) {
1160
+ if (toolCall == null ? void 0 : toolCall.id) {
1161
+ mode = "function";
1162
+ currentToolCallId = toolCall.id;
1163
+ eventStream$.sendActionExecutionStart({
1164
+ actionExecutionId: currentToolCallId,
1165
+ actionName: toolCall.function.name,
1166
+ parentMessageId: chunk.id
1167
+ });
1168
+ } else if (content) {
1169
+ mode = "message";
1170
+ currentMessageId = chunk.id;
1171
+ eventStream$.sendTextMessageStart({
1172
+ messageId: currentMessageId
1173
+ });
1174
+ }
1175
+ }
1176
+ if (mode === "message" && content) {
1177
+ eventStream$.sendTextMessageContent({
1178
+ messageId: currentMessageId,
1179
+ content
1180
+ });
1181
+ } else if (mode === "function" && ((_b = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _b.arguments)) {
1182
+ eventStream$.sendActionExecutionArgs({
1183
+ actionExecutionId: currentToolCallId,
1184
+ args: toolCall.function.arguments
1185
+ });
1186
+ }
1187
+ }
1188
+ if (mode === "message") {
1189
+ eventStream$.sendTextMessageEnd({
1190
+ messageId: currentMessageId
1191
+ });
1192
+ } else if (mode === "function") {
1193
+ eventStream$.sendActionExecutionEnd({
1194
+ actionExecutionId: currentToolCallId
1195
+ });
1196
+ }
1197
+ eventStream$.complete();
1198
+ });
1199
+ return {
1200
+ threadId: threadId || (0, import_shared5.randomId)()
1201
+ };
1202
+ }
1203
+ };
1204
+ __name(GroqAdapter, "GroqAdapter");
1205
+
1206
+ // src/service-adapters/events.ts
1207
+ var import_shared8 = require("@copilotkit/shared");
1208
+ var import_rxjs2 = require("rxjs");
1209
+
1210
+ // src/lib/telemetry-client.ts
1211
+ var import_shared7 = require("@copilotkit/shared");
1212
+
1213
+ // src/lib/runtime/remote-action-constructors.ts
1214
+ var import_node_crypto2 = require("crypto");
1215
+
1216
+ // src/agents/langgraph/event-source.ts
1217
+ var import_rxjs = require("rxjs");
1218
+
1219
+ // src/agents/langgraph/events.ts
1220
+ var LangGraphEventTypes;
1221
+ (function(LangGraphEventTypes2) {
1222
+ LangGraphEventTypes2["OnChainStart"] = "on_chain_start";
1223
+ LangGraphEventTypes2["OnChainStream"] = "on_chain_stream";
1224
+ LangGraphEventTypes2["OnChainEnd"] = "on_chain_end";
1225
+ LangGraphEventTypes2["OnChatModelStart"] = "on_chat_model_start";
1226
+ LangGraphEventTypes2["OnChatModelStream"] = "on_chat_model_stream";
1227
+ LangGraphEventTypes2["OnChatModelEnd"] = "on_chat_model_end";
1228
+ LangGraphEventTypes2["OnToolStart"] = "on_tool_start";
1229
+ LangGraphEventTypes2["OnToolEnd"] = "on_tool_end";
1230
+ LangGraphEventTypes2["OnCopilotKitStateSync"] = "on_copilotkit_state_sync";
1231
+ LangGraphEventTypes2["OnCopilotKitEmitMessage"] = "on_copilotkit_emit_message";
1232
+ LangGraphEventTypes2["OnCopilotKitEmitToolCall"] = "on_copilotkit_emit_tool_call";
1233
+ LangGraphEventTypes2["OnCustomEvent"] = "on_custom_event";
1234
+ })(LangGraphEventTypes || (LangGraphEventTypes = {}));
1235
+ var CustomEventNames;
1236
+ (function(CustomEventNames2) {
1237
+ CustomEventNames2["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
1238
+ CustomEventNames2["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
1239
+ CustomEventNames2["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
1240
+ CustomEventNames2["CopilotKitExit"] = "copilotkit_exit";
1241
+ })(CustomEventNames || (CustomEventNames = {}));
1242
+
1243
+ // src/agents/langgraph/event-source.ts
1244
+ var import_shared6 = require("@copilotkit/shared");
1245
+ var RemoteLangGraphEventSource = class {
1246
+ eventStream$ = new import_rxjs.ReplaySubject();
1247
+ shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
1248
+ if (typeof shouldEmitToolCalls === "boolean") {
1249
+ return shouldEmitToolCalls;
1250
+ }
1251
+ if (Array.isArray(shouldEmitToolCalls)) {
1252
+ return shouldEmitToolCalls.includes(toolCallName);
1253
+ }
1254
+ return shouldEmitToolCalls === toolCallName;
1255
+ }
1256
+ getCurrentContent(event) {
1257
+ var _a, _b, _c, _d, _e;
1258
+ const content = ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.content) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.content);
1259
+ if (!content) {
1260
+ const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
1261
+ for (const chunk of toolCallChunks) {
1262
+ if (chunk.args) {
1263
+ return chunk.args;
1264
+ }
1265
+ }
1266
+ }
1267
+ if (typeof content === "string") {
1268
+ return content;
1269
+ } else if (Array.isArray(content) && content.length > 0) {
1270
+ return content[0].text;
1271
+ }
1272
+ return null;
1273
+ }
1274
+ getCurrentMessageId(event) {
1275
+ var _a, _b, _c, _d, _e;
1276
+ return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.id) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.id);
1277
+ }
1278
+ getCurrentToolCallChunks(event) {
1279
+ var _a, _b, _c, _d, _e;
1280
+ return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.tool_call_chunks);
1281
+ }
1282
+ getResponseMetadata(event) {
1283
+ var _a, _b, _c, _d, _e;
1284
+ return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.response_metadata) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.response_metadata);
1285
+ }
1286
+ processLangGraphEvents() {
1287
+ let lastEventWithState = null;
1288
+ return this.eventStream$.pipe((0, import_rxjs.scan)((acc, event) => {
1289
+ if (event.event === LangGraphEventTypes.OnChatModelStream) {
1290
+ const prevMessageId = acc.lastMessageId;
1291
+ acc.currentContent = this.getCurrentContent(event);
1292
+ acc.lastMessageId = this.getCurrentMessageId(event) ?? acc.lastMessageId;
1293
+ const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
1294
+ const responseMetadata = this.getResponseMetadata(event);
1295
+ acc.isToolCallStart = toolCallChunks.some((chunk) => chunk.name && chunk.id);
1296
+ acc.isMessageStart = prevMessageId !== acc.lastMessageId && !acc.isToolCallStart;
1297
+ acc.isToolCall = toolCallChunks && toolCallChunks.length > 0;
1298
+ acc.isToolCallEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls";
1299
+ acc.isMessageEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop";
1300
+ ({ name: acc.lastToolCallName, id: acc.lastToolCallId } = toolCallChunks.find((chunk) => chunk.name && chunk.id) ?? {
1301
+ name: acc.lastToolCallName,
1302
+ id: acc.lastToolCallId
1303
+ });
1304
+ }
1305
+ acc.event = event;
1306
+ lastEventWithState = acc;
1307
+ return acc;
1308
+ }, {
1309
+ event: null,
1310
+ isMessageStart: false,
1311
+ isMessageEnd: false,
1312
+ isToolCallStart: false,
1313
+ isToolCallEnd: false,
1314
+ isToolCall: false,
1315
+ lastMessageId: null,
1316
+ lastToolCallId: null,
1317
+ lastToolCallName: null,
1318
+ currentContent: null
1319
+ }), (0, import_rxjs.mergeMap)((acc) => {
1320
+ const events = [];
1321
+ let shouldEmitMessages = true;
1322
+ let shouldEmitToolCalls = true;
1323
+ if (acc.event.event == LangGraphEventTypes.OnChatModelStream) {
1324
+ if ("copilotkit:emit-tool-calls" in (acc.event.metadata || {})) {
1325
+ shouldEmitToolCalls = acc.event.metadata["copilotkit:emit-tool-calls"];
1326
+ }
1327
+ if ("copilotkit:emit-messages" in (acc.event.metadata || {})) {
1328
+ shouldEmitMessages = acc.event.metadata["copilotkit:emit-messages"];
1329
+ }
1330
+ }
1331
+ const responseMetadata = this.getResponseMetadata(acc.event);
1332
+ if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls" && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1333
+ events.push({
1334
+ type: RuntimeEventTypes.ActionExecutionEnd,
1335
+ actionExecutionId: acc.lastToolCallId
1336
+ });
1337
+ }
1338
+ if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop" && shouldEmitMessages) {
1339
+ events.push({
1340
+ type: RuntimeEventTypes.TextMessageEnd,
1341
+ messageId: acc.lastMessageId
1342
+ });
1343
+ }
1344
+ switch (acc.event.event) {
1345
+ case LangGraphEventTypes.OnCustomEvent:
1346
+ if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1347
+ events.push({
1348
+ type: RuntimeEventTypes.TextMessageStart,
1349
+ messageId: acc.event.data.message_id
1350
+ });
1351
+ events.push({
1352
+ type: RuntimeEventTypes.TextMessageContent,
1353
+ messageId: acc.event.data.message_id,
1354
+ content: acc.event.data.message
1355
+ });
1356
+ events.push({
1357
+ type: RuntimeEventTypes.TextMessageEnd,
1358
+ messageId: acc.event.data.message_id
1359
+ });
1360
+ } else if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1361
+ events.push({
1362
+ type: RuntimeEventTypes.ActionExecutionStart,
1363
+ actionExecutionId: acc.event.data.id,
1364
+ actionName: acc.event.data.name,
1365
+ parentMessageId: acc.event.data.id
1366
+ });
1367
+ events.push({
1368
+ type: RuntimeEventTypes.ActionExecutionArgs,
1369
+ actionExecutionId: acc.event.data.id,
1370
+ args: JSON.stringify(acc.event.data.args)
1371
+ });
1372
+ events.push({
1373
+ type: RuntimeEventTypes.ActionExecutionEnd,
1374
+ actionExecutionId: acc.event.data.id
1375
+ });
1376
+ }
1377
+ break;
1378
+ case LangGraphEventTypes.OnCopilotKitStateSync:
1379
+ events.push({
1380
+ type: RuntimeEventTypes.AgentStateMessage,
1381
+ threadId: acc.event.thread_id,
1382
+ role: acc.event.role,
1383
+ agentName: acc.event.agent_name,
1384
+ nodeName: acc.event.node_name,
1385
+ runId: acc.event.run_id,
1386
+ active: acc.event.active,
1387
+ state: JSON.stringify(acc.event.state),
1388
+ running: acc.event.running
1389
+ });
1390
+ break;
1391
+ case LangGraphEventTypes.OnChatModelStream:
1392
+ if (acc.isToolCallStart && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1393
+ events.push({
1394
+ type: RuntimeEventTypes.ActionExecutionStart,
1395
+ actionExecutionId: acc.lastToolCallId,
1396
+ actionName: acc.lastToolCallName,
1397
+ parentMessageId: acc.lastMessageId
1398
+ });
1399
+ } else if (acc.isMessageStart && shouldEmitMessages) {
1400
+ events.push({
1401
+ type: RuntimeEventTypes.TextMessageStart,
1402
+ messageId: acc.lastMessageId
1403
+ });
1404
+ }
1405
+ if (acc.isToolCall && acc.currentContent && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1406
+ events.push({
1407
+ type: RuntimeEventTypes.ActionExecutionArgs,
1408
+ actionExecutionId: acc.lastToolCallId,
1409
+ args: acc.currentContent
1410
+ });
1411
+ } else if (!acc.isToolCall && acc.currentContent && shouldEmitMessages) {
1412
+ events.push({
1413
+ type: RuntimeEventTypes.TextMessageContent,
1414
+ messageId: acc.lastMessageId,
1415
+ content: acc.currentContent
1416
+ });
1417
+ }
1418
+ break;
1419
+ }
1420
+ return events;
1421
+ }), (0, import_rxjs.catchError)((error) => {
1422
+ console.error(error);
1423
+ const events = [];
1424
+ if ((lastEventWithState == null ? void 0 : lastEventWithState.lastMessageId) && !lastEventWithState.isToolCall) {
1425
+ events.push({
1426
+ type: RuntimeEventTypes.TextMessageEnd,
1427
+ messageId: lastEventWithState.lastMessageId
1428
+ });
1429
+ }
1430
+ if (lastEventWithState == null ? void 0 : lastEventWithState.lastToolCallId) {
1431
+ events.push({
1432
+ type: RuntimeEventTypes.ActionExecutionEnd,
1433
+ actionExecutionId: lastEventWithState.lastToolCallId
1434
+ });
1435
+ }
1436
+ const messageId = (0, import_shared6.randomId)();
1437
+ events.push({
1438
+ type: RuntimeEventTypes.TextMessageStart,
1439
+ messageId
1440
+ });
1441
+ events.push({
1442
+ type: RuntimeEventTypes.TextMessageContent,
1443
+ messageId,
1444
+ content: "\u274C An error occurred. Please try again."
1445
+ });
1446
+ events.push({
1447
+ type: RuntimeEventTypes.TextMessageEnd,
1448
+ messageId
1449
+ });
1450
+ return events;
1451
+ }));
1452
+ }
1453
+ };
1454
+ __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
1455
+
1456
+ // src/lib/runtime/remote-lg-action.ts
1457
+ var import_langgraph_sdk = require("@langchain/langgraph-sdk");
1458
+ var import_node_crypto = require("crypto");
1459
+ var import_partial_json = require("partial-json");
1460
+
1461
+ // src/graphql/types/enums.ts
1462
+ var import_type_graphql = require("type-graphql");
1463
+ var MessageRole;
1464
+ (function(MessageRole2) {
1465
+ MessageRole2["user"] = "user";
1466
+ MessageRole2["assistant"] = "assistant";
1467
+ MessageRole2["system"] = "system";
1468
+ MessageRole2["tool"] = "tool";
1469
+ })(MessageRole || (MessageRole = {}));
1470
+ var CopilotRequestType;
1471
+ (function(CopilotRequestType2) {
1472
+ CopilotRequestType2["Chat"] = "Chat";
1473
+ CopilotRequestType2["Task"] = "Task";
1474
+ CopilotRequestType2["TextareaCompletion"] = "TextareaCompletion";
1475
+ CopilotRequestType2["TextareaPopover"] = "TextareaPopover";
1476
+ CopilotRequestType2["Suggestion"] = "Suggestion";
1477
+ })(CopilotRequestType || (CopilotRequestType = {}));
1478
+ var ActionInputAvailability;
1479
+ (function(ActionInputAvailability2) {
1480
+ ActionInputAvailability2["disabled"] = "disabled";
1481
+ ActionInputAvailability2["enabled"] = "enabled";
1482
+ ActionInputAvailability2["remote"] = "remote";
1483
+ })(ActionInputAvailability || (ActionInputAvailability = {}));
1484
+ (0, import_type_graphql.registerEnumType)(MessageRole, {
1485
+ name: "MessageRole",
1486
+ description: "The role of the message"
1487
+ });
1488
+ (0, import_type_graphql.registerEnumType)(CopilotRequestType, {
1489
+ name: "CopilotRequestType",
1490
+ description: "The type of Copilot request"
1491
+ });
1492
+ (0, import_type_graphql.registerEnumType)(ActionInputAvailability, {
1493
+ name: "ActionInputAvailability",
1494
+ description: "The availability of the frontend action"
1495
+ });
1496
+
1497
+ // src/lib/runtime/remote-lg-action.ts
1498
+ async function execute(args) {
1499
+ return new ReadableStream({
1500
+ async start(controller) {
1501
+ try {
1502
+ await streamEvents(controller, args);
1503
+ controller.close();
1504
+ } catch (err) {
1505
+ }
1506
+ }
1507
+ });
1508
+ }
1509
+ __name(execute, "execute");
1510
+ async function streamEvents(controller, args) {
1511
+ var _a, _b, _c, _d, _e, _f;
1512
+ const { deploymentUrl, langsmithApiKey, threadId: agrsInitialThreadId, agent, nodeName: initialNodeName, state: initialState, messages, actions, logger: logger2 } = args;
1513
+ let nodeName = initialNodeName;
1514
+ let state = initialState;
1515
+ const { name, assistantId: initialAssistantId } = agent;
1516
+ const client = new import_langgraph_sdk.Client({
1517
+ apiUrl: deploymentUrl,
1518
+ apiKey: langsmithApiKey
1519
+ });
1520
+ let initialThreadId = agrsInitialThreadId;
1521
+ const wasInitiatedWithExistingThread = !!initialThreadId;
1522
+ if (initialThreadId && initialThreadId.startsWith("ck-")) {
1523
+ initialThreadId = initialThreadId.substring(3);
1524
+ }
1525
+ const threadId = initialThreadId ?? (0, import_node_crypto.randomUUID)();
1526
+ if (initialThreadId === threadId) {
1527
+ await client.threads.get(threadId);
1528
+ } else {
1529
+ await client.threads.create({
1530
+ threadId
1531
+ });
1532
+ }
1533
+ let agentState = {
1534
+ values: {}
1535
+ };
1536
+ if (wasInitiatedWithExistingThread) {
1537
+ agentState = await client.threads.getState(threadId);
1538
+ }
1539
+ const agentStateValues = agentState.values;
1540
+ state.messages = agentStateValues.messages;
1541
+ const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
1542
+ let formattedMessages = [];
1543
+ try {
1544
+ formattedMessages = copilotkitMessagesToLangChain(messages);
1545
+ } catch (e) {
1546
+ logger2.error(e, `Error event thrown: ${e.message}`);
1547
+ }
1548
+ state = langGraphDefaultMergeState(state, formattedMessages, actions, name);
1549
+ if (mode === "continue") {
1550
+ await client.threads.updateState(threadId, {
1551
+ values: state,
1552
+ asNode: nodeName
1553
+ });
1554
+ }
1555
+ let streamInfo = {
1556
+ hashedLgcKey: (0, import_node_crypto.createHash)("sha256").update(langsmithApiKey).digest("hex")
1557
+ };
1558
+ const assistants = await client.assistants.search();
1559
+ const retrievedAssistant = assistants.find((a) => a.name === name || a.assistant_id === initialAssistantId);
1560
+ if (!retrievedAssistant) {
1561
+ telemetry_client_default.capture("oss.runtime.agent_execution_stream_errored", {
1562
+ ...streamInfo,
1563
+ error: `Found no assistants for given information, while ${assistants.length} assistants exists`
1564
+ });
1565
+ console.error(`
1566
+ No agent found for the agent name specified in CopilotKit provider
1567
+ Please check your available agents or provide an agent ID in the LangGraph Platform endpoint definition.
1568
+
1569
+
1570
+ These are the available agents: [${assistants.map((a) => `${a.name} (ID: ${a.assistant_id})`).join(", ")}]
1571
+ `);
1572
+ throw new Error("No agent id found");
1573
+ }
1574
+ const assistantId = retrievedAssistant.assistant_id;
1575
+ const graphInfo = await client.assistants.getGraph(assistantId);
1576
+ const streamInput = mode === "start" ? state : null;
1577
+ let streamingStateExtractor = new StreamingStateExtractor([]);
1578
+ let prevNodeName = null;
1579
+ let emitIntermediateStateUntilEnd = null;
1580
+ let shouldExit = false;
1581
+ let externalRunId = null;
1582
+ const streamResponse2 = client.runs.stream(threadId, assistantId, {
1583
+ input: streamInput,
1584
+ streamMode: [
1585
+ "events",
1586
+ "values"
1587
+ ]
1588
+ });
1589
+ const emit = /* @__PURE__ */ __name((message) => controller.enqueue(new TextEncoder().encode(message)), "emit");
1590
+ let latestStateValues = {};
1591
+ let updatedState = state;
1592
+ let manuallyEmittedState = null;
1593
+ try {
1594
+ telemetry_client_default.capture("oss.runtime.agent_execution_stream_started", {
1595
+ hashedLgcKey: streamInfo.hashedLgcKey
1596
+ });
1597
+ for await (const chunk of streamResponse2) {
1598
+ if (![
1599
+ "events",
1600
+ "values",
1601
+ "error"
1602
+ ].includes(chunk.event))
1603
+ continue;
1604
+ if (chunk.event === "error") {
1605
+ throw new Error(`Error event thrown: ${chunk.data.message}`);
1606
+ }
1607
+ if (chunk.event === "values") {
1608
+ latestStateValues = chunk.data;
1609
+ continue;
1610
+ }
1611
+ const event = chunk.data;
1612
+ const currentNodeName = event.name;
1613
+ const eventType = event.event;
1614
+ const runId = event.metadata.run_id;
1615
+ externalRunId = runId;
1616
+ const metadata = event.metadata;
1617
+ if (((_b = (_a = event.data) == null ? void 0 : _a.output) == null ? void 0 : _b.model) != null && ((_d = (_c = event.data) == null ? void 0 : _c.output) == null ? void 0 : _d.model) != "") {
1618
+ streamInfo.provider = (_f = (_e = event.data) == null ? void 0 : _e.output) == null ? void 0 : _f.model;
1619
+ }
1620
+ if (metadata.langgraph_host != null && metadata.langgraph_host != "") {
1621
+ streamInfo.langGraphHost = metadata.langgraph_host;
1622
+ }
1623
+ if (metadata.langgraph_version != null && metadata.langgraph_version != "") {
1624
+ streamInfo.langGraphVersion = metadata.langgraph_version;
1625
+ }
1626
+ shouldExit = shouldExit || eventType === LangGraphEventTypes.OnCustomEvent && event.name === CustomEventNames.CopilotKitExit;
1627
+ const emitIntermediateState = metadata["copilotkit:emit-intermediate-state"];
1628
+ const manuallyEmitIntermediateState = eventType === LangGraphEventTypes.OnCustomEvent && event.name === CustomEventNames.CopilotKitManuallyEmitIntermediateState;
1629
+ const exitingNode = nodeName === currentNodeName && eventType === LangGraphEventTypes.OnChainEnd;
1630
+ if (exitingNode) {
1631
+ manuallyEmittedState = null;
1632
+ }
1633
+ if (graphInfo["nodes"].some((node) => node.id === currentNodeName)) {
1634
+ nodeName = currentNodeName;
1635
+ }
1636
+ updatedState = manuallyEmittedState ?? latestStateValues;
1637
+ if (!nodeName) {
1638
+ continue;
1639
+ }
1640
+ if (manuallyEmitIntermediateState) {
1641
+ manuallyEmittedState = event.data;
1642
+ emit(getStateSyncEvent({
1643
+ threadId,
1644
+ runId,
1645
+ agentName: agent.name,
1646
+ nodeName,
1647
+ state: manuallyEmittedState,
1648
+ running: true,
1649
+ active: true
1650
+ }));
1651
+ continue;
1652
+ }
1653
+ if (emitIntermediateState && emitIntermediateStateUntilEnd == null) {
1654
+ emitIntermediateStateUntilEnd = nodeName;
1655
+ }
1656
+ if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStart) {
1657
+ streamingStateExtractor = new StreamingStateExtractor(emitIntermediateState);
1658
+ }
1659
+ if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStream) {
1660
+ streamingStateExtractor.bufferToolCalls(event);
1661
+ }
1662
+ if (emitIntermediateStateUntilEnd !== null) {
1663
+ updatedState = {
1664
+ ...updatedState,
1665
+ ...streamingStateExtractor.extractState()
1666
+ };
1667
+ }
1668
+ if (!emitIntermediateState && currentNodeName === emitIntermediateStateUntilEnd && eventType === LangGraphEventTypes.OnChainEnd) {
1669
+ emitIntermediateStateUntilEnd = null;
1670
+ }
1671
+ if (JSON.stringify(updatedState) !== JSON.stringify(state) || prevNodeName != nodeName || exitingNode) {
1672
+ state = updatedState;
1673
+ prevNodeName = nodeName;
1674
+ emit(getStateSyncEvent({
1675
+ threadId,
1676
+ runId,
1677
+ agentName: agent.name,
1678
+ nodeName,
1679
+ state,
1680
+ running: true,
1681
+ active: !exitingNode
1682
+ }));
1683
+ }
1684
+ emit(JSON.stringify(event) + "\n");
1685
+ }
1686
+ state = await client.threads.getState(threadId);
1687
+ const isEndNode = state.next.length === 0;
1688
+ nodeName = Object.keys(state.metadata.writes)[0];
1689
+ telemetry_client_default.capture("oss.runtime.agent_execution_stream_ended", streamInfo);
1690
+ emit(getStateSyncEvent({
1691
+ threadId,
1692
+ runId: externalRunId,
1693
+ agentName: agent.name,
1694
+ nodeName: isEndNode ? "__end__" : nodeName,
1695
+ state: state.values,
1696
+ running: !shouldExit,
1697
+ active: false,
1698
+ includeMessages: true
1699
+ }));
1700
+ return Promise.resolve();
1701
+ } catch (e) {
1702
+ logger2.error(e);
1703
+ telemetry_client_default.capture("oss.runtime.agent_execution_stream_errored", {
1704
+ ...streamInfo,
1705
+ error: e.message
1706
+ });
1707
+ return Promise.resolve();
1708
+ }
1709
+ }
1710
+ __name(streamEvents, "streamEvents");
1711
+ function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active, includeMessages = false }) {
1712
+ if (!includeMessages) {
1713
+ state = Object.keys(state).reduce((acc, key) => {
1714
+ if (key !== "messages") {
1715
+ acc[key] = state[key];
1716
+ }
1717
+ return acc;
1718
+ }, {});
1719
+ } else {
1720
+ state = {
1721
+ ...state,
1722
+ messages: langchainMessagesToCopilotKit(state.messages || [])
1723
+ };
1724
+ }
1725
+ return JSON.stringify({
1726
+ event: LangGraphEventTypes.OnCopilotKitStateSync,
1727
+ thread_id: threadId,
1728
+ run_id: runId,
1729
+ agent_name: agentName,
1730
+ node_name: nodeName,
1731
+ active,
1732
+ state,
1733
+ running,
1734
+ role: "assistant"
1735
+ }) + "\n";
1736
+ }
1737
+ __name(getStateSyncEvent, "getStateSyncEvent");
1738
+ var StreamingStateExtractor = /* @__PURE__ */ __name(class StreamingStateExtractor2 {
1739
+ emitIntermediateState;
1740
+ toolCallBuffer;
1741
+ currentToolCall;
1742
+ previouslyParsableState;
1743
+ constructor(emitIntermediateState) {
1744
+ this.emitIntermediateState = emitIntermediateState;
1745
+ this.toolCallBuffer = {};
1746
+ this.currentToolCall = null;
1747
+ this.previouslyParsableState = {};
1748
+ }
1749
+ bufferToolCalls(event) {
1750
+ if (event.data.chunk.tool_call_chunks.length > 0) {
1751
+ const chunk = event.data.chunk.tool_call_chunks[0];
1752
+ if (chunk.name !== null && chunk.name !== void 0) {
1753
+ this.currentToolCall = chunk.name;
1754
+ this.toolCallBuffer[this.currentToolCall] = chunk.args;
1755
+ } else if (this.currentToolCall !== null && this.currentToolCall !== void 0) {
1756
+ this.toolCallBuffer[this.currentToolCall] += chunk.args;
1757
+ }
1758
+ }
1759
+ }
1760
+ getEmitStateConfig(currentToolName) {
1761
+ for (const config2 of this.emitIntermediateState) {
1762
+ const stateKey = config2["state_key"];
1763
+ const tool = config2["tool"];
1764
+ const toolArgument = config2["tool_argument"];
1765
+ if (currentToolName === tool) {
1766
+ return [
1767
+ toolArgument,
1768
+ stateKey
1769
+ ];
1770
+ }
1771
+ }
1772
+ return [
1773
+ null,
1774
+ null
1775
+ ];
1776
+ }
1777
+ extractState() {
1778
+ const state = {};
1779
+ for (const [key, value] of Object.entries(this.toolCallBuffer)) {
1780
+ const [argumentName, stateKey] = this.getEmitStateConfig(key);
1781
+ if (stateKey === null) {
1782
+ continue;
1783
+ }
1784
+ let parsedValue;
1785
+ try {
1786
+ parsedValue = (0, import_partial_json.parse)(value);
1787
+ } catch (error) {
1788
+ if (key in this.previouslyParsableState) {
1789
+ parsedValue = this.previouslyParsableState[key];
1790
+ } else {
1791
+ continue;
1792
+ }
1793
+ }
1794
+ this.previouslyParsableState[key] = parsedValue;
1795
+ if (!argumentName) {
1796
+ state[stateKey] = parsedValue;
1797
+ } else {
1798
+ state[stateKey] = parsedValue[argumentName];
1799
+ }
1800
+ }
1801
+ return state;
1802
+ }
1803
+ }, "StreamingStateExtractor");
1804
+ function langGraphDefaultMergeState(state, messages, actions, agentName) {
1805
+ if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
1806
+ messages = messages.slice(1);
1807
+ }
1808
+ const existingMessages = state.messages || [];
1809
+ const existingMessageIds = new Set(existingMessages.map((message) => message.id));
1810
+ const newMessages = messages.filter((message) => !existingMessageIds.has(message.id));
1811
+ return {
1812
+ ...state,
1813
+ messages: newMessages,
1814
+ copilotkit: {
1815
+ actions
1816
+ }
1817
+ };
1818
+ }
1819
+ __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1820
+ function langchainMessagesToCopilotKit(messages) {
1821
+ const result = [];
1822
+ const tool_call_names = {};
1823
+ for (const message of messages) {
1824
+ if (message.type === "ai") {
1825
+ for (const tool_call of message.tool_calls) {
1826
+ tool_call_names[tool_call.id] = tool_call.name;
1827
+ }
1828
+ }
1829
+ }
1830
+ for (const message of messages) {
1831
+ let content = message.content;
1832
+ if (content instanceof Array) {
1833
+ content = content[0];
1834
+ }
1835
+ if (content instanceof Object) {
1836
+ content = content.text;
1837
+ }
1838
+ if (message.type === "human") {
1839
+ result.push({
1840
+ role: "user",
1841
+ content,
1842
+ id: message.id
1843
+ });
1844
+ } else if (message.type === "system") {
1845
+ result.push({
1846
+ role: "system",
1847
+ content,
1848
+ id: message.id
1849
+ });
1850
+ } else if (message.type === "ai") {
1851
+ if (message.tool_calls && message.tool_calls.length > 0) {
1852
+ for (const tool_call of message.tool_calls) {
1853
+ result.push({
1854
+ id: tool_call.id,
1855
+ name: tool_call.name,
1856
+ arguments: tool_call.args,
1857
+ parentMessageId: message.id
1858
+ });
1859
+ }
1860
+ } else {
1861
+ result.push({
1862
+ role: "assistant",
1863
+ content,
1864
+ id: message.id,
1865
+ parentMessageId: message.id
1866
+ });
1867
+ }
1868
+ } else if (message.type === "tool") {
1869
+ const actionName = tool_call_names[message.tool_call_id] || message.name || "";
1870
+ result.push({
1871
+ actionExecutionId: message.tool_call_id,
1872
+ actionName,
1873
+ result: content,
1874
+ id: message.id
1875
+ });
1876
+ }
1877
+ }
1878
+ const resultsDict = {};
1879
+ for (const msg of result) {
1880
+ if (msg.actionExecutionId) {
1881
+ resultsDict[msg.actionExecutionId] = msg;
1882
+ }
1883
+ }
1884
+ const reorderedResult = [];
1885
+ for (const msg of result) {
1886
+ if (!("actionExecutionId" in msg)) {
1887
+ reorderedResult.push(msg);
1888
+ }
1889
+ if ("arguments" in msg) {
1890
+ const msgId = msg.id;
1891
+ if (msgId in resultsDict) {
1892
+ reorderedResult.push(resultsDict[msgId]);
1893
+ }
1894
+ }
1895
+ }
1896
+ return reorderedResult;
1897
+ }
1898
+ __name(langchainMessagesToCopilotKit, "langchainMessagesToCopilotKit");
1899
+ function copilotkitMessagesToLangChain(messages) {
1900
+ const result = [];
1901
+ const processedActionExecutions = /* @__PURE__ */ new Set();
1902
+ for (const message of messages) {
1903
+ if (message.isTextMessage()) {
1904
+ if (message.role === "user") {
1905
+ result.push({
1906
+ ...message,
1907
+ role: MessageRole.user
1908
+ });
1909
+ } else if (message.role === "system") {
1910
+ result.push({
1911
+ ...message,
1912
+ role: MessageRole.system
1913
+ });
1914
+ } else if (message.role === "assistant") {
1915
+ result.push({
1916
+ ...message,
1917
+ role: MessageRole.assistant
1918
+ });
1919
+ }
1920
+ continue;
1921
+ }
1922
+ if (message.isActionExecutionMessage()) {
1923
+ const messageId = message.parentMessageId ?? message.id;
1924
+ if (processedActionExecutions.has(messageId)) {
1925
+ continue;
1926
+ }
1927
+ processedActionExecutions.add(messageId);
1928
+ const relatedActionExecutions = messages.filter((m) => m.isActionExecutionMessage() && (m.parentMessageId && m.parentMessageId === messageId || m.id === messageId));
1929
+ const tool_calls = relatedActionExecutions.map((m) => ({
1930
+ name: m.name,
1931
+ args: m.arguments,
1932
+ id: m.id
1933
+ }));
1934
+ result.push({
1935
+ id: messageId,
1936
+ type: "ActionExecutionMessage",
1937
+ content: "",
1938
+ tool_calls,
1939
+ role: MessageRole.assistant
1940
+ });
1941
+ continue;
1942
+ }
1943
+ if (message.isResultMessage()) {
1944
+ result.push({
1945
+ type: message.type,
1946
+ content: message.result,
1947
+ id: message.id,
1948
+ tool_call_id: message.actionExecutionId,
1949
+ name: message.actionName,
1950
+ role: MessageRole.tool
1951
+ });
1952
+ continue;
1953
+ }
1954
+ throw new Error(`Unknown message type ${message.type}`);
1955
+ }
1956
+ return result;
1957
+ }
1958
+ __name(copilotkitMessagesToLangChain, "copilotkitMessagesToLangChain");
1959
+
1960
+ // src/lib/runtime/remote-action-constructors.ts
1961
+ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
1962
+ const agents = endpoint.agents.map((agent) => ({
1963
+ name: agent.name,
1964
+ description: agent.description,
1965
+ parameters: [],
1966
+ handler: async (_args) => {
1967
+ },
1968
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [] }) => {
1969
+ var _a;
1970
+ logger2.debug({
1971
+ actionName: agent.name
1972
+ }, "Executing LangGraph Platform agent");
1973
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
1974
+ agentExecution: true,
1975
+ type: "langgraph-platform",
1976
+ agentsAmount: endpoint.agents.length,
1977
+ hashedLgcKey: (0, import_node_crypto2.createHash)("sha256").update(endpoint.langsmithApiKey).digest("hex")
1978
+ });
1979
+ let state = {};
1980
+ if (agentStates) {
1981
+ const jsonState = (_a = agentStates.find((state2) => state2.agentName === name)) == null ? void 0 : _a.state;
1982
+ if (jsonState) {
1983
+ state = JSON.parse(jsonState);
1984
+ }
1985
+ }
1986
+ try {
1987
+ const response = await execute({
1988
+ logger: logger2,
1989
+ deploymentUrl: endpoint.deploymentUrl,
1990
+ langsmithApiKey: endpoint.langsmithApiKey,
1991
+ agent,
1992
+ threadId,
1993
+ nodeName,
1994
+ messages: [
1995
+ ...messages,
1996
+ ...additionalMessages
1997
+ ],
1998
+ state,
1999
+ properties: graphqlContext.properties,
2000
+ actions: actionInputsWithoutAgents.map((action) => ({
2001
+ name: action.name,
2002
+ description: action.description,
2003
+ parameters: JSON.parse(action.jsonSchema)
2004
+ }))
2005
+ });
2006
+ const eventSource = new RemoteLangGraphEventSource();
2007
+ streamResponse(response, eventSource.eventStream$);
2008
+ return eventSource.processLangGraphEvents();
2009
+ } catch (error) {
2010
+ logger2.error({
2011
+ url: endpoint.deploymentUrl,
2012
+ status: 500,
2013
+ body: error.message
2014
+ }, "Failed to execute LangGraph Platform agent");
2015
+ throw new Error("Failed to execute LangGraph Platform agent");
2016
+ }
2017
+ }
2018
+ }));
2019
+ return [
2020
+ ...agents
2021
+ ];
2022
+ }
2023
+ __name(constructLGCRemoteAction, "constructLGCRemoteAction");
2024
+ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
2025
+ const totalAgents = Array.isArray(json["agents"]) ? json["agents"].length : 0;
2026
+ const actions = json["actions"].map((action) => ({
2027
+ name: action.name,
2028
+ description: action.description,
2029
+ parameters: action.parameters,
2030
+ handler: async (args) => {
2031
+ logger2.debug({
2032
+ actionName: action.name,
2033
+ args
2034
+ }, "Executing remote action");
2035
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
2036
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2037
+ agentExecution: false,
2038
+ type: "self-hosted",
2039
+ agentsAmount: totalAgents
2040
+ });
2041
+ try {
2042
+ const response = await fetch(`${url}/actions/execute`, {
2043
+ method: "POST",
2044
+ headers,
2045
+ body: JSON.stringify({
2046
+ name: action.name,
2047
+ arguments: args,
2048
+ properties: graphqlContext.properties
2049
+ })
2050
+ });
2051
+ if (!response.ok) {
2052
+ logger2.error({
2053
+ url,
2054
+ status: response.status,
2055
+ body: await response.text()
2056
+ }, "Failed to execute remote action");
2057
+ return "Failed to execute remote action";
2058
+ }
2059
+ const requestResult = await response.json();
2060
+ const result = requestResult["result"];
2061
+ logger2.debug({
2062
+ actionName: action.name,
2063
+ result
2064
+ }, "Executed remote action");
2065
+ return result;
2066
+ } catch (error) {
2067
+ logger2.error({
2068
+ error: error.message ? error.message : error + ""
2069
+ }, "Failed to execute remote action");
2070
+ return "Failed to execute remote action";
2071
+ }
2072
+ }
2073
+ }));
2074
+ const agents = totalAgents ? json["agents"].map((agent) => ({
2075
+ name: agent.name,
2076
+ description: agent.description,
2077
+ parameters: [],
2078
+ handler: async (_args) => {
2079
+ },
2080
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [] }) => {
2081
+ var _a;
2082
+ logger2.debug({
2083
+ actionName: agent.name
2084
+ }, "Executing remote agent");
2085
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
2086
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2087
+ agentExecution: true,
2088
+ type: "self-hosted",
2089
+ agentsAmount: json["agents"].length
2090
+ });
2091
+ let state = {};
2092
+ if (agentStates) {
2093
+ const jsonState = (_a = agentStates.find((state2) => state2.agentName === name)) == null ? void 0 : _a.state;
2094
+ if (jsonState) {
2095
+ state = JSON.parse(jsonState);
2096
+ }
2097
+ }
2098
+ const response = await fetch(`${url}/agents/execute`, {
2099
+ method: "POST",
2100
+ headers,
2101
+ body: JSON.stringify({
2102
+ name,
2103
+ threadId,
2104
+ nodeName,
2105
+ messages: [
2106
+ ...messages,
2107
+ ...additionalMessages
2108
+ ],
2109
+ state,
2110
+ properties: graphqlContext.properties,
2111
+ actions: actionInputsWithoutAgents.map((action) => ({
2112
+ name: action.name,
2113
+ description: action.description,
2114
+ parameters: JSON.parse(action.jsonSchema)
2115
+ }))
2116
+ })
2117
+ });
2118
+ if (!response.ok) {
2119
+ logger2.error({
2120
+ url,
2121
+ status: response.status,
2122
+ body: await response.text()
2123
+ }, "Failed to execute remote agent");
2124
+ throw new Error("Failed to execute remote agent");
2125
+ }
2126
+ const eventSource = new RemoteLangGraphEventSource();
2127
+ streamResponse(response.body, eventSource.eventStream$);
2128
+ return eventSource.processLangGraphEvents();
2129
+ }
2130
+ })) : [];
2131
+ return [
2132
+ ...actions,
2133
+ ...agents
2134
+ ];
2135
+ }
2136
+ __name(constructRemoteActions, "constructRemoteActions");
2137
+ async function streamResponse(response, eventStream$) {
2138
+ const reader = response.getReader();
2139
+ const decoder = new TextDecoder();
2140
+ let buffer = [];
2141
+ function flushBuffer() {
2142
+ const currentBuffer = buffer.join("");
2143
+ if (currentBuffer.trim().length === 0) {
2144
+ return;
2145
+ }
2146
+ const parts = currentBuffer.split("\n");
2147
+ if (parts.length === 0) {
2148
+ return;
2149
+ }
2150
+ const lastPartIsComplete = currentBuffer.endsWith("\n");
2151
+ buffer = [];
2152
+ if (!lastPartIsComplete) {
2153
+ buffer.push(parts.pop());
2154
+ }
2155
+ parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
2156
+ eventStream$.next(JSON.parse(part));
2157
+ });
2158
+ }
2159
+ __name(flushBuffer, "flushBuffer");
2160
+ try {
2161
+ while (true) {
2162
+ const { done, value } = await reader.read();
2163
+ if (!done) {
2164
+ buffer.push(decoder.decode(value, {
2165
+ stream: true
2166
+ }));
2167
+ }
2168
+ flushBuffer();
2169
+ if (done) {
2170
+ break;
2171
+ }
2172
+ }
2173
+ } catch (error) {
2174
+ console.error("Error in stream", error);
2175
+ eventStream$.error(error);
2176
+ return;
2177
+ }
2178
+ eventStream$.complete();
2179
+ }
2180
+ __name(streamResponse, "streamResponse");
2181
+ function createHeaders(onBeforeRequest, graphqlContext) {
2182
+ const headers = {
2183
+ "Content-Type": "application/json"
2184
+ };
2185
+ if (onBeforeRequest) {
2186
+ const { headers: additionalHeaders } = onBeforeRequest({
2187
+ ctx: graphqlContext
2188
+ });
2189
+ if (additionalHeaders) {
2190
+ Object.assign(headers, additionalHeaders);
2191
+ }
2192
+ }
2193
+ return headers;
2194
+ }
2195
+ __name(createHeaders, "createHeaders");
2196
+
2197
+ // src/lib/runtime/remote-actions.ts
2198
+ var EndpointType;
2199
+ (function(EndpointType2) {
2200
+ EndpointType2["CopilotKit"] = "copilotKit";
2201
+ EndpointType2["LangGraphPlatform"] = "langgraph-platform";
2202
+ })(EndpointType || (EndpointType = {}));
2203
+ function isLangGraphAgentAction(action) {
2204
+ if (!action) {
2205
+ return false;
2206
+ }
2207
+ return typeof action.langGraphAgentHandler === "function";
2208
+ }
2209
+ __name(isLangGraphAgentAction, "isLangGraphAgentAction");
2210
+ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
2211
+ logger2.debug({
2212
+ url
2213
+ }, "Fetching actions from url");
2214
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
2215
+ try {
2216
+ const response = await fetch(`${url}/info`, {
2217
+ method: "POST",
2218
+ headers,
2219
+ body: JSON.stringify({
2220
+ properties: graphqlContext.properties,
2221
+ frontendUrl
2222
+ })
2223
+ });
2224
+ if (!response.ok) {
2225
+ logger2.error({
2226
+ url,
2227
+ status: response.status,
2228
+ body: await response.text()
2229
+ }, "Failed to fetch actions from url");
2230
+ return {
2231
+ actions: [],
2232
+ agents: []
2233
+ };
2234
+ }
2235
+ const json = await response.json();
2236
+ logger2.debug({
2237
+ json
2238
+ }, "Fetched actions from url");
2239
+ return json;
2240
+ } catch (error) {
2241
+ logger2.error({
2242
+ error: error.message ? error.message : error + ""
2243
+ }, "Failed to fetch actions from url");
2244
+ return {
2245
+ actions: [],
2246
+ agents: []
2247
+ };
2248
+ }
2249
+ }
2250
+ __name(fetchRemoteInfo, "fetchRemoteInfo");
2251
+ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
2252
+ const logger2 = graphqlContext.logger.child({
2253
+ component: "remote-actions.fetchRemoteActions"
2254
+ });
2255
+ logger2.debug({
2256
+ remoteEndpointDefinitions
2257
+ }, "Fetching from remote endpoints");
2258
+ const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
2259
+ if (value.type === "langgraph-platform") {
2260
+ return value;
2261
+ }
2262
+ return index === self.findIndex((t) => t.url === value.url);
2263
+ });
2264
+ const result = await Promise.all(filtered.map(async (endpoint) => {
2265
+ if (endpoint.type === "langgraph-platform") {
2266
+ return constructLGCRemoteAction({
2267
+ endpoint,
2268
+ messages,
2269
+ graphqlContext,
2270
+ logger: logger2.child({
2271
+ component: "remote-actions.constructLGCRemoteAction",
2272
+ endpoint
2273
+ }),
2274
+ agentStates
2275
+ });
2276
+ }
2277
+ const json = await fetchRemoteInfo({
2278
+ url: endpoint.url,
2279
+ onBeforeRequest: endpoint.onBeforeRequest,
2280
+ graphqlContext,
2281
+ logger: logger2.child({
2282
+ component: "remote-actions.fetchActionsFromUrl",
2283
+ endpoint
2284
+ }),
2285
+ frontendUrl
2286
+ });
2287
+ return constructRemoteActions({
2288
+ json,
2289
+ messages,
2290
+ url: endpoint.url,
2291
+ onBeforeRequest: endpoint.onBeforeRequest,
2292
+ graphqlContext,
2293
+ logger: logger2.child({
2294
+ component: "remote-actions.constructActions",
2295
+ endpoint
2296
+ }),
2297
+ agentStates
2298
+ });
2299
+ }));
2300
+ return result.flat();
2301
+ }
2302
+ __name(setupRemoteActions, "setupRemoteActions");
2303
+
2304
+ // src/lib/telemetry-client.ts
2305
+ var import_node_crypto3 = require("crypto");
2306
+ var packageJson = require_package();
2307
+ var telemetryClient = new import_shared7.TelemetryClient({
2308
+ packageName: packageJson.name,
2309
+ packageVersion: packageJson.version
2310
+ });
2311
+ function getRuntimeInstanceTelemetryInfo(runtime) {
2312
+ const endpointsInfo = runtime.remoteEndpointDefinitions.reduce((acc, endpoint) => {
2313
+ let info = {
2314
+ ...acc
2315
+ };
2316
+ const endpointType = resolveEndpointType(endpoint);
2317
+ if (!info.endpointTypes.includes(endpointType)) {
2318
+ info = {
2319
+ ...info,
2320
+ endpointTypes: [
2321
+ ...info.endpointTypes,
2322
+ endpointType
2323
+ ]
2324
+ };
2325
+ }
2326
+ if (endpointType === EndpointType.LangGraphPlatform) {
2327
+ const ep = endpoint;
2328
+ info = {
2329
+ ...info,
2330
+ agentsAmount: ep.agents.length,
2331
+ hashedKey: (0, import_node_crypto3.createHash)("sha256").update(ep.langsmithApiKey).digest("hex")
2332
+ };
2333
+ }
2334
+ return info;
2335
+ }, {
2336
+ endpointTypes: [],
2337
+ agentsAmount: null,
2338
+ hashedKey: null
2339
+ });
2340
+ return {
2341
+ actionsAmount: runtime.actions.length,
2342
+ endpointsAmount: runtime.remoteEndpointDefinitions.length,
2343
+ endpointTypes: endpointsInfo.endpointTypes,
2344
+ agentsAmount: endpointsInfo.agentsAmount,
2345
+ hashedLgcKey: endpointsInfo.hashedKey
2346
+ };
2347
+ }
2348
+ __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
2349
+ var telemetry_client_default = telemetryClient;
2350
+
2351
+ // src/graphql/types/base/index.ts
2352
+ var import_type_graphql2 = require("type-graphql");
2353
+ function _ts_decorate(decorators, target, key, desc) {
2354
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2355
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2356
+ r = Reflect.decorate(decorators, target, key, desc);
2357
+ else
2358
+ for (var i = decorators.length - 1; i >= 0; i--)
2359
+ if (d = decorators[i])
2360
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2361
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2362
+ }
2363
+ __name(_ts_decorate, "_ts_decorate");
2364
+ function _ts_metadata(k, v) {
2365
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
2366
+ return Reflect.metadata(k, v);
2367
+ }
2368
+ __name(_ts_metadata, "_ts_metadata");
2369
+ var BaseMessageInput = class {
2370
+ id;
2371
+ createdAt;
2372
+ };
2373
+ __name(BaseMessageInput, "BaseMessageInput");
2374
+ _ts_decorate([
2375
+ (0, import_type_graphql2.Field)(() => String),
2376
+ _ts_metadata("design:type", String)
2377
+ ], BaseMessageInput.prototype, "id", void 0);
2378
+ _ts_decorate([
2379
+ (0, import_type_graphql2.Field)(() => Date),
2380
+ _ts_metadata("design:type", typeof Date === "undefined" ? Object : Date)
2381
+ ], BaseMessageInput.prototype, "createdAt", void 0);
2382
+ BaseMessageInput = _ts_decorate([
2383
+ (0, import_type_graphql2.InputType)()
2384
+ ], BaseMessageInput);
2385
+
2386
+ // src/graphql/types/converted/index.ts
2387
+ var Message = class extends BaseMessageInput {
2388
+ type;
2389
+ isTextMessage() {
2390
+ return this.type === "TextMessage";
2391
+ }
2392
+ isActionExecutionMessage() {
2393
+ return this.type === "ActionExecutionMessage";
2394
+ }
2395
+ isResultMessage() {
2396
+ return this.type === "ResultMessage";
2397
+ }
2398
+ isAgentStateMessage() {
2399
+ return this.type === "AgentStateMessage";
2400
+ }
2401
+ };
2402
+ __name(Message, "Message");
2403
+ var TextMessage = class extends Message {
2404
+ type = "TextMessage";
2405
+ content;
2406
+ role;
2407
+ parentMessageId;
2408
+ };
2409
+ __name(TextMessage, "TextMessage");
2410
+ var ActionExecutionMessage = class extends Message {
2411
+ type = "ActionExecutionMessage";
2412
+ name;
2413
+ arguments;
2414
+ parentMessageId;
2415
+ };
2416
+ __name(ActionExecutionMessage, "ActionExecutionMessage");
2417
+ var ResultMessage = class extends Message {
2418
+ type = "ResultMessage";
2419
+ actionExecutionId;
2420
+ actionName;
2421
+ result;
2422
+ };
2423
+ __name(ResultMessage, "ResultMessage");
2424
+ var AgentStateMessage = class extends Message {
2425
+ type = "AgentStateMessage";
2426
+ threadId;
2427
+ agentName;
2428
+ nodeName;
2429
+ runId;
2430
+ active;
2431
+ role;
2432
+ state;
2433
+ running;
2434
+ };
2435
+ __name(AgentStateMessage, "AgentStateMessage");
2436
+
2437
+ // src/service-adapters/events.ts
2438
+ var import_class_transformer = require("class-transformer");
2439
+ var RuntimeEventTypes;
2440
+ (function(RuntimeEventTypes2) {
2441
+ RuntimeEventTypes2["TextMessageStart"] = "TextMessageStart";
2442
+ RuntimeEventTypes2["TextMessageContent"] = "TextMessageContent";
2443
+ RuntimeEventTypes2["TextMessageEnd"] = "TextMessageEnd";
2444
+ RuntimeEventTypes2["ActionExecutionStart"] = "ActionExecutionStart";
2445
+ RuntimeEventTypes2["ActionExecutionArgs"] = "ActionExecutionArgs";
2446
+ RuntimeEventTypes2["ActionExecutionEnd"] = "ActionExecutionEnd";
2447
+ RuntimeEventTypes2["ActionExecutionResult"] = "ActionExecutionResult";
2448
+ RuntimeEventTypes2["AgentStateMessage"] = "AgentStateMessage";
2449
+ })(RuntimeEventTypes || (RuntimeEventTypes = {}));
2450
+ var RuntimeEventSubject = class extends import_rxjs2.ReplaySubject {
2451
+ constructor() {
2452
+ super();
2453
+ }
2454
+ sendTextMessageStart({ messageId, parentMessageId }) {
2455
+ this.next({
2456
+ type: "TextMessageStart",
2457
+ messageId,
2458
+ parentMessageId
2459
+ });
2460
+ }
2461
+ sendTextMessageContent({ messageId, content }) {
2462
+ this.next({
2463
+ type: "TextMessageContent",
2464
+ content,
2465
+ messageId
2466
+ });
2467
+ }
2468
+ sendTextMessageEnd({ messageId }) {
2469
+ this.next({
2470
+ type: "TextMessageEnd",
2471
+ messageId
2472
+ });
2473
+ }
2474
+ sendTextMessage(messageId, content) {
2475
+ this.sendTextMessageStart({
2476
+ messageId
2477
+ });
2478
+ this.sendTextMessageContent({
2479
+ messageId,
2480
+ content
2481
+ });
2482
+ this.sendTextMessageEnd({
2483
+ messageId
2484
+ });
2485
+ }
2486
+ sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId }) {
2487
+ this.next({
2488
+ type: "ActionExecutionStart",
2489
+ actionExecutionId,
2490
+ actionName,
2491
+ parentMessageId
2492
+ });
2493
+ }
2494
+ sendActionExecutionArgs({ actionExecutionId, args }) {
2495
+ this.next({
2496
+ type: "ActionExecutionArgs",
2497
+ args,
2498
+ actionExecutionId
2499
+ });
2500
+ }
2501
+ sendActionExecutionEnd({ actionExecutionId }) {
2502
+ this.next({
2503
+ type: "ActionExecutionEnd",
2504
+ actionExecutionId
2505
+ });
2506
+ }
2507
+ sendActionExecution({ actionExecutionId, actionName, args, parentMessageId }) {
2508
+ this.sendActionExecutionStart({
2509
+ actionExecutionId,
2510
+ actionName,
2511
+ parentMessageId
2512
+ });
2513
+ this.sendActionExecutionArgs({
2514
+ actionExecutionId,
2515
+ args
2516
+ });
2517
+ this.sendActionExecutionEnd({
2518
+ actionExecutionId
2519
+ });
2520
+ }
2521
+ sendActionExecutionResult({ actionExecutionId, actionName, result }) {
2522
+ this.next({
2523
+ type: "ActionExecutionResult",
2524
+ actionName,
2525
+ actionExecutionId,
2526
+ result
2527
+ });
2528
+ }
2529
+ sendAgentStateMessage({ threadId, agentName, nodeName, runId, active, role, state, running }) {
2530
+ this.next({
2531
+ type: "AgentStateMessage",
2532
+ threadId,
2533
+ agentName,
2534
+ nodeName,
2535
+ runId,
2536
+ active,
2537
+ role,
2538
+ state,
2539
+ running
2540
+ });
2541
+ }
2542
+ };
2543
+ __name(RuntimeEventSubject, "RuntimeEventSubject");
2544
+ var RuntimeEventSource = class {
2545
+ eventStream$ = new RuntimeEventSubject();
2546
+ callback;
2547
+ async stream(callback) {
2548
+ this.callback = callback;
2549
+ }
2550
+ sendErrorMessageToChat(message = "An error occurred. Please try again.") {
2551
+ const errorMessage = `\u274C ${message}`;
2552
+ if (!this.callback) {
2553
+ this.stream(async (eventStream$) => {
2554
+ eventStream$.sendTextMessage((0, import_shared8.randomId)(), errorMessage);
2555
+ });
2556
+ } else {
2557
+ this.eventStream$.sendTextMessage((0, import_shared8.randomId)(), errorMessage);
2558
+ }
2559
+ }
2560
+ processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents }) {
2561
+ this.callback(this.eventStream$).catch((error) => {
2562
+ console.error("Error in event source callback", error);
2563
+ this.sendErrorMessageToChat();
2564
+ });
2565
+ return this.eventStream$.pipe(
2566
+ // track state
2567
+ (0, import_rxjs2.scan)((acc, event) => {
2568
+ acc = {
2569
+ ...acc
2570
+ };
2571
+ if (event.type === "ActionExecutionStart") {
2572
+ acc.callActionServerSide = serverSideActions.find((action) => action.name === event.actionName) !== void 0;
2573
+ acc.args = "";
2574
+ acc.actionExecutionId = event.actionExecutionId;
2575
+ if (acc.callActionServerSide) {
2576
+ acc.action = serverSideActions.find((action) => action.name === event.actionName);
2577
+ }
2578
+ acc.actionExecutionParentMessageId = event.parentMessageId;
2579
+ } else if (event.type === "ActionExecutionArgs") {
2580
+ acc.args += event.args;
2581
+ }
2582
+ acc.event = event;
2583
+ return acc;
2584
+ }, {
2585
+ event: null,
2586
+ callActionServerSide: false,
2587
+ args: "",
2588
+ actionExecutionId: null,
2589
+ action: null,
2590
+ actionExecutionParentMessageId: null
2591
+ }),
2592
+ (0, import_rxjs2.concatMap)((eventWithState) => {
2593
+ if (eventWithState.event.type === "ActionExecutionEnd" && eventWithState.callActionServerSide) {
2594
+ const toolCallEventStream$ = new RuntimeEventSubject();
2595
+ executeAction(toolCallEventStream$, guardrailsResult$ ? guardrailsResult$ : null, eventWithState.action, eventWithState.args, eventWithState.actionExecutionParentMessageId, eventWithState.actionExecutionId, actionInputsWithoutAgents).catch((error) => {
2596
+ console.error(error);
2597
+ });
2598
+ telemetry_client_default.capture("oss.runtime.server_action_executed", {});
2599
+ return (0, import_rxjs2.concat)((0, import_rxjs2.of)(eventWithState.event), toolCallEventStream$);
2600
+ } else {
2601
+ return (0, import_rxjs2.of)(eventWithState.event);
2602
+ }
2603
+ })
2604
+ );
2605
+ }
2606
+ };
2607
+ __name(RuntimeEventSource, "RuntimeEventSource");
2608
+ async function executeAction(eventStream$, guardrailsResult$, action, actionArguments, actionExecutionParentMessageId, actionExecutionId, actionInputsWithoutAgents) {
2609
+ var _a;
2610
+ if (guardrailsResult$) {
2611
+ const { status } = await (0, import_rxjs2.firstValueFrom)(guardrailsResult$);
2612
+ if (status === "denied") {
2613
+ eventStream$.complete();
2614
+ return;
2615
+ }
2616
+ }
2617
+ let args = [];
2618
+ if (actionArguments) {
2619
+ try {
2620
+ args = JSON.parse(actionArguments);
2621
+ } catch (e) {
2622
+ console.warn("Action argument unparsable", {
2623
+ actionArguments
2624
+ });
2625
+ }
2626
+ }
2627
+ if (isLangGraphAgentAction(action)) {
2628
+ const result = `${action.name} agent started`;
2629
+ const agentExecution = (0, import_class_transformer.plainToInstance)(ActionExecutionMessage, {
2630
+ id: actionExecutionId,
2631
+ createdAt: /* @__PURE__ */ new Date(),
2632
+ name: action.name,
2633
+ arguments: JSON.parse(actionArguments),
2634
+ parentMessageId: actionExecutionParentMessageId ?? actionExecutionId
2635
+ });
2636
+ const agentExecutionResult = (0, import_class_transformer.plainToInstance)(ResultMessage, {
2637
+ id: "result-" + actionExecutionId,
2638
+ createdAt: /* @__PURE__ */ new Date(),
2639
+ actionExecutionId,
2640
+ actionName: action.name,
2641
+ result
2642
+ });
2643
+ eventStream$.sendActionExecutionResult({
2644
+ actionExecutionId,
2645
+ actionName: action.name,
2646
+ result
2647
+ });
2648
+ const stream = await action.langGraphAgentHandler({
2649
+ name: action.name,
2650
+ actionInputsWithoutAgents,
2651
+ additionalMessages: [
2652
+ agentExecution,
2653
+ agentExecutionResult
2654
+ ]
2655
+ });
2656
+ (0, import_rxjs2.from)(stream).subscribe({
2657
+ next: (event) => eventStream$.next(event),
2658
+ error: (err) => console.error("Error in stream", err),
2659
+ complete: () => eventStream$.complete()
2660
+ });
2661
+ } else {
2662
+ const result = await ((_a = action.handler) == null ? void 0 : _a.call(action, args));
2663
+ await streamLangChainResponse({
2664
+ result,
2665
+ eventStream$,
2666
+ actionExecution: {
2667
+ name: action.name,
2668
+ id: actionExecutionId
2669
+ }
2670
+ });
2671
+ }
2672
+ }
2673
+ __name(executeAction, "executeAction");
2674
+
2675
+ // src/service-adapters/conversion.ts
2676
+ var import_class_transformer2 = require("class-transformer");
2677
+ function convertGqlInputToMessages(inputMessages) {
2678
+ const messages = [];
2679
+ for (const message of inputMessages) {
2680
+ if (message.textMessage) {
2681
+ messages.push((0, import_class_transformer2.plainToInstance)(TextMessage, {
2682
+ id: message.id,
2683
+ createdAt: message.createdAt,
2684
+ role: message.textMessage.role,
2685
+ content: message.textMessage.content,
2686
+ parentMessageId: message.textMessage.parentMessageId
2687
+ }));
2688
+ } else if (message.actionExecutionMessage) {
2689
+ messages.push((0, import_class_transformer2.plainToInstance)(ActionExecutionMessage, {
2690
+ id: message.id,
2691
+ createdAt: message.createdAt,
2692
+ name: message.actionExecutionMessage.name,
2693
+ arguments: JSON.parse(message.actionExecutionMessage.arguments),
2694
+ parentMessageId: message.actionExecutionMessage.parentMessageId
2695
+ }));
2696
+ } else if (message.resultMessage) {
2697
+ messages.push((0, import_class_transformer2.plainToInstance)(ResultMessage, {
2698
+ id: message.id,
2699
+ createdAt: message.createdAt,
2700
+ actionExecutionId: message.resultMessage.actionExecutionId,
2701
+ actionName: message.resultMessage.actionName,
2702
+ result: message.resultMessage.result
2703
+ }));
2704
+ } else if (message.agentStateMessage) {
2705
+ messages.push((0, import_class_transformer2.plainToInstance)(AgentStateMessage, {
2706
+ id: message.id,
2707
+ threadId: message.agentStateMessage.threadId,
2708
+ createdAt: message.createdAt,
2709
+ agentName: message.agentStateMessage.agentName,
2710
+ nodeName: message.agentStateMessage.nodeName,
2711
+ runId: message.agentStateMessage.runId,
2712
+ active: message.agentStateMessage.active,
2713
+ role: message.agentStateMessage.role,
2714
+ state: JSON.parse(message.agentStateMessage.state),
2715
+ running: message.agentStateMessage.running
2716
+ }));
2717
+ }
2718
+ }
2719
+ return messages;
2720
+ }
2721
+ __name(convertGqlInputToMessages, "convertGqlInputToMessages");
2722
+
2723
+ // src/lib/runtime/copilot-runtime.ts
2724
+ var import_rxjs3 = require("rxjs");
2725
+ var CopilotRuntime = class {
2726
+ actions;
2727
+ remoteEndpointDefinitions;
2728
+ langserve = [];
2729
+ onBeforeRequest;
2730
+ onAfterRequest;
2731
+ constructor(params) {
2732
+ var _a, _b;
2733
+ this.actions = (params == null ? void 0 : params.actions) || [];
2734
+ for (const chain of (params == null ? void 0 : params.langserve) || []) {
2735
+ const remoteChain = new RemoteChain(chain);
2736
+ this.langserve.push(remoteChain.toAction());
2737
+ }
2738
+ this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) ?? (params == null ? void 0 : params.remoteActions) ?? [];
2739
+ this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
2740
+ this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
2741
+ }
2742
+ async processRuntimeRequest(request) {
2743
+ var _a;
2744
+ const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, agentSession, url } = request;
2745
+ const eventSource = new RuntimeEventSource();
2746
+ try {
2747
+ if (agentSession) {
2748
+ return await this.processAgentRequest(request);
2749
+ }
2750
+ const messages = rawMessages.filter((message) => !message.agentStateMessage);
2751
+ const inputMessages = convertGqlInputToMessages(messages);
2752
+ const serverSideActions = await this.getServerSideActions(request);
2753
+ const serverSideActionsInput = serverSideActions.map((action) => ({
2754
+ name: action.name,
2755
+ description: action.description,
2756
+ jsonSchema: JSON.stringify((0, import_shared9.actionParametersToJsonSchema)(action.parameters))
2757
+ }));
2758
+ const actionInputs = flattenToolCallsNoDuplicates([
2759
+ ...serverSideActionsInput,
2760
+ ...clientSideActionsInput.filter(
2761
+ // Filter remote actions from CopilotKit core loop
2762
+ (action) => action.available !== ActionInputAvailability.remote
2763
+ )
2764
+ ]);
2765
+ await ((_a = this.onBeforeRequest) == null ? void 0 : _a.call(this, {
2766
+ threadId,
2767
+ runId,
2768
+ inputMessages,
2769
+ properties: graphqlContext.properties,
2770
+ url
2771
+ }));
2772
+ const result = await serviceAdapter.process({
2773
+ messages: inputMessages,
2774
+ actions: actionInputs,
2775
+ threadId,
2776
+ runId,
2777
+ eventSource,
2778
+ forwardedParameters
2779
+ });
2780
+ outputMessagesPromise.then((outputMessages) => {
2781
+ var _a2;
2782
+ (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
2783
+ threadId: result.threadId,
2784
+ runId: result.runId,
2785
+ inputMessages,
2786
+ outputMessages,
2787
+ properties: graphqlContext.properties,
2788
+ url
2789
+ });
2790
+ }).catch((_error) => {
2791
+ });
2792
+ return {
2793
+ threadId: result.threadId,
2794
+ runId: result.runId,
2795
+ eventSource,
2796
+ serverSideActions,
2797
+ actionInputsWithoutAgents: actionInputs.filter((action) => (
2798
+ // TODO-AGENTS: do not exclude ALL server side actions
2799
+ !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
2800
+ ))
2801
+ };
2802
+ } catch (error) {
2803
+ console.error("Error getting response:", error);
2804
+ eventSource.sendErrorMessageToChat();
2805
+ throw error;
2806
+ }
2807
+ }
2808
+ async discoverAgentsFromEndpoints(graphqlContext) {
2809
+ const headers = createHeaders(null, graphqlContext);
2810
+ const agents = this.remoteEndpointDefinitions.reduce(async (acc, endpoint) => {
2811
+ const agents2 = await acc;
2812
+ if (endpoint.type === EndpointType.LangGraphPlatform) {
2813
+ const response2 = await fetch(`${endpoint.deploymentUrl}/assistants/search`, {
2814
+ method: "POST",
2815
+ headers
2816
+ });
2817
+ const data2 = await response2.json();
2818
+ const endpointAgents2 = (data2 ?? []).map((entry) => ({
2819
+ name: entry.graph_id,
2820
+ id: entry.assistant_id
2821
+ }));
2822
+ return [
2823
+ ...agents2,
2824
+ ...endpointAgents2
2825
+ ];
2826
+ }
2827
+ const response = await fetch(`${endpoint.url}/info`, {
2828
+ method: "POST",
2829
+ headers,
2830
+ body: JSON.stringify({
2831
+ properties: graphqlContext.properties
2832
+ })
2833
+ });
2834
+ const data = await response.json();
2835
+ const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
2836
+ name: agent.name,
2837
+ description: agent.description,
2838
+ id: (0, import_shared9.randomId)()
2839
+ }));
2840
+ return [
2841
+ ...agents2,
2842
+ ...endpointAgents
2843
+ ];
2844
+ }, Promise.resolve([]));
2845
+ return agents;
2846
+ }
2847
+ async processAgentRequest(request) {
2848
+ var _a;
2849
+ const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession } = request;
2850
+ const { threadId, agentName, nodeName } = agentSession;
2851
+ const serverSideActions = await this.getServerSideActions(request);
2852
+ const messages = convertGqlInputToMessages(rawMessages);
2853
+ const agent = serverSideActions.find((action) => action.name === agentName && isLangGraphAgentAction(action));
2854
+ if (!agent) {
2855
+ throw new Error(`Agent ${agentName} not found`);
2856
+ }
2857
+ const serverSideActionsInput = serverSideActions.filter((action) => !isLangGraphAgentAction(action)).map((action) => ({
2858
+ name: action.name,
2859
+ description: action.description,
2860
+ jsonSchema: JSON.stringify((0, import_shared9.actionParametersToJsonSchema)(action.parameters))
2861
+ }));
2862
+ const actionInputsWithoutAgents = flattenToolCallsNoDuplicates([
2863
+ ...serverSideActionsInput,
2864
+ ...request.actions
2865
+ ]);
2866
+ await ((_a = this.onBeforeRequest) == null ? void 0 : _a.call(this, {
2867
+ threadId,
2868
+ runId: void 0,
2869
+ inputMessages: messages,
2870
+ properties: graphqlContext.properties
2871
+ }));
2872
+ try {
2873
+ const eventSource = new RuntimeEventSource();
2874
+ const stream = await agent.langGraphAgentHandler({
2875
+ name: agentName,
2876
+ threadId,
2877
+ nodeName,
2878
+ actionInputsWithoutAgents
2879
+ });
2880
+ eventSource.stream(async (eventStream$) => {
2881
+ (0, import_rxjs3.from)(stream).subscribe({
2882
+ next: (event) => eventStream$.next(event),
2883
+ error: (err) => console.error("Error in stream", err),
2884
+ complete: () => eventStream$.complete()
2885
+ });
2886
+ });
2887
+ outputMessagesPromise.then((outputMessages) => {
2888
+ var _a2;
2889
+ (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
2890
+ threadId,
2891
+ runId: void 0,
2892
+ inputMessages: messages,
2893
+ outputMessages,
2894
+ properties: graphqlContext.properties
2895
+ });
2896
+ }).catch((_error) => {
2897
+ });
2898
+ return {
2899
+ threadId,
2900
+ runId: void 0,
2901
+ eventSource,
2902
+ serverSideActions: [],
2903
+ actionInputsWithoutAgents
2904
+ };
2905
+ } catch (error) {
2906
+ console.error("Error getting response:", error);
2907
+ throw error;
2908
+ }
2909
+ }
2910
+ async getServerSideActions(request) {
2911
+ const { messages: rawMessages, graphqlContext, agentStates, url } = request;
2912
+ const inputMessages = convertGqlInputToMessages(rawMessages);
2913
+ const langserveFunctions = [];
2914
+ for (const chainPromise of this.langserve) {
2915
+ try {
2916
+ const chain = await chainPromise;
2917
+ langserveFunctions.push(chain);
2918
+ } catch (error) {
2919
+ console.error("Error loading langserve chain:", error);
2920
+ }
2921
+ }
2922
+ const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
2923
+ ...endpoint,
2924
+ type: resolveEndpointType(endpoint)
2925
+ }));
2926
+ const remoteActions = await setupRemoteActions({
2927
+ remoteEndpointDefinitions,
2928
+ graphqlContext,
2929
+ messages: inputMessages,
2930
+ agentStates,
2931
+ frontendUrl: url
2932
+ });
2933
+ const configuredActions = typeof this.actions === "function" ? this.actions({
2934
+ properties: graphqlContext.properties,
2935
+ url
2936
+ }) : this.actions;
2937
+ return [
2938
+ ...configuredActions,
2939
+ ...langserveFunctions,
2940
+ ...remoteActions
2941
+ ];
2942
+ }
2943
+ };
2944
+ __name(CopilotRuntime, "CopilotRuntime");
2945
+ function flattenToolCallsNoDuplicates(toolsByPriority) {
2946
+ let allTools = [];
2947
+ const allToolNames = [];
2948
+ for (const tool of toolsByPriority) {
2949
+ if (!allToolNames.includes(tool.name)) {
2950
+ allTools.push(tool);
2951
+ allToolNames.push(tool.name);
2952
+ }
2953
+ }
2954
+ return allTools;
2955
+ }
2956
+ __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
2957
+ function copilotKitEndpoint(config2) {
2958
+ return {
2959
+ ...config2,
2960
+ type: EndpointType.CopilotKit
2961
+ };
2962
+ }
2963
+ __name(copilotKitEndpoint, "copilotKitEndpoint");
2964
+ function langGraphPlatformEndpoint(config2) {
2965
+ return {
2966
+ ...config2,
2967
+ type: EndpointType.LangGraphPlatform
2968
+ };
2969
+ }
2970
+ __name(langGraphPlatformEndpoint, "langGraphPlatformEndpoint");
2971
+ function resolveEndpointType(endpoint) {
2972
+ if (!endpoint.type) {
2973
+ if ("langsmithApiKey" in endpoint && "deploymentUrl" in endpoint && "agents" in endpoint) {
2974
+ return EndpointType.LangGraphPlatform;
2975
+ } else {
2976
+ return EndpointType.CopilotKit;
2977
+ }
2978
+ }
2979
+ return endpoint.type;
2980
+ }
2981
+ __name(resolveEndpointType, "resolveEndpointType");
2982
+
2983
+ // src/lib/integrations/shared.ts
2984
+ var import_type_graphql17 = require("type-graphql");
2985
+
2986
+ // src/graphql/resolvers/copilot.resolver.ts
2987
+ var import_type_graphql16 = require("type-graphql");
2988
+ var import_rxjs4 = require("rxjs");
2989
+
2990
+ // src/graphql/inputs/generate-copilot-response.input.ts
2991
+ var import_type_graphql11 = require("type-graphql");
2992
+
2993
+ // src/graphql/inputs/message.input.ts
2994
+ var import_type_graphql3 = require("type-graphql");
2995
+ function _ts_decorate2(decorators, target, key, desc) {
2996
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2997
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2998
+ r = Reflect.decorate(decorators, target, key, desc);
2999
+ else
3000
+ for (var i = decorators.length - 1; i >= 0; i--)
3001
+ if (d = decorators[i])
3002
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3003
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3004
+ }
3005
+ __name(_ts_decorate2, "_ts_decorate");
3006
+ function _ts_metadata2(k, v) {
3007
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3008
+ return Reflect.metadata(k, v);
3009
+ }
3010
+ __name(_ts_metadata2, "_ts_metadata");
3011
+ var MessageInput = class extends BaseMessageInput {
3012
+ textMessage;
3013
+ actionExecutionMessage;
3014
+ resultMessage;
3015
+ agentStateMessage;
3016
+ };
3017
+ __name(MessageInput, "MessageInput");
3018
+ _ts_decorate2([
3019
+ (0, import_type_graphql3.Field)(() => TextMessageInput, {
3020
+ nullable: true
3021
+ }),
3022
+ _ts_metadata2("design:type", typeof TextMessageInput === "undefined" ? Object : TextMessageInput)
3023
+ ], MessageInput.prototype, "textMessage", void 0);
3024
+ _ts_decorate2([
3025
+ (0, import_type_graphql3.Field)(() => ActionExecutionMessageInput, {
3026
+ nullable: true
3027
+ }),
3028
+ _ts_metadata2("design:type", typeof ActionExecutionMessageInput === "undefined" ? Object : ActionExecutionMessageInput)
3029
+ ], MessageInput.prototype, "actionExecutionMessage", void 0);
3030
+ _ts_decorate2([
3031
+ (0, import_type_graphql3.Field)(() => ResultMessageInput, {
3032
+ nullable: true
3033
+ }),
3034
+ _ts_metadata2("design:type", typeof ResultMessageInput === "undefined" ? Object : ResultMessageInput)
3035
+ ], MessageInput.prototype, "resultMessage", void 0);
3036
+ _ts_decorate2([
3037
+ (0, import_type_graphql3.Field)(() => AgentStateMessageInput, {
3038
+ nullable: true
3039
+ }),
3040
+ _ts_metadata2("design:type", typeof AgentStateMessageInput === "undefined" ? Object : AgentStateMessageInput)
3041
+ ], MessageInput.prototype, "agentStateMessage", void 0);
3042
+ MessageInput = _ts_decorate2([
3043
+ (0, import_type_graphql3.InputType)()
3044
+ ], MessageInput);
3045
+ var TextMessageInput = class {
3046
+ content;
3047
+ parentMessageId;
3048
+ role;
3049
+ };
3050
+ __name(TextMessageInput, "TextMessageInput");
3051
+ _ts_decorate2([
3052
+ (0, import_type_graphql3.Field)(() => String),
3053
+ _ts_metadata2("design:type", String)
3054
+ ], TextMessageInput.prototype, "content", void 0);
3055
+ _ts_decorate2([
3056
+ (0, import_type_graphql3.Field)(() => String, {
3057
+ nullable: true
3058
+ }),
3059
+ _ts_metadata2("design:type", String)
3060
+ ], TextMessageInput.prototype, "parentMessageId", void 0);
3061
+ _ts_decorate2([
3062
+ (0, import_type_graphql3.Field)(() => MessageRole),
3063
+ _ts_metadata2("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
3064
+ ], TextMessageInput.prototype, "role", void 0);
3065
+ TextMessageInput = _ts_decorate2([
3066
+ (0, import_type_graphql3.InputType)()
3067
+ ], TextMessageInput);
3068
+ var ActionExecutionMessageInput = class {
3069
+ name;
3070
+ arguments;
3071
+ parentMessageId;
3072
+ scope;
3073
+ };
3074
+ __name(ActionExecutionMessageInput, "ActionExecutionMessageInput");
3075
+ _ts_decorate2([
3076
+ (0, import_type_graphql3.Field)(() => String),
3077
+ _ts_metadata2("design:type", String)
3078
+ ], ActionExecutionMessageInput.prototype, "name", void 0);
3079
+ _ts_decorate2([
3080
+ (0, import_type_graphql3.Field)(() => String),
3081
+ _ts_metadata2("design:type", String)
3082
+ ], ActionExecutionMessageInput.prototype, "arguments", void 0);
3083
+ _ts_decorate2([
3084
+ (0, import_type_graphql3.Field)(() => String, {
3085
+ nullable: true
3086
+ }),
3087
+ _ts_metadata2("design:type", String)
3088
+ ], ActionExecutionMessageInput.prototype, "parentMessageId", void 0);
3089
+ _ts_decorate2([
3090
+ (0, import_type_graphql3.Field)(() => String, {
3091
+ nullable: true,
3092
+ deprecationReason: "This field will be removed in a future version"
3093
+ }),
3094
+ _ts_metadata2("design:type", typeof String === "undefined" ? Object : String)
3095
+ ], ActionExecutionMessageInput.prototype, "scope", void 0);
3096
+ ActionExecutionMessageInput = _ts_decorate2([
3097
+ (0, import_type_graphql3.InputType)()
3098
+ ], ActionExecutionMessageInput);
3099
+ var ResultMessageInput = class {
3100
+ actionExecutionId;
3101
+ actionName;
3102
+ parentMessageId;
3103
+ result;
3104
+ };
3105
+ __name(ResultMessageInput, "ResultMessageInput");
3106
+ _ts_decorate2([
3107
+ (0, import_type_graphql3.Field)(() => String),
3108
+ _ts_metadata2("design:type", String)
3109
+ ], ResultMessageInput.prototype, "actionExecutionId", void 0);
3110
+ _ts_decorate2([
3111
+ (0, import_type_graphql3.Field)(() => String),
3112
+ _ts_metadata2("design:type", String)
3113
+ ], ResultMessageInput.prototype, "actionName", void 0);
3114
+ _ts_decorate2([
3115
+ (0, import_type_graphql3.Field)(() => String, {
3116
+ nullable: true
3117
+ }),
3118
+ _ts_metadata2("design:type", String)
3119
+ ], ResultMessageInput.prototype, "parentMessageId", void 0);
3120
+ _ts_decorate2([
3121
+ (0, import_type_graphql3.Field)(() => String),
3122
+ _ts_metadata2("design:type", String)
3123
+ ], ResultMessageInput.prototype, "result", void 0);
3124
+ ResultMessageInput = _ts_decorate2([
3125
+ (0, import_type_graphql3.InputType)()
3126
+ ], ResultMessageInput);
3127
+ var AgentStateMessageInput = class {
3128
+ threadId;
3129
+ agentName;
3130
+ role;
3131
+ state;
3132
+ running;
3133
+ nodeName;
3134
+ runId;
3135
+ active;
3136
+ };
3137
+ __name(AgentStateMessageInput, "AgentStateMessageInput");
3138
+ _ts_decorate2([
3139
+ (0, import_type_graphql3.Field)(() => String),
3140
+ _ts_metadata2("design:type", String)
3141
+ ], AgentStateMessageInput.prototype, "threadId", void 0);
3142
+ _ts_decorate2([
3143
+ (0, import_type_graphql3.Field)(() => String),
3144
+ _ts_metadata2("design:type", String)
3145
+ ], AgentStateMessageInput.prototype, "agentName", void 0);
3146
+ _ts_decorate2([
3147
+ (0, import_type_graphql3.Field)(() => MessageRole),
3148
+ _ts_metadata2("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
3149
+ ], AgentStateMessageInput.prototype, "role", void 0);
3150
+ _ts_decorate2([
3151
+ (0, import_type_graphql3.Field)(() => String),
3152
+ _ts_metadata2("design:type", String)
3153
+ ], AgentStateMessageInput.prototype, "state", void 0);
3154
+ _ts_decorate2([
3155
+ (0, import_type_graphql3.Field)(() => Boolean),
3156
+ _ts_metadata2("design:type", Boolean)
3157
+ ], AgentStateMessageInput.prototype, "running", void 0);
3158
+ _ts_decorate2([
3159
+ (0, import_type_graphql3.Field)(() => String),
3160
+ _ts_metadata2("design:type", String)
3161
+ ], AgentStateMessageInput.prototype, "nodeName", void 0);
3162
+ _ts_decorate2([
3163
+ (0, import_type_graphql3.Field)(() => String),
3164
+ _ts_metadata2("design:type", String)
3165
+ ], AgentStateMessageInput.prototype, "runId", void 0);
3166
+ _ts_decorate2([
3167
+ (0, import_type_graphql3.Field)(() => Boolean),
3168
+ _ts_metadata2("design:type", Boolean)
3169
+ ], AgentStateMessageInput.prototype, "active", void 0);
3170
+ AgentStateMessageInput = _ts_decorate2([
3171
+ (0, import_type_graphql3.InputType)()
3172
+ ], AgentStateMessageInput);
3173
+
3174
+ // src/graphql/inputs/frontend.input.ts
3175
+ var import_type_graphql5 = require("type-graphql");
3176
+
3177
+ // src/graphql/inputs/action.input.ts
3178
+ var import_type_graphql4 = require("type-graphql");
3179
+ function _ts_decorate3(decorators, target, key, desc) {
3180
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3181
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3182
+ r = Reflect.decorate(decorators, target, key, desc);
3183
+ else
3184
+ for (var i = decorators.length - 1; i >= 0; i--)
3185
+ if (d = decorators[i])
3186
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3187
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3188
+ }
3189
+ __name(_ts_decorate3, "_ts_decorate");
3190
+ function _ts_metadata3(k, v) {
3191
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3192
+ return Reflect.metadata(k, v);
3193
+ }
3194
+ __name(_ts_metadata3, "_ts_metadata");
3195
+ var ActionInput = class {
3196
+ name;
3197
+ description;
3198
+ jsonSchema;
3199
+ available;
3200
+ };
3201
+ __name(ActionInput, "ActionInput");
3202
+ _ts_decorate3([
3203
+ (0, import_type_graphql4.Field)(() => String),
3204
+ _ts_metadata3("design:type", String)
3205
+ ], ActionInput.prototype, "name", void 0);
3206
+ _ts_decorate3([
3207
+ (0, import_type_graphql4.Field)(() => String),
3208
+ _ts_metadata3("design:type", String)
3209
+ ], ActionInput.prototype, "description", void 0);
3210
+ _ts_decorate3([
3211
+ (0, import_type_graphql4.Field)(() => String),
3212
+ _ts_metadata3("design:type", String)
3213
+ ], ActionInput.prototype, "jsonSchema", void 0);
3214
+ _ts_decorate3([
3215
+ (0, import_type_graphql4.Field)(() => ActionInputAvailability, {
3216
+ nullable: true
3217
+ }),
3218
+ _ts_metadata3("design:type", typeof ActionInputAvailability === "undefined" ? Object : ActionInputAvailability)
3219
+ ], ActionInput.prototype, "available", void 0);
3220
+ ActionInput = _ts_decorate3([
3221
+ (0, import_type_graphql4.InputType)()
3222
+ ], ActionInput);
3223
+
3224
+ // src/graphql/inputs/frontend.input.ts
3225
+ function _ts_decorate4(decorators, target, key, desc) {
3226
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3227
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3228
+ r = Reflect.decorate(decorators, target, key, desc);
3229
+ else
3230
+ for (var i = decorators.length - 1; i >= 0; i--)
3231
+ if (d = decorators[i])
3232
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3233
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3234
+ }
3235
+ __name(_ts_decorate4, "_ts_decorate");
3236
+ function _ts_metadata4(k, v) {
3237
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3238
+ return Reflect.metadata(k, v);
3239
+ }
3240
+ __name(_ts_metadata4, "_ts_metadata");
3241
+ var FrontendInput = class {
3242
+ toDeprecate_fullContext;
3243
+ actions;
3244
+ url;
3245
+ };
3246
+ __name(FrontendInput, "FrontendInput");
3247
+ _ts_decorate4([
3248
+ (0, import_type_graphql5.Field)(() => String, {
3249
+ nullable: true
3250
+ }),
3251
+ _ts_metadata4("design:type", String)
3252
+ ], FrontendInput.prototype, "toDeprecate_fullContext", void 0);
3253
+ _ts_decorate4([
3254
+ (0, import_type_graphql5.Field)(() => [
3255
+ ActionInput
3256
+ ]),
3257
+ _ts_metadata4("design:type", Array)
3258
+ ], FrontendInput.prototype, "actions", void 0);
3259
+ _ts_decorate4([
3260
+ (0, import_type_graphql5.Field)(() => String, {
3261
+ nullable: true
3262
+ }),
3263
+ _ts_metadata4("design:type", String)
3264
+ ], FrontendInput.prototype, "url", void 0);
3265
+ FrontendInput = _ts_decorate4([
3266
+ (0, import_type_graphql5.InputType)()
3267
+ ], FrontendInput);
3268
+
3269
+ // src/graphql/inputs/cloud.input.ts
3270
+ var import_type_graphql7 = require("type-graphql");
3271
+
3272
+ // src/graphql/inputs/cloud-guardrails.input.ts
3273
+ var import_type_graphql6 = require("type-graphql");
3274
+ function _ts_decorate5(decorators, target, key, desc) {
3275
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3276
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3277
+ r = Reflect.decorate(decorators, target, key, desc);
3278
+ else
3279
+ for (var i = decorators.length - 1; i >= 0; i--)
3280
+ if (d = decorators[i])
3281
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3282
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3283
+ }
3284
+ __name(_ts_decorate5, "_ts_decorate");
3285
+ function _ts_metadata5(k, v) {
3286
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3287
+ return Reflect.metadata(k, v);
3288
+ }
3289
+ __name(_ts_metadata5, "_ts_metadata");
3290
+ var GuardrailsRuleInput = class {
3291
+ allowList = [];
3292
+ denyList = [];
3293
+ };
3294
+ __name(GuardrailsRuleInput, "GuardrailsRuleInput");
3295
+ _ts_decorate5([
3296
+ (0, import_type_graphql6.Field)(() => [
3297
+ String
3298
+ ], {
3299
+ nullable: true
3300
+ }),
3301
+ _ts_metadata5("design:type", Array)
3302
+ ], GuardrailsRuleInput.prototype, "allowList", void 0);
3303
+ _ts_decorate5([
3304
+ (0, import_type_graphql6.Field)(() => [
3305
+ String
3306
+ ], {
3307
+ nullable: true
3308
+ }),
3309
+ _ts_metadata5("design:type", Array)
3310
+ ], GuardrailsRuleInput.prototype, "denyList", void 0);
3311
+ GuardrailsRuleInput = _ts_decorate5([
3312
+ (0, import_type_graphql6.InputType)()
3313
+ ], GuardrailsRuleInput);
3314
+ var GuardrailsInput = class {
3315
+ inputValidationRules;
3316
+ };
3317
+ __name(GuardrailsInput, "GuardrailsInput");
3318
+ _ts_decorate5([
3319
+ (0, import_type_graphql6.Field)(() => GuardrailsRuleInput, {
3320
+ nullable: false
3321
+ }),
3322
+ _ts_metadata5("design:type", typeof GuardrailsRuleInput === "undefined" ? Object : GuardrailsRuleInput)
3323
+ ], GuardrailsInput.prototype, "inputValidationRules", void 0);
3324
+ GuardrailsInput = _ts_decorate5([
3325
+ (0, import_type_graphql6.InputType)()
3326
+ ], GuardrailsInput);
3327
+
3328
+ // src/graphql/inputs/cloud.input.ts
3329
+ function _ts_decorate6(decorators, target, key, desc) {
3330
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3331
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3332
+ r = Reflect.decorate(decorators, target, key, desc);
3333
+ else
3334
+ for (var i = decorators.length - 1; i >= 0; i--)
3335
+ if (d = decorators[i])
3336
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3337
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3338
+ }
3339
+ __name(_ts_decorate6, "_ts_decorate");
3340
+ function _ts_metadata6(k, v) {
3341
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3342
+ return Reflect.metadata(k, v);
3343
+ }
3344
+ __name(_ts_metadata6, "_ts_metadata");
3345
+ var CloudInput = class {
3346
+ guardrails;
3347
+ };
3348
+ __name(CloudInput, "CloudInput");
3349
+ _ts_decorate6([
3350
+ (0, import_type_graphql7.Field)(() => GuardrailsInput, {
3351
+ nullable: true
3352
+ }),
3353
+ _ts_metadata6("design:type", typeof GuardrailsInput === "undefined" ? Object : GuardrailsInput)
3354
+ ], CloudInput.prototype, "guardrails", void 0);
3355
+ CloudInput = _ts_decorate6([
3356
+ (0, import_type_graphql7.InputType)()
3357
+ ], CloudInput);
3358
+
3359
+ // src/graphql/inputs/forwarded-parameters.input.ts
3360
+ var import_type_graphql8 = require("type-graphql");
3361
+ function _ts_decorate7(decorators, target, key, desc) {
3362
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3363
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3364
+ r = Reflect.decorate(decorators, target, key, desc);
3365
+ else
3366
+ for (var i = decorators.length - 1; i >= 0; i--)
3367
+ if (d = decorators[i])
3368
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3369
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3370
+ }
3371
+ __name(_ts_decorate7, "_ts_decorate");
3372
+ function _ts_metadata7(k, v) {
3373
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3374
+ return Reflect.metadata(k, v);
3375
+ }
3376
+ __name(_ts_metadata7, "_ts_metadata");
3377
+ var ForwardedParametersInput = class {
3378
+ model;
3379
+ maxTokens;
3380
+ stop;
3381
+ toolChoice;
3382
+ toolChoiceFunctionName;
3383
+ temperature;
3384
+ };
3385
+ __name(ForwardedParametersInput, "ForwardedParametersInput");
3386
+ _ts_decorate7([
3387
+ (0, import_type_graphql8.Field)(() => String, {
3388
+ nullable: true
3389
+ }),
3390
+ _ts_metadata7("design:type", String)
3391
+ ], ForwardedParametersInput.prototype, "model", void 0);
3392
+ _ts_decorate7([
3393
+ (0, import_type_graphql8.Field)(() => Number, {
3394
+ nullable: true
3395
+ }),
3396
+ _ts_metadata7("design:type", Number)
3397
+ ], ForwardedParametersInput.prototype, "maxTokens", void 0);
3398
+ _ts_decorate7([
3399
+ (0, import_type_graphql8.Field)(() => [
3400
+ String
3401
+ ], {
3402
+ nullable: true
3403
+ }),
3404
+ _ts_metadata7("design:type", Array)
3405
+ ], ForwardedParametersInput.prototype, "stop", void 0);
3406
+ _ts_decorate7([
3407
+ (0, import_type_graphql8.Field)(() => String, {
3408
+ nullable: true
3409
+ }),
3410
+ _ts_metadata7("design:type", typeof String === "undefined" ? Object : String)
3411
+ ], ForwardedParametersInput.prototype, "toolChoice", void 0);
3412
+ _ts_decorate7([
3413
+ (0, import_type_graphql8.Field)(() => String, {
3414
+ nullable: true
3415
+ }),
3416
+ _ts_metadata7("design:type", String)
3417
+ ], ForwardedParametersInput.prototype, "toolChoiceFunctionName", void 0);
3418
+ _ts_decorate7([
3419
+ (0, import_type_graphql8.Field)(() => Number, {
3420
+ nullable: true
3421
+ }),
3422
+ _ts_metadata7("design:type", Number)
3423
+ ], ForwardedParametersInput.prototype, "temperature", void 0);
3424
+ ForwardedParametersInput = _ts_decorate7([
3425
+ (0, import_type_graphql8.InputType)()
3426
+ ], ForwardedParametersInput);
3427
+
3428
+ // src/graphql/inputs/agent-session.input.ts
3429
+ var import_type_graphql9 = require("type-graphql");
3430
+ function _ts_decorate8(decorators, target, key, desc) {
3431
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3432
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3433
+ r = Reflect.decorate(decorators, target, key, desc);
3434
+ else
3435
+ for (var i = decorators.length - 1; i >= 0; i--)
3436
+ if (d = decorators[i])
3437
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3438
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3439
+ }
3440
+ __name(_ts_decorate8, "_ts_decorate");
3441
+ function _ts_metadata8(k, v) {
3442
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3443
+ return Reflect.metadata(k, v);
3444
+ }
3445
+ __name(_ts_metadata8, "_ts_metadata");
3446
+ var AgentSessionInput = class {
3447
+ agentName;
3448
+ threadId;
3449
+ nodeName;
3450
+ };
3451
+ __name(AgentSessionInput, "AgentSessionInput");
3452
+ _ts_decorate8([
3453
+ (0, import_type_graphql9.Field)(() => String),
3454
+ _ts_metadata8("design:type", String)
3455
+ ], AgentSessionInput.prototype, "agentName", void 0);
3456
+ _ts_decorate8([
3457
+ (0, import_type_graphql9.Field)(() => String, {
3458
+ nullable: true
3459
+ }),
3460
+ _ts_metadata8("design:type", String)
3461
+ ], AgentSessionInput.prototype, "threadId", void 0);
3462
+ _ts_decorate8([
3463
+ (0, import_type_graphql9.Field)(() => String, {
3464
+ nullable: true
3465
+ }),
3466
+ _ts_metadata8("design:type", String)
3467
+ ], AgentSessionInput.prototype, "nodeName", void 0);
3468
+ AgentSessionInput = _ts_decorate8([
3469
+ (0, import_type_graphql9.InputType)()
3470
+ ], AgentSessionInput);
3471
+
3472
+ // src/graphql/inputs/agent-state.input.ts
3473
+ var import_type_graphql10 = require("type-graphql");
3474
+ function _ts_decorate9(decorators, target, key, desc) {
3475
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3476
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3477
+ r = Reflect.decorate(decorators, target, key, desc);
3478
+ else
3479
+ for (var i = decorators.length - 1; i >= 0; i--)
3480
+ if (d = decorators[i])
3481
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3482
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3483
+ }
3484
+ __name(_ts_decorate9, "_ts_decorate");
3485
+ function _ts_metadata9(k, v) {
3486
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3487
+ return Reflect.metadata(k, v);
3488
+ }
3489
+ __name(_ts_metadata9, "_ts_metadata");
3490
+ var AgentStateInput = class {
3491
+ agentName;
3492
+ state;
3493
+ };
3494
+ __name(AgentStateInput, "AgentStateInput");
3495
+ _ts_decorate9([
3496
+ (0, import_type_graphql10.Field)(() => String),
3497
+ _ts_metadata9("design:type", String)
3498
+ ], AgentStateInput.prototype, "agentName", void 0);
3499
+ _ts_decorate9([
3500
+ (0, import_type_graphql10.Field)(() => String),
3501
+ _ts_metadata9("design:type", String)
3502
+ ], AgentStateInput.prototype, "state", void 0);
3503
+ AgentStateInput = _ts_decorate9([
3504
+ (0, import_type_graphql10.InputType)()
3505
+ ], AgentStateInput);
3506
+
3507
+ // src/graphql/inputs/generate-copilot-response.input.ts
3508
+ function _ts_decorate10(decorators, target, key, desc) {
3509
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3510
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3511
+ r = Reflect.decorate(decorators, target, key, desc);
3512
+ else
3513
+ for (var i = decorators.length - 1; i >= 0; i--)
3514
+ if (d = decorators[i])
3515
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3516
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3517
+ }
3518
+ __name(_ts_decorate10, "_ts_decorate");
3519
+ function _ts_metadata10(k, v) {
3520
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3521
+ return Reflect.metadata(k, v);
3522
+ }
3523
+ __name(_ts_metadata10, "_ts_metadata");
3524
+ var GenerateCopilotResponseMetadataInput = class {
3525
+ requestType;
3526
+ };
3527
+ __name(GenerateCopilotResponseMetadataInput, "GenerateCopilotResponseMetadataInput");
3528
+ _ts_decorate10([
3529
+ (0, import_type_graphql11.Field)(() => CopilotRequestType, {
3530
+ nullable: true
3531
+ }),
3532
+ _ts_metadata10("design:type", typeof CopilotRequestType === "undefined" ? Object : CopilotRequestType)
3533
+ ], GenerateCopilotResponseMetadataInput.prototype, "requestType", void 0);
3534
+ GenerateCopilotResponseMetadataInput = _ts_decorate10([
3535
+ (0, import_type_graphql11.InputType)()
3536
+ ], GenerateCopilotResponseMetadataInput);
3537
+ var GenerateCopilotResponseInput = class {
3538
+ metadata;
3539
+ threadId;
3540
+ runId;
3541
+ messages;
3542
+ frontend;
3543
+ cloud;
3544
+ forwardedParameters;
3545
+ agentSession;
3546
+ agentState;
3547
+ agentStates;
3548
+ };
3549
+ __name(GenerateCopilotResponseInput, "GenerateCopilotResponseInput");
3550
+ _ts_decorate10([
3551
+ (0, import_type_graphql11.Field)(() => GenerateCopilotResponseMetadataInput, {
3552
+ nullable: false
3553
+ }),
3554
+ _ts_metadata10("design:type", typeof GenerateCopilotResponseMetadataInput === "undefined" ? Object : GenerateCopilotResponseMetadataInput)
3555
+ ], GenerateCopilotResponseInput.prototype, "metadata", void 0);
3556
+ _ts_decorate10([
3557
+ (0, import_type_graphql11.Field)(() => String, {
3558
+ nullable: true
3559
+ }),
3560
+ _ts_metadata10("design:type", String)
3561
+ ], GenerateCopilotResponseInput.prototype, "threadId", void 0);
3562
+ _ts_decorate10([
3563
+ (0, import_type_graphql11.Field)(() => String, {
3564
+ nullable: true
3565
+ }),
3566
+ _ts_metadata10("design:type", String)
3567
+ ], GenerateCopilotResponseInput.prototype, "runId", void 0);
3568
+ _ts_decorate10([
3569
+ (0, import_type_graphql11.Field)(() => [
3570
+ MessageInput
3571
+ ]),
3572
+ _ts_metadata10("design:type", Array)
3573
+ ], GenerateCopilotResponseInput.prototype, "messages", void 0);
3574
+ _ts_decorate10([
3575
+ (0, import_type_graphql11.Field)(() => FrontendInput),
3576
+ _ts_metadata10("design:type", typeof FrontendInput === "undefined" ? Object : FrontendInput)
3577
+ ], GenerateCopilotResponseInput.prototype, "frontend", void 0);
3578
+ _ts_decorate10([
3579
+ (0, import_type_graphql11.Field)(() => CloudInput, {
3580
+ nullable: true
3581
+ }),
3582
+ _ts_metadata10("design:type", typeof CloudInput === "undefined" ? Object : CloudInput)
3583
+ ], GenerateCopilotResponseInput.prototype, "cloud", void 0);
3584
+ _ts_decorate10([
3585
+ (0, import_type_graphql11.Field)(() => ForwardedParametersInput, {
3586
+ nullable: true
3587
+ }),
3588
+ _ts_metadata10("design:type", typeof ForwardedParametersInput === "undefined" ? Object : ForwardedParametersInput)
3589
+ ], GenerateCopilotResponseInput.prototype, "forwardedParameters", void 0);
3590
+ _ts_decorate10([
3591
+ (0, import_type_graphql11.Field)(() => AgentSessionInput, {
3592
+ nullable: true
3593
+ }),
3594
+ _ts_metadata10("design:type", typeof AgentSessionInput === "undefined" ? Object : AgentSessionInput)
3595
+ ], GenerateCopilotResponseInput.prototype, "agentSession", void 0);
3596
+ _ts_decorate10([
3597
+ (0, import_type_graphql11.Field)(() => AgentStateInput, {
3598
+ nullable: true
3599
+ }),
3600
+ _ts_metadata10("design:type", typeof AgentStateInput === "undefined" ? Object : AgentStateInput)
3601
+ ], GenerateCopilotResponseInput.prototype, "agentState", void 0);
3602
+ _ts_decorate10([
3603
+ (0, import_type_graphql11.Field)(() => [
3604
+ AgentStateInput
3605
+ ], {
3606
+ nullable: true
3607
+ }),
3608
+ _ts_metadata10("design:type", Array)
3609
+ ], GenerateCopilotResponseInput.prototype, "agentStates", void 0);
3610
+ GenerateCopilotResponseInput = _ts_decorate10([
3611
+ (0, import_type_graphql11.InputType)()
3612
+ ], GenerateCopilotResponseInput);
3613
+
3614
+ // src/graphql/types/copilot-response.type.ts
3615
+ var import_type_graphql14 = require("type-graphql");
3616
+
3617
+ // src/graphql/types/message-status.type.ts
3618
+ var import_type_graphql12 = require("type-graphql");
3619
+ function _ts_decorate11(decorators, target, key, desc) {
3620
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3621
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3622
+ r = Reflect.decorate(decorators, target, key, desc);
3623
+ else
3624
+ for (var i = decorators.length - 1; i >= 0; i--)
3625
+ if (d = decorators[i])
3626
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3627
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3628
+ }
3629
+ __name(_ts_decorate11, "_ts_decorate");
3630
+ function _ts_metadata11(k, v) {
3631
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3632
+ return Reflect.metadata(k, v);
3633
+ }
3634
+ __name(_ts_metadata11, "_ts_metadata");
3635
+ var MessageStatusCode;
3636
+ (function(MessageStatusCode2) {
3637
+ MessageStatusCode2["Pending"] = "pending";
3638
+ MessageStatusCode2["Success"] = "success";
3639
+ MessageStatusCode2["Failed"] = "failed";
3640
+ })(MessageStatusCode || (MessageStatusCode = {}));
3641
+ (0, import_type_graphql12.registerEnumType)(MessageStatusCode, {
3642
+ name: "MessageStatusCode"
3643
+ });
3644
+ var BaseMessageStatus = /* @__PURE__ */ __name(class BaseMessageStatus2 {
3645
+ code;
3646
+ }, "BaseMessageStatus");
3647
+ _ts_decorate11([
3648
+ (0, import_type_graphql12.Field)(() => MessageStatusCode),
3649
+ _ts_metadata11("design:type", String)
3650
+ ], BaseMessageStatus.prototype, "code", void 0);
3651
+ BaseMessageStatus = _ts_decorate11([
3652
+ (0, import_type_graphql12.ObjectType)()
3653
+ ], BaseMessageStatus);
3654
+ var PendingMessageStatus = class extends BaseMessageStatus {
3655
+ code = "pending";
3656
+ };
3657
+ __name(PendingMessageStatus, "PendingMessageStatus");
3658
+ PendingMessageStatus = _ts_decorate11([
3659
+ (0, import_type_graphql12.ObjectType)()
3660
+ ], PendingMessageStatus);
3661
+ var SuccessMessageStatus = class extends BaseMessageStatus {
3662
+ code = "success";
3663
+ };
3664
+ __name(SuccessMessageStatus, "SuccessMessageStatus");
3665
+ SuccessMessageStatus = _ts_decorate11([
3666
+ (0, import_type_graphql12.ObjectType)()
3667
+ ], SuccessMessageStatus);
3668
+ var FailedMessageStatus = class extends BaseMessageStatus {
3669
+ code = "failed";
3670
+ reason;
3671
+ };
3672
+ __name(FailedMessageStatus, "FailedMessageStatus");
3673
+ _ts_decorate11([
3674
+ (0, import_type_graphql12.Field)(() => String),
3675
+ _ts_metadata11("design:type", String)
3676
+ ], FailedMessageStatus.prototype, "reason", void 0);
3677
+ FailedMessageStatus = _ts_decorate11([
3678
+ (0, import_type_graphql12.ObjectType)()
3679
+ ], FailedMessageStatus);
3680
+ var MessageStatusUnion = (0, import_type_graphql12.createUnionType)({
3681
+ name: "MessageStatus",
3682
+ types: () => [
3683
+ PendingMessageStatus,
3684
+ SuccessMessageStatus,
3685
+ FailedMessageStatus
3686
+ ]
3687
+ });
3688
+
3689
+ // src/graphql/types/response-status.type.ts
3690
+ var import_graphql_scalars = require("graphql-scalars");
3691
+ var import_type_graphql13 = require("type-graphql");
3692
+ function _ts_decorate12(decorators, target, key, desc) {
3693
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3694
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3695
+ r = Reflect.decorate(decorators, target, key, desc);
3696
+ else
3697
+ for (var i = decorators.length - 1; i >= 0; i--)
3698
+ if (d = decorators[i])
3699
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3700
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3701
+ }
3702
+ __name(_ts_decorate12, "_ts_decorate");
3703
+ function _ts_metadata12(k, v) {
3704
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3705
+ return Reflect.metadata(k, v);
3706
+ }
3707
+ __name(_ts_metadata12, "_ts_metadata");
3708
+ var ResponseStatusCode;
3709
+ (function(ResponseStatusCode2) {
3710
+ ResponseStatusCode2["Pending"] = "pending";
3711
+ ResponseStatusCode2["Success"] = "success";
3712
+ ResponseStatusCode2["Failed"] = "failed";
3713
+ })(ResponseStatusCode || (ResponseStatusCode = {}));
3714
+ (0, import_type_graphql13.registerEnumType)(ResponseStatusCode, {
3715
+ name: "ResponseStatusCode"
3716
+ });
3717
+ var BaseResponseStatus = /* @__PURE__ */ __name(class BaseResponseStatus2 {
3718
+ code;
3719
+ }, "BaseResponseStatus");
3720
+ _ts_decorate12([
3721
+ (0, import_type_graphql13.Field)(() => ResponseStatusCode),
3722
+ _ts_metadata12("design:type", String)
3723
+ ], BaseResponseStatus.prototype, "code", void 0);
3724
+ BaseResponseStatus = _ts_decorate12([
3725
+ (0, import_type_graphql13.InterfaceType)({
3726
+ resolveType(value) {
3727
+ if (value.code === "success") {
3728
+ return SuccessResponseStatus;
3729
+ } else if (value.code === "failed") {
3730
+ return FailedResponseStatus;
3731
+ } else if (value.code === "pending") {
3732
+ return PendingResponseStatus;
3733
+ }
3734
+ return void 0;
3735
+ }
3736
+ }),
3737
+ (0, import_type_graphql13.ObjectType)()
3738
+ ], BaseResponseStatus);
3739
+ var PendingResponseStatus = class extends BaseResponseStatus {
3740
+ code = "pending";
3741
+ };
3742
+ __name(PendingResponseStatus, "PendingResponseStatus");
3743
+ PendingResponseStatus = _ts_decorate12([
3744
+ (0, import_type_graphql13.ObjectType)({
3745
+ implements: BaseResponseStatus
3746
+ })
3747
+ ], PendingResponseStatus);
3748
+ var SuccessResponseStatus = class extends BaseResponseStatus {
3749
+ code = "success";
3750
+ };
3751
+ __name(SuccessResponseStatus, "SuccessResponseStatus");
3752
+ SuccessResponseStatus = _ts_decorate12([
3753
+ (0, import_type_graphql13.ObjectType)({
3754
+ implements: BaseResponseStatus
3755
+ })
3756
+ ], SuccessResponseStatus);
3757
+ var FailedResponseStatusReason;
3758
+ (function(FailedResponseStatusReason2) {
3759
+ FailedResponseStatusReason2["GUARDRAILS_VALIDATION_FAILED"] = "GUARDRAILS_VALIDATION_FAILED";
3760
+ FailedResponseStatusReason2["MESSAGE_STREAM_INTERRUPTED"] = "MESSAGE_STREAM_INTERRUPTED";
3761
+ FailedResponseStatusReason2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
3762
+ })(FailedResponseStatusReason || (FailedResponseStatusReason = {}));
3763
+ (0, import_type_graphql13.registerEnumType)(FailedResponseStatusReason, {
3764
+ name: "FailedResponseStatusReason"
3765
+ });
3766
+ var FailedResponseStatus = class extends BaseResponseStatus {
3767
+ code = "failed";
3768
+ reason;
3769
+ details = null;
3770
+ };
3771
+ __name(FailedResponseStatus, "FailedResponseStatus");
3772
+ _ts_decorate12([
3773
+ (0, import_type_graphql13.Field)(() => FailedResponseStatusReason),
3774
+ _ts_metadata12("design:type", String)
3775
+ ], FailedResponseStatus.prototype, "reason", void 0);
3776
+ _ts_decorate12([
3777
+ (0, import_type_graphql13.Field)(() => import_graphql_scalars.GraphQLJSON, {
3778
+ nullable: true
3779
+ }),
3780
+ _ts_metadata12("design:type", typeof Record === "undefined" ? Object : Record)
3781
+ ], FailedResponseStatus.prototype, "details", void 0);
3782
+ FailedResponseStatus = _ts_decorate12([
3783
+ (0, import_type_graphql13.ObjectType)({
3784
+ implements: BaseResponseStatus
3785
+ })
3786
+ ], FailedResponseStatus);
3787
+ var ResponseStatusUnion = (0, import_type_graphql13.createUnionType)({
3788
+ name: "ResponseStatus",
3789
+ types: () => [
3790
+ PendingResponseStatus,
3791
+ SuccessResponseStatus,
3792
+ FailedResponseStatus
3793
+ ]
3794
+ });
3795
+
3796
+ // src/graphql/types/copilot-response.type.ts
3797
+ function _ts_decorate13(decorators, target, key, desc) {
3798
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3799
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3800
+ r = Reflect.decorate(decorators, target, key, desc);
3801
+ else
3802
+ for (var i = decorators.length - 1; i >= 0; i--)
3803
+ if (d = decorators[i])
3804
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3805
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3806
+ }
3807
+ __name(_ts_decorate13, "_ts_decorate");
3808
+ function _ts_metadata13(k, v) {
3809
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
3810
+ return Reflect.metadata(k, v);
3811
+ }
3812
+ __name(_ts_metadata13, "_ts_metadata");
3813
+ var BaseMessageOutput = /* @__PURE__ */ __name(class BaseMessageOutput2 {
3814
+ id;
3815
+ createdAt;
3816
+ status;
3817
+ }, "BaseMessageOutput");
3818
+ _ts_decorate13([
3819
+ (0, import_type_graphql14.Field)(() => String),
3820
+ _ts_metadata13("design:type", String)
3821
+ ], BaseMessageOutput.prototype, "id", void 0);
3822
+ _ts_decorate13([
3823
+ (0, import_type_graphql14.Field)(() => Date),
3824
+ _ts_metadata13("design:type", typeof Date === "undefined" ? Object : Date)
3825
+ ], BaseMessageOutput.prototype, "createdAt", void 0);
3826
+ _ts_decorate13([
3827
+ (0, import_type_graphql14.Field)(() => MessageStatusUnion),
3828
+ _ts_metadata13("design:type", Object)
3829
+ ], BaseMessageOutput.prototype, "status", void 0);
3830
+ BaseMessageOutput = _ts_decorate13([
3831
+ (0, import_type_graphql14.InterfaceType)({
3832
+ resolveType(value) {
3833
+ if (value.hasOwnProperty("content")) {
3834
+ return TextMessageOutput;
3835
+ } else if (value.hasOwnProperty("name")) {
3836
+ return ActionExecutionMessageOutput;
3837
+ } else if (value.hasOwnProperty("result")) {
3838
+ return ResultMessageOutput;
3839
+ } else if (value.hasOwnProperty("state")) {
3840
+ return AgentStateMessageOutput;
3841
+ }
3842
+ return void 0;
3843
+ }
3844
+ })
3845
+ ], BaseMessageOutput);
3846
+ var TextMessageOutput = class {
3847
+ role;
3848
+ content;
3849
+ parentMessageId;
3850
+ };
3851
+ __name(TextMessageOutput, "TextMessageOutput");
3852
+ _ts_decorate13([
3853
+ (0, import_type_graphql14.Field)(() => MessageRole),
3854
+ _ts_metadata13("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
3855
+ ], TextMessageOutput.prototype, "role", void 0);
3856
+ _ts_decorate13([
3857
+ (0, import_type_graphql14.Field)(() => [
3858
+ String
3859
+ ]),
3860
+ _ts_metadata13("design:type", Array)
3861
+ ], TextMessageOutput.prototype, "content", void 0);
3862
+ _ts_decorate13([
3863
+ (0, import_type_graphql14.Field)(() => String, {
3864
+ nullable: true
3865
+ }),
3866
+ _ts_metadata13("design:type", String)
3867
+ ], TextMessageOutput.prototype, "parentMessageId", void 0);
3868
+ TextMessageOutput = _ts_decorate13([
3869
+ (0, import_type_graphql14.ObjectType)({
3870
+ implements: BaseMessageOutput
3871
+ })
3872
+ ], TextMessageOutput);
3873
+ var ActionExecutionMessageOutput = class {
3874
+ name;
3875
+ scope;
3876
+ arguments;
3877
+ parentMessageId;
3878
+ };
3879
+ __name(ActionExecutionMessageOutput, "ActionExecutionMessageOutput");
3880
+ _ts_decorate13([
3881
+ (0, import_type_graphql14.Field)(() => String),
3882
+ _ts_metadata13("design:type", String)
3883
+ ], ActionExecutionMessageOutput.prototype, "name", void 0);
3884
+ _ts_decorate13([
3885
+ (0, import_type_graphql14.Field)(() => String, {
3886
+ nullable: true,
3887
+ deprecationReason: "This field will be removed in a future version"
3888
+ }),
3889
+ _ts_metadata13("design:type", String)
3890
+ ], ActionExecutionMessageOutput.prototype, "scope", void 0);
3891
+ _ts_decorate13([
3892
+ (0, import_type_graphql14.Field)(() => [
3893
+ String
3894
+ ]),
3895
+ _ts_metadata13("design:type", Array)
3896
+ ], ActionExecutionMessageOutput.prototype, "arguments", void 0);
3897
+ _ts_decorate13([
3898
+ (0, import_type_graphql14.Field)(() => String, {
3899
+ nullable: true
3900
+ }),
3901
+ _ts_metadata13("design:type", String)
3902
+ ], ActionExecutionMessageOutput.prototype, "parentMessageId", void 0);
3903
+ ActionExecutionMessageOutput = _ts_decorate13([
3904
+ (0, import_type_graphql14.ObjectType)({
3905
+ implements: BaseMessageOutput
3906
+ })
3907
+ ], ActionExecutionMessageOutput);
3908
+ var ResultMessageOutput = class {
3909
+ actionExecutionId;
3910
+ actionName;
3911
+ result;
3912
+ };
3913
+ __name(ResultMessageOutput, "ResultMessageOutput");
3914
+ _ts_decorate13([
3915
+ (0, import_type_graphql14.Field)(() => String),
3916
+ _ts_metadata13("design:type", String)
3917
+ ], ResultMessageOutput.prototype, "actionExecutionId", void 0);
3918
+ _ts_decorate13([
3919
+ (0, import_type_graphql14.Field)(() => String),
3920
+ _ts_metadata13("design:type", String)
3921
+ ], ResultMessageOutput.prototype, "actionName", void 0);
3922
+ _ts_decorate13([
3923
+ (0, import_type_graphql14.Field)(() => String),
3924
+ _ts_metadata13("design:type", String)
3925
+ ], ResultMessageOutput.prototype, "result", void 0);
3926
+ ResultMessageOutput = _ts_decorate13([
3927
+ (0, import_type_graphql14.ObjectType)({
3928
+ implements: BaseMessageOutput
3929
+ })
3930
+ ], ResultMessageOutput);
3931
+ var AgentStateMessageOutput = class {
3932
+ threadId;
3933
+ agentName;
3934
+ nodeName;
3935
+ runId;
3936
+ active;
3937
+ role;
3938
+ state;
3939
+ running;
3940
+ };
3941
+ __name(AgentStateMessageOutput, "AgentStateMessageOutput");
3942
+ _ts_decorate13([
3943
+ (0, import_type_graphql14.Field)(() => String),
3944
+ _ts_metadata13("design:type", String)
3945
+ ], AgentStateMessageOutput.prototype, "threadId", void 0);
3946
+ _ts_decorate13([
3947
+ (0, import_type_graphql14.Field)(() => String),
3948
+ _ts_metadata13("design:type", String)
3949
+ ], AgentStateMessageOutput.prototype, "agentName", void 0);
3950
+ _ts_decorate13([
3951
+ (0, import_type_graphql14.Field)(() => String),
3952
+ _ts_metadata13("design:type", String)
3953
+ ], AgentStateMessageOutput.prototype, "nodeName", void 0);
3954
+ _ts_decorate13([
3955
+ (0, import_type_graphql14.Field)(() => String),
3956
+ _ts_metadata13("design:type", String)
3957
+ ], AgentStateMessageOutput.prototype, "runId", void 0);
3958
+ _ts_decorate13([
3959
+ (0, import_type_graphql14.Field)(() => Boolean),
3960
+ _ts_metadata13("design:type", Boolean)
3961
+ ], AgentStateMessageOutput.prototype, "active", void 0);
3962
+ _ts_decorate13([
3963
+ (0, import_type_graphql14.Field)(() => MessageRole),
3964
+ _ts_metadata13("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
3965
+ ], AgentStateMessageOutput.prototype, "role", void 0);
3966
+ _ts_decorate13([
3967
+ (0, import_type_graphql14.Field)(() => String),
3968
+ _ts_metadata13("design:type", String)
3969
+ ], AgentStateMessageOutput.prototype, "state", void 0);
3970
+ _ts_decorate13([
3971
+ (0, import_type_graphql14.Field)(() => Boolean),
3972
+ _ts_metadata13("design:type", Boolean)
3973
+ ], AgentStateMessageOutput.prototype, "running", void 0);
3974
+ AgentStateMessageOutput = _ts_decorate13([
3975
+ (0, import_type_graphql14.ObjectType)({
3976
+ implements: BaseMessageOutput
3977
+ })
3978
+ ], AgentStateMessageOutput);
3979
+ var CopilotResponse = class {
3980
+ threadId;
3981
+ status;
3982
+ runId;
3983
+ messages;
3984
+ };
3985
+ __name(CopilotResponse, "CopilotResponse");
3986
+ _ts_decorate13([
3987
+ (0, import_type_graphql14.Field)(() => String),
3988
+ _ts_metadata13("design:type", String)
3989
+ ], CopilotResponse.prototype, "threadId", void 0);
3990
+ _ts_decorate13([
3991
+ (0, import_type_graphql14.Field)(() => ResponseStatusUnion),
3992
+ _ts_metadata13("design:type", Object)
3993
+ ], CopilotResponse.prototype, "status", void 0);
3994
+ _ts_decorate13([
3995
+ (0, import_type_graphql14.Field)({
3996
+ nullable: true
3997
+ }),
3998
+ _ts_metadata13("design:type", String)
3999
+ ], CopilotResponse.prototype, "runId", void 0);
4000
+ _ts_decorate13([
4001
+ (0, import_type_graphql14.Field)(() => [
4002
+ BaseMessageOutput
4003
+ ]),
4004
+ _ts_metadata13("design:type", Array)
4005
+ ], CopilotResponse.prototype, "messages", void 0);
4006
+ CopilotResponse = _ts_decorate13([
4007
+ (0, import_type_graphql14.ObjectType)()
4008
+ ], CopilotResponse);
4009
+
4010
+ // src/graphql/resolvers/copilot.resolver.ts
4011
+ var import_graphql_yoga = require("graphql-yoga");
4012
+ var import_graphql_scalars2 = require("graphql-scalars");
4013
+ var import_class_transformer3 = require("class-transformer");
4014
+ var import_graphql = require("graphql");
4015
+
4016
+ // src/utils/failed-response-status-reasons.ts
4017
+ var GuardrailsValidationFailureResponse = class extends FailedResponseStatus {
4018
+ reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;
4019
+ constructor({ guardrailsReason }) {
4020
+ super();
4021
+ this.details = {
4022
+ guardrailsReason
4023
+ };
4024
+ }
4025
+ };
4026
+ __name(GuardrailsValidationFailureResponse, "GuardrailsValidationFailureResponse");
4027
+ var MessageStreamInterruptedResponse = class extends FailedResponseStatus {
4028
+ reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;
4029
+ constructor({ messageId }) {
4030
+ super();
4031
+ this.details = {
4032
+ messageId,
4033
+ description: "Check the message for mode details"
4034
+ };
4035
+ }
4036
+ };
4037
+ __name(MessageStreamInterruptedResponse, "MessageStreamInterruptedResponse");
4038
+ var UnknownErrorResponse = class extends FailedResponseStatus {
4039
+ reason = FailedResponseStatusReason.UNKNOWN_ERROR;
4040
+ constructor({ description }) {
4041
+ super();
4042
+ this.details = {
4043
+ description
4044
+ };
4045
+ }
4046
+ };
4047
+ __name(UnknownErrorResponse, "UnknownErrorResponse");
4048
+
4049
+ // src/graphql/resolvers/copilot.resolver.ts
4050
+ var import_shared10 = require("@copilotkit/shared");
4051
+
4052
+ // src/graphql/types/agents-response.type.ts
4053
+ var import_type_graphql15 = require("type-graphql");
4054
+ function _ts_decorate14(decorators, target, key, desc) {
4055
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4056
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
4057
+ r = Reflect.decorate(decorators, target, key, desc);
4058
+ else
4059
+ for (var i = decorators.length - 1; i >= 0; i--)
4060
+ if (d = decorators[i])
4061
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4062
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
4063
+ }
4064
+ __name(_ts_decorate14, "_ts_decorate");
4065
+ function _ts_metadata14(k, v) {
4066
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
4067
+ return Reflect.metadata(k, v);
4068
+ }
4069
+ __name(_ts_metadata14, "_ts_metadata");
4070
+ var Agent = class {
4071
+ id;
4072
+ name;
4073
+ description;
4074
+ };
4075
+ __name(Agent, "Agent");
4076
+ _ts_decorate14([
4077
+ (0, import_type_graphql15.Field)(() => String),
4078
+ _ts_metadata14("design:type", String)
4079
+ ], Agent.prototype, "id", void 0);
4080
+ _ts_decorate14([
4081
+ (0, import_type_graphql15.Field)(() => String),
4082
+ _ts_metadata14("design:type", String)
4083
+ ], Agent.prototype, "name", void 0);
4084
+ _ts_decorate14([
4085
+ (0, import_type_graphql15.Field)(() => String),
4086
+ _ts_metadata14("design:type", String)
4087
+ ], Agent.prototype, "description", void 0);
4088
+ Agent = _ts_decorate14([
4089
+ (0, import_type_graphql15.ObjectType)()
4090
+ ], Agent);
4091
+ var AgentsResponse = class {
4092
+ agents;
4093
+ };
4094
+ __name(AgentsResponse, "AgentsResponse");
4095
+ _ts_decorate14([
4096
+ (0, import_type_graphql15.Field)(() => [
4097
+ Agent
4098
+ ]),
4099
+ _ts_metadata14("design:type", Array)
4100
+ ], AgentsResponse.prototype, "agents", void 0);
4101
+ AgentsResponse = _ts_decorate14([
4102
+ (0, import_type_graphql15.ObjectType)()
4103
+ ], AgentsResponse);
4104
+
4105
+ // src/graphql/resolvers/copilot.resolver.ts
4106
+ function _ts_decorate15(decorators, target, key, desc) {
4107
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4108
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
4109
+ r = Reflect.decorate(decorators, target, key, desc);
4110
+ else
4111
+ for (var i = decorators.length - 1; i >= 0; i--)
4112
+ if (d = decorators[i])
4113
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4114
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
4115
+ }
4116
+ __name(_ts_decorate15, "_ts_decorate");
4117
+ function _ts_metadata15(k, v) {
4118
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
4119
+ return Reflect.metadata(k, v);
4120
+ }
4121
+ __name(_ts_metadata15, "_ts_metadata");
4122
+ function _ts_param(paramIndex, decorator) {
4123
+ return function(target, key) {
4124
+ decorator(target, key, paramIndex);
4125
+ };
4126
+ }
4127
+ __name(_ts_param, "_ts_param");
4128
+ var invokeGuardrails = /* @__PURE__ */ __name(async ({ baseUrl, copilotCloudPublicApiKey, data, onResult, onError }) => {
4129
+ var _a;
4130
+ if (data.messages.length && ((_a = data.messages[data.messages.length - 1].textMessage) == null ? void 0 : _a.role) === MessageRole.user) {
4131
+ const messages = data.messages.filter((m) => m.textMessage !== void 0 && (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant)).map((m) => ({
4132
+ role: m.textMessage.role,
4133
+ content: m.textMessage.content
4134
+ }));
4135
+ const lastMessage = messages[messages.length - 1];
4136
+ const restOfMessages = messages.slice(0, -1);
4137
+ const body = {
4138
+ input: lastMessage.content,
4139
+ validTopics: data.cloud.guardrails.inputValidationRules.allowList,
4140
+ invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,
4141
+ messages: restOfMessages
4142
+ };
4143
+ const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {
4144
+ method: "POST",
4145
+ headers: {
4146
+ "Content-Type": "application/json",
4147
+ "X-CopilotCloud-Public-API-Key": copilotCloudPublicApiKey
4148
+ },
4149
+ body: JSON.stringify(body)
4150
+ });
4151
+ if (guardrailsResult.ok) {
4152
+ const resultJson = await guardrailsResult.json();
4153
+ onResult(resultJson);
4154
+ } else {
4155
+ onError(await guardrailsResult.json());
4156
+ }
4157
+ }
4158
+ }, "invokeGuardrails");
4159
+ var CopilotResolver = class {
4160
+ async hello() {
4161
+ return "Hello World";
4162
+ }
4163
+ async availableAgents(ctx) {
4164
+ let logger2 = ctx.logger.child({
4165
+ component: "CopilotResolver.availableAgents"
4166
+ });
4167
+ logger2.debug("Processing");
4168
+ const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
4169
+ logger2.debug("Event source created, creating response");
4170
+ return {
4171
+ agents
4172
+ };
4173
+ }
4174
+ async generateCopilotResponse(ctx, data, properties) {
4175
+ var _a, _b, _c;
4176
+ telemetry_client_default.capture("oss.runtime.copilot_request_created", {
4177
+ "cloud.guardrails.enabled": ((_a = data.cloud) == null ? void 0 : _a.guardrails) !== void 0,
4178
+ requestType: data.metadata.requestType
4179
+ });
4180
+ let logger2 = ctx.logger.child({
4181
+ component: "CopilotResolver.generateCopilotResponse"
4182
+ });
4183
+ logger2.debug({
4184
+ data
4185
+ }, "Generating Copilot response");
4186
+ if (properties) {
4187
+ logger2.debug("Properties provided, merging with context properties");
4188
+ ctx.properties = {
4189
+ ...ctx.properties,
4190
+ ...properties
4191
+ };
4192
+ }
4193
+ const copilotRuntime = ctx._copilotkit.runtime;
4194
+ const serviceAdapter = ctx._copilotkit.serviceAdapter;
4195
+ let copilotCloudPublicApiKey = null;
4196
+ let copilotCloudBaseUrl;
4197
+ if (data.cloud) {
4198
+ logger2 = logger2.child({
4199
+ cloud: true
4200
+ });
4201
+ logger2.debug("Cloud configuration provided, checking for public API key in headers");
4202
+ const key = ctx.request.headers.get("x-copilotcloud-public-api-key");
4203
+ if (key) {
4204
+ logger2.debug("Public API key found in headers");
4205
+ copilotCloudPublicApiKey = key;
4206
+ } else {
4207
+ logger2.error("Public API key not found in headers");
4208
+ throw new import_graphql.GraphQLError("X-CopilotCloud-Public-API-Key header is required");
4209
+ }
4210
+ if (process.env.COPILOT_CLOUD_BASE_URL) {
4211
+ copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;
4212
+ } else if ((_b = ctx._copilotkit.cloud) == null ? void 0 : _b.baseUrl) {
4213
+ copilotCloudBaseUrl = (_c = ctx._copilotkit.cloud) == null ? void 0 : _c.baseUrl;
4214
+ } else {
4215
+ copilotCloudBaseUrl = "https://api.cloud.copilotkit.ai";
4216
+ }
4217
+ logger2 = logger2.child({
4218
+ copilotCloudBaseUrl
4219
+ });
4220
+ }
4221
+ logger2.debug("Setting up subjects");
4222
+ const responseStatus$ = new import_rxjs4.ReplaySubject();
4223
+ const interruptStreaming$ = new import_rxjs4.ReplaySubject();
4224
+ const guardrailsResult$ = new import_rxjs4.ReplaySubject();
4225
+ let outputMessages = [];
4226
+ let resolveOutputMessagesPromise;
4227
+ let rejectOutputMessagesPromise;
4228
+ const outputMessagesPromise = new Promise((resolve, reject) => {
4229
+ resolveOutputMessagesPromise = resolve;
4230
+ rejectOutputMessagesPromise = reject;
4231
+ });
4232
+ logger2.debug("Processing");
4233
+ const { eventSource, threadId = (0, import_shared10.randomId)(), runId, serverSideActions, actionInputsWithoutAgents } = await copilotRuntime.processRuntimeRequest({
4234
+ serviceAdapter,
4235
+ messages: data.messages,
4236
+ actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
4237
+ threadId: data.threadId,
4238
+ runId: data.runId,
4239
+ publicApiKey: void 0,
4240
+ outputMessagesPromise,
4241
+ graphqlContext: ctx,
4242
+ forwardedParameters: data.forwardedParameters,
4243
+ agentSession: data.agentSession,
4244
+ agentStates: data.agentStates,
4245
+ url: data.frontend.url
4246
+ });
4247
+ logger2.debug("Event source created, creating response");
4248
+ const response = {
4249
+ threadId,
4250
+ runId,
4251
+ status: (0, import_rxjs4.firstValueFrom)(responseStatus$),
4252
+ messages: new import_graphql_yoga.Repeater(async (pushMessage, stopStreamingMessages) => {
4253
+ var _a2, _b2;
4254
+ logger2.debug("Messages repeater created");
4255
+ if ((_a2 = data.cloud) == null ? void 0 : _a2.guardrails) {
4256
+ logger2 = logger2.child({
4257
+ guardrails: true
4258
+ });
4259
+ logger2.debug("Guardrails is enabled, validating input");
4260
+ invokeGuardrails({
4261
+ baseUrl: copilotCloudBaseUrl,
4262
+ copilotCloudPublicApiKey,
4263
+ data,
4264
+ onResult: (result) => {
4265
+ logger2.debug({
4266
+ status: result.status
4267
+ }, "Guardrails validation done");
4268
+ guardrailsResult$.next(result);
4269
+ if (result.status === "denied") {
4270
+ responseStatus$.next(new GuardrailsValidationFailureResponse({
4271
+ guardrailsReason: result.reason
4272
+ }));
4273
+ interruptStreaming$.next({
4274
+ reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`
4275
+ });
4276
+ outputMessages = [
4277
+ (0, import_class_transformer3.plainToInstance)(TextMessage, {
4278
+ id: (0, import_shared10.randomId)(),
4279
+ createdAt: /* @__PURE__ */ new Date(),
4280
+ content: result.reason,
4281
+ role: MessageRole.assistant
4282
+ })
4283
+ ];
4284
+ resolveOutputMessagesPromise(outputMessages);
4285
+ }
4286
+ },
4287
+ onError: (err) => {
4288
+ logger2.error({
4289
+ err
4290
+ }, "Error in guardrails validation");
4291
+ responseStatus$.next(new UnknownErrorResponse({
4292
+ description: `An unknown error has occurred in the guardrails validation`
4293
+ }));
4294
+ interruptStreaming$.next({
4295
+ reason: `Interrupted due to unknown error in guardrails validation`
4296
+ });
4297
+ rejectOutputMessagesPromise(err);
4298
+ }
4299
+ });
4300
+ }
4301
+ let eventStreamSubscription;
4302
+ const eventStream = eventSource.processRuntimeEvents({
4303
+ serverSideActions,
4304
+ guardrailsResult$: ((_b2 = data.cloud) == null ? void 0 : _b2.guardrails) ? guardrailsResult$ : null,
4305
+ actionInputsWithoutAgents: actionInputsWithoutAgents.filter(
4306
+ // TODO-AGENTS: do not exclude ALL server side actions
4307
+ (action) => !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
4308
+ )
4309
+ }).pipe(
4310
+ // shareReplay() ensures that later subscribers will see the whole stream instead of
4311
+ // just the events that were emitted after the subscriber was added.
4312
+ (0, import_rxjs4.shareReplay)(),
4313
+ (0, import_rxjs4.finalize)(() => {
4314
+ logger2.debug("Event stream finalized");
4315
+ })
4316
+ );
4317
+ logger2.debug("Event stream created, subscribing to event stream");
4318
+ eventStreamSubscription = eventStream.subscribe({
4319
+ next: async (event) => {
4320
+ switch (event.type) {
4321
+ case RuntimeEventTypes.TextMessageStart:
4322
+ const textMessageContentStream = eventStream.pipe(
4323
+ // skip until this message start event
4324
+ (0, import_rxjs4.skipWhile)((e) => e !== event),
4325
+ // take until the message end event
4326
+ (0, import_rxjs4.takeWhile)((e) => !(e.type === RuntimeEventTypes.TextMessageEnd && e.messageId == event.messageId)),
4327
+ // filter out any other message events or message ids
4328
+ (0, import_rxjs4.filter)((e) => e.type == RuntimeEventTypes.TextMessageContent && e.messageId == event.messageId)
4329
+ );
4330
+ const streamingTextStatus = new import_rxjs4.Subject();
4331
+ const messageId = event.messageId;
4332
+ pushMessage({
4333
+ id: messageId,
4334
+ parentMessageId: event.parentMessageId,
4335
+ status: (0, import_rxjs4.firstValueFrom)(streamingTextStatus),
4336
+ createdAt: /* @__PURE__ */ new Date(),
4337
+ role: MessageRole.assistant,
4338
+ content: new import_graphql_yoga.Repeater(async (pushTextChunk, stopStreamingText) => {
4339
+ logger2.debug("Text message content repeater created");
4340
+ const textChunks = [];
4341
+ let textSubscription;
4342
+ interruptStreaming$.pipe((0, import_rxjs4.shareReplay)(), (0, import_rxjs4.take)(1), (0, import_rxjs4.tap)(({ reason, messageId: messageId2 }) => {
4343
+ logger2.debug({
4344
+ reason,
4345
+ messageId: messageId2
4346
+ }, "Text streaming interrupted");
4347
+ streamingTextStatus.next((0, import_class_transformer3.plainToInstance)(FailedMessageStatus, {
4348
+ reason
4349
+ }));
4350
+ responseStatus$.next(new MessageStreamInterruptedResponse({
4351
+ messageId: messageId2
4352
+ }));
4353
+ stopStreamingText();
4354
+ textSubscription == null ? void 0 : textSubscription.unsubscribe();
4355
+ })).subscribe();
4356
+ logger2.debug("Subscribing to text message content stream");
4357
+ textSubscription = textMessageContentStream.subscribe({
4358
+ next: async (e) => {
4359
+ if (e.type == RuntimeEventTypes.TextMessageContent) {
4360
+ await pushTextChunk(e.content);
4361
+ textChunks.push(e.content);
4362
+ }
4363
+ },
4364
+ error: (err) => {
4365
+ logger2.error({
4366
+ err
4367
+ }, "Error in text message content stream");
4368
+ interruptStreaming$.next({
4369
+ reason: "Error streaming message content",
4370
+ messageId
4371
+ });
4372
+ stopStreamingText();
4373
+ textSubscription == null ? void 0 : textSubscription.unsubscribe();
4374
+ },
4375
+ complete: () => {
4376
+ logger2.debug("Text message content stream completed");
4377
+ streamingTextStatus.next(new SuccessMessageStatus());
4378
+ stopStreamingText();
4379
+ textSubscription == null ? void 0 : textSubscription.unsubscribe();
4380
+ outputMessages.push((0, import_class_transformer3.plainToInstance)(TextMessage, {
4381
+ id: messageId,
4382
+ createdAt: /* @__PURE__ */ new Date(),
4383
+ content: textChunks.join(""),
4384
+ role: MessageRole.assistant
4385
+ }));
4386
+ }
4387
+ });
4388
+ })
4389
+ });
4390
+ break;
4391
+ case RuntimeEventTypes.ActionExecutionStart:
4392
+ logger2.debug("Action execution start event received");
4393
+ const actionExecutionArgumentStream = eventStream.pipe(
4394
+ (0, import_rxjs4.skipWhile)((e) => e !== event),
4395
+ // take until the action execution end event
4396
+ (0, import_rxjs4.takeWhile)((e) => !(e.type === RuntimeEventTypes.ActionExecutionEnd && e.actionExecutionId == event.actionExecutionId)),
4397
+ // filter out any other action execution events or action execution ids
4398
+ (0, import_rxjs4.filter)((e) => e.type == RuntimeEventTypes.ActionExecutionArgs && e.actionExecutionId == event.actionExecutionId)
4399
+ );
4400
+ const streamingArgumentsStatus = new import_rxjs4.Subject();
4401
+ pushMessage({
4402
+ id: event.actionExecutionId,
4403
+ parentMessageId: event.parentMessageId,
4404
+ status: (0, import_rxjs4.firstValueFrom)(streamingArgumentsStatus),
4405
+ createdAt: /* @__PURE__ */ new Date(),
4406
+ name: event.actionName,
4407
+ arguments: new import_graphql_yoga.Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
4408
+ logger2.debug("Action execution argument stream created");
4409
+ const argumentChunks = [];
4410
+ let actionExecutionArgumentSubscription;
4411
+ actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({
4412
+ next: async (e) => {
4413
+ if (e.type == RuntimeEventTypes.ActionExecutionArgs) {
4414
+ await pushArgumentsChunk(e.args);
4415
+ argumentChunks.push(e.args);
4416
+ }
4417
+ },
4418
+ error: (err) => {
4419
+ logger2.error({
4420
+ err
4421
+ }, "Error in action execution argument stream");
4422
+ streamingArgumentsStatus.next((0, import_class_transformer3.plainToInstance)(FailedMessageStatus, {
4423
+ reason: "An unknown error has occurred in the action execution argument stream"
4424
+ }));
4425
+ stopStreamingArguments();
4426
+ actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
4427
+ },
4428
+ complete: () => {
4429
+ logger2.debug("Action execution argument stream completed");
4430
+ streamingArgumentsStatus.next(new SuccessMessageStatus());
4431
+ stopStreamingArguments();
4432
+ actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
4433
+ outputMessages.push((0, import_class_transformer3.plainToInstance)(ActionExecutionMessage, {
4434
+ id: event.actionExecutionId,
4435
+ createdAt: /* @__PURE__ */ new Date(),
4436
+ name: event.actionName,
4437
+ arguments: argumentChunks.join("")
4438
+ }));
4439
+ }
4440
+ });
4441
+ })
4442
+ });
4443
+ break;
4444
+ case RuntimeEventTypes.ActionExecutionResult:
4445
+ logger2.debug({
4446
+ result: event.result
4447
+ }, "Action execution result event received");
4448
+ pushMessage({
4449
+ id: "result-" + event.actionExecutionId,
4450
+ status: new SuccessMessageStatus(),
4451
+ createdAt: /* @__PURE__ */ new Date(),
4452
+ actionExecutionId: event.actionExecutionId,
4453
+ actionName: event.actionName,
4454
+ result: event.result
4455
+ });
4456
+ outputMessages.push((0, import_class_transformer3.plainToInstance)(ResultMessage, {
4457
+ id: "result-" + event.actionExecutionId,
4458
+ createdAt: /* @__PURE__ */ new Date(),
4459
+ actionExecutionId: event.actionExecutionId,
4460
+ actionName: event.actionName,
4461
+ result: event.result
4462
+ }));
4463
+ break;
4464
+ case RuntimeEventTypes.AgentStateMessage:
4465
+ logger2.debug({
4466
+ event
4467
+ }, "Agent message event received");
4468
+ pushMessage({
4469
+ id: (0, import_shared10.randomId)(),
4470
+ status: new SuccessMessageStatus(),
4471
+ threadId: event.threadId,
4472
+ agentName: event.agentName,
4473
+ nodeName: event.nodeName,
4474
+ runId: event.runId,
4475
+ active: event.active,
4476
+ state: event.state,
4477
+ running: event.running,
4478
+ role: MessageRole.assistant,
4479
+ createdAt: /* @__PURE__ */ new Date()
4480
+ });
4481
+ outputMessages.push((0, import_class_transformer3.plainToInstance)(AgentStateMessage, {
4482
+ id: (0, import_shared10.randomId)(),
4483
+ threadId: event.threadId,
4484
+ agentName: event.agentName,
4485
+ nodeName: event.nodeName,
4486
+ runId: event.runId,
4487
+ active: event.active,
4488
+ state: event.state,
4489
+ running: event.running,
4490
+ role: MessageRole.assistant,
4491
+ createdAt: /* @__PURE__ */ new Date()
4492
+ }));
4493
+ break;
4494
+ }
4495
+ },
4496
+ error: (err) => {
4497
+ logger2.error({
4498
+ err
4499
+ }, "Error in event stream");
4500
+ responseStatus$.next(new UnknownErrorResponse({
4501
+ description: `An unknown error has occurred in the event stream`
4502
+ }));
4503
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
4504
+ stopStreamingMessages();
4505
+ rejectOutputMessagesPromise(err);
4506
+ },
4507
+ complete: async () => {
4508
+ var _a3;
4509
+ logger2.debug("Event stream completed");
4510
+ if ((_a3 = data.cloud) == null ? void 0 : _a3.guardrails) {
4511
+ logger2.debug("Guardrails is enabled, waiting for guardrails result");
4512
+ await (0, import_rxjs4.firstValueFrom)(guardrailsResult$);
4513
+ }
4514
+ responseStatus$.next(new SuccessResponseStatus());
4515
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
4516
+ stopStreamingMessages();
4517
+ resolveOutputMessagesPromise(outputMessages);
4518
+ }
4519
+ });
4520
+ })
4521
+ };
4522
+ return response;
4523
+ }
4524
+ };
4525
+ __name(CopilotResolver, "CopilotResolver");
4526
+ _ts_decorate15([
4527
+ (0, import_type_graphql16.Query)(() => String),
4528
+ _ts_metadata15("design:type", Function),
4529
+ _ts_metadata15("design:paramtypes", []),
4530
+ _ts_metadata15("design:returntype", Promise)
4531
+ ], CopilotResolver.prototype, "hello", null);
4532
+ _ts_decorate15([
4533
+ (0, import_type_graphql16.Query)(() => AgentsResponse),
4534
+ _ts_param(0, (0, import_type_graphql16.Ctx)()),
4535
+ _ts_metadata15("design:type", Function),
4536
+ _ts_metadata15("design:paramtypes", [
4537
+ typeof GraphQLContext === "undefined" ? Object : GraphQLContext
4538
+ ]),
4539
+ _ts_metadata15("design:returntype", Promise)
4540
+ ], CopilotResolver.prototype, "availableAgents", null);
4541
+ _ts_decorate15([
4542
+ (0, import_type_graphql16.Mutation)(() => CopilotResponse),
4543
+ _ts_param(0, (0, import_type_graphql16.Ctx)()),
4544
+ _ts_param(1, (0, import_type_graphql16.Arg)("data")),
4545
+ _ts_param(2, (0, import_type_graphql16.Arg)("properties", () => import_graphql_scalars2.GraphQLJSONObject, {
4546
+ nullable: true
4547
+ })),
4548
+ _ts_metadata15("design:type", Function),
4549
+ _ts_metadata15("design:paramtypes", [
4550
+ typeof GraphQLContext === "undefined" ? Object : GraphQLContext,
4551
+ typeof GenerateCopilotResponseInput === "undefined" ? Object : GenerateCopilotResponseInput,
4552
+ typeof CopilotRequestContextProperties === "undefined" ? Object : CopilotRequestContextProperties
4553
+ ]),
4554
+ _ts_metadata15("design:returntype", Promise)
4555
+ ], CopilotResolver.prototype, "generateCopilotResponse", null);
4556
+ CopilotResolver = _ts_decorate15([
4557
+ (0, import_type_graphql16.Resolver)(() => CopilotResponse)
4558
+ ], CopilotResolver);
4559
+
4560
+ // src/lib/integrations/shared.ts
4561
+ var import_plugin_defer_stream = require("@graphql-yoga/plugin-defer-stream");
4562
+
4563
+ // src/lib/logger.ts
4564
+ var import_pino = __toESM(require("pino"));
4565
+ var import_pino_pretty = __toESM(require("pino-pretty"));
4566
+ function createLogger(options) {
4567
+ const { level, component } = options || {};
4568
+ const stream = (0, import_pino_pretty.default)({
4569
+ colorize: true
4570
+ });
4571
+ const logger2 = (0, import_pino.default)({
4572
+ level: process.env.LOG_LEVEL || level || "error",
4573
+ redact: {
4574
+ paths: [
4575
+ "pid",
4576
+ "hostname"
4577
+ ],
4578
+ remove: true
4579
+ }
4580
+ }, stream);
4581
+ if (component) {
4582
+ return logger2.child({
4583
+ component
4584
+ });
4585
+ } else {
4586
+ return logger2;
4587
+ }
4588
+ }
4589
+ __name(createLogger, "createLogger");
4590
+
4591
+ // src/lib/integrations/shared.ts
4592
+ var logger = createLogger();
4593
+ async function createContext(initialContext, copilotKitContext, contextLogger, properties = {}) {
4594
+ logger.debug({
4595
+ copilotKitContext
4596
+ }, "Creating GraphQL context");
4597
+ const ctx = {
4598
+ ...initialContext,
4599
+ _copilotkit: {
4600
+ ...copilotKitContext
4601
+ },
4602
+ properties: {
4603
+ ...properties
4604
+ },
4605
+ logger: contextLogger
4606
+ };
4607
+ return ctx;
4608
+ }
4609
+ __name(createContext, "createContext");
4610
+ function buildSchema(options = {}) {
4611
+ logger.debug("Building GraphQL schema...");
4612
+ const schema = (0, import_type_graphql17.buildSchemaSync)({
4613
+ resolvers: [
4614
+ CopilotResolver
4615
+ ],
4616
+ emitSchemaFile: options.emitSchemaFile
4617
+ });
4618
+ logger.debug("GraphQL schema built successfully");
4619
+ return schema;
4620
+ }
4621
+ __name(buildSchema, "buildSchema");
4622
+ function getCommonConfig(options) {
4623
+ var _a;
4624
+ const logLevel = process.env.LOG_LEVEL || options.logLevel || "error";
4625
+ const logger2 = createLogger({
4626
+ level: logLevel,
4627
+ component: "getCommonConfig"
4628
+ });
4629
+ const contextLogger = createLogger({
4630
+ level: logLevel
4631
+ });
4632
+ if (options.cloud) {
4633
+ telemetry_client_default.setCloudConfiguration({
4634
+ publicApiKey: options.cloud.publicApiKey,
4635
+ baseUrl: options.cloud.baseUrl
4636
+ });
4637
+ }
4638
+ if ((_a = options.properties) == null ? void 0 : _a._copilotkit) {
4639
+ telemetry_client_default.setGlobalProperties({
4640
+ _copilotkit: {
4641
+ ...options.properties._copilotkit
4642
+ }
4643
+ });
4644
+ }
4645
+ telemetry_client_default.setGlobalProperties({
4646
+ runtime: {
4647
+ serviceAdapter: options.serviceAdapter.constructor.name
4648
+ }
4649
+ });
4650
+ return {
4651
+ logging: createLogger({
4652
+ component: "Yoga GraphQL",
4653
+ level: logLevel
4654
+ }),
4655
+ schema: buildSchema(),
4656
+ plugins: [
4657
+ (0, import_plugin_defer_stream.useDeferStream)()
4658
+ ],
4659
+ context: (ctx) => createContext(ctx, options, contextLogger, options.properties)
4660
+ };
4661
+ }
4662
+ __name(getCommonConfig, "getCommonConfig");
4663
+
4664
+ // src/lib/integrations/nextjs/app-router.ts
4665
+ var import_graphql_yoga2 = require("graphql-yoga");
4666
+ function copilotRuntimeNextJSAppRouterEndpoint(options) {
4667
+ var _a;
4668
+ const commonConfig = getCommonConfig(options);
4669
+ telemetry_client_default.setGlobalProperties({
4670
+ runtime: {
4671
+ framework: "nextjs-app-router"
4672
+ }
4673
+ });
4674
+ if ((_a = options.properties) == null ? void 0 : _a._copilotkit) {
4675
+ telemetry_client_default.setGlobalProperties({
4676
+ _copilotkit: options.properties._copilotkit
4677
+ });
4678
+ }
4679
+ telemetry_client_default.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options.runtime));
4680
+ const logger2 = commonConfig.logging;
4681
+ logger2.debug("Creating NextJS App Router endpoint");
4682
+ const yoga = (0, import_graphql_yoga2.createYoga)({
4683
+ ...commonConfig,
4684
+ graphqlEndpoint: options.endpoint,
4685
+ fetchAPI: {
4686
+ Response: globalThis.Response
4687
+ }
4688
+ });
4689
+ return {
4690
+ handleRequest: yoga,
4691
+ GET: yoga,
4692
+ POST: yoga,
4693
+ OPTIONS: yoga
4694
+ };
4695
+ }
4696
+ __name(copilotRuntimeNextJSAppRouterEndpoint, "copilotRuntimeNextJSAppRouterEndpoint");
4697
+
4698
+ // src/lib/integrations/nextjs/pages-router.ts
4699
+ var import_graphql_yoga3 = require("graphql-yoga");
4700
+ var config = {
4701
+ api: {
4702
+ bodyParser: false
4703
+ }
4704
+ };
4705
+ function copilotRuntimeNextJSPagesRouterEndpoint(options) {
4706
+ var _a;
4707
+ const commonConfig = getCommonConfig(options);
4708
+ telemetry_client_default.setGlobalProperties({
4709
+ runtime: {
4710
+ framework: "nextjs-pages-router"
4711
+ }
4712
+ });
4713
+ if ((_a = options.properties) == null ? void 0 : _a._copilotkit) {
4714
+ telemetry_client_default.setGlobalProperties({
4715
+ _copilotkit: options.properties._copilotkit
4716
+ });
4717
+ }
4718
+ telemetry_client_default.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options.runtime));
4719
+ const logger2 = commonConfig.logging;
4720
+ logger2.debug("Creating NextJS Pages Router endpoint");
4721
+ const yoga = (0, import_graphql_yoga3.createYoga)({
4722
+ ...commonConfig,
4723
+ graphqlEndpoint: options.endpoint
4724
+ });
4725
+ return yoga;
4726
+ }
4727
+ __name(copilotRuntimeNextJSPagesRouterEndpoint, "copilotRuntimeNextJSPagesRouterEndpoint");
4728
+
4729
+ // src/lib/integrations/node-http/index.ts
4730
+ var import_graphql_yoga4 = require("graphql-yoga");
4731
+ function copilotRuntimeNodeHttpEndpoint(options) {
4732
+ var _a;
4733
+ const commonConfig = getCommonConfig(options);
4734
+ telemetry_client_default.setGlobalProperties({
4735
+ runtime: {
4736
+ framework: "node-http"
4737
+ }
4738
+ });
4739
+ if ((_a = options.properties) == null ? void 0 : _a._copilotkit) {
4740
+ telemetry_client_default.setGlobalProperties({
4741
+ _copilotkit: options.properties._copilotkit
4742
+ });
4743
+ }
4744
+ telemetry_client_default.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options.runtime));
4745
+ const logger2 = commonConfig.logging;
4746
+ logger2.debug("Creating Node HTTP endpoint");
4747
+ const yoga = (0, import_graphql_yoga4.createYoga)({
4748
+ ...commonConfig,
4749
+ graphqlEndpoint: options.endpoint
4750
+ });
4751
+ return yoga;
4752
+ }
4753
+ __name(copilotRuntimeNodeHttpEndpoint, "copilotRuntimeNodeHttpEndpoint");
4754
+
4755
+ // src/lib/integrations/node-express/index.ts
4756
+ function copilotRuntimeNodeExpressEndpoint(options) {
4757
+ telemetry_client_default.setGlobalProperties({
4758
+ runtime: {
4759
+ framework: "node-express"
4760
+ }
4761
+ });
4762
+ telemetry_client_default.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options.runtime));
4763
+ return copilotRuntimeNodeHttpEndpoint(options);
4764
+ }
4765
+ __name(copilotRuntimeNodeExpressEndpoint, "copilotRuntimeNodeExpressEndpoint");
4766
+
4767
+ // src/lib/integrations/nest/index.ts
4768
+ function copilotRuntimeNestEndpoint(options) {
4769
+ telemetry_client_default.setGlobalProperties({
4770
+ runtime: {
4771
+ framework: "nest"
4772
+ }
4773
+ });
4774
+ telemetry_client_default.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options.runtime));
4775
+ return copilotRuntimeNodeHttpEndpoint(options);
4776
+ }
4777
+ __name(copilotRuntimeNestEndpoint, "copilotRuntimeNestEndpoint");
4778
+ // Annotate the CommonJS export names for ESM import in node:
4779
+ 0 && (module.exports = {
4780
+ CopilotRuntime,
4781
+ GoogleGenerativeAIAdapter,
4782
+ GroqAdapter,
4783
+ LangChainAdapter,
4784
+ OpenAIAdapter,
4785
+ OpenAIAssistantAdapter,
4786
+ UnifyAdapter,
4787
+ buildSchema,
4788
+ config,
4789
+ copilotKitEndpoint,
4790
+ copilotRuntimeNestEndpoint,
4791
+ copilotRuntimeNextJSAppRouterEndpoint,
4792
+ copilotRuntimeNextJSPagesRouterEndpoint,
4793
+ copilotRuntimeNodeExpressEndpoint,
4794
+ copilotRuntimeNodeHttpEndpoint,
4795
+ createContext,
4796
+ flattenToolCallsNoDuplicates,
4797
+ getCommonConfig,
4798
+ langGraphPlatformEndpoint,
4799
+ resolveEndpointType
4800
+ });
4801
+ //# sourceMappingURL=index.js.map