@copilotkit/runtime 0.0.0-feat-dynamic-copilotcloud-qa-20250117190454

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