@copilotkit/runtime 1.5.1-next.3 → 1.5.1-next.4

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