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