@copilotkit/runtime 1.50.0-beta.1 → 1.50.0-beta.11

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