@copilotkit/runtime 1.5.1-test-custom-tag-prerelease-1.0 → 1.5.2-next.0

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