@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
@@ -1,3147 +0,0 @@
1
- import {
2
- GuardrailsValidationFailureResponse,
3
- MessageStreamInterruptedResponse,
4
- ResponseStatusUnion,
5
- SuccessResponseStatus,
6
- UnknownErrorResponse
7
- } from "./chunk-U3V2BCGI.mjs";
8
- import {
9
- RemoteChain,
10
- streamLangChainResponse
11
- } from "./chunk-OKQVDDJ2.mjs";
12
- import {
13
- ActionExecutionMessage,
14
- AgentStateMessage,
15
- ResultMessage,
16
- TextMessage
17
- } from "./chunk-B74M7FXG.mjs";
18
- import {
19
- BaseMessageInput
20
- } from "./chunk-D2WLFQS6.mjs";
21
- import {
22
- __commonJS,
23
- __name
24
- } from "./chunk-44O2JGUY.mjs";
25
-
26
- // package.json
27
- var require_package = __commonJS({
28
- "package.json"(exports, module) {
29
- module.exports = {
30
- name: "@copilotkit/runtime",
31
- private: false,
32
- homepage: "https://github.com/CopilotKit/CopilotKit",
33
- repository: {
34
- type: "git",
35
- url: "https://github.com/CopilotKit/CopilotKit.git"
36
- },
37
- publishConfig: {
38
- access: "public"
39
- },
40
- version: "1.4.1-pre.6",
41
- sideEffects: false,
42
- main: "./dist/index.js",
43
- module: "./dist/index.mjs",
44
- exports: {
45
- ".": "./dist/index.js"
46
- },
47
- types: "./dist/index.d.ts",
48
- license: "MIT",
49
- scripts: {
50
- build: 'tsup --onSuccess "pnpm run generate-graphql-schema"',
51
- dev: 'tsup --watch --onSuccess "pnpm run generate-graphql-schema"',
52
- test: "jest --passWithNoTests",
53
- "check-types": "tsc --noEmit",
54
- clean: "rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__",
55
- "generate-graphql-schema": "rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts",
56
- "link:global": "pnpm link --global",
57
- "unlink:global": "pnpm unlink --global"
58
- },
59
- devDependencies: {
60
- "@swc/core": "1.5.28",
61
- "@types/express": "^4.17.21",
62
- "@types/jest": "^29.5.4",
63
- "@types/node": "^18.11.17",
64
- "@whatwg-node/server": "^0.9.34",
65
- eslint: "^8.56.0",
66
- "eslint-config-custom": "workspace:*",
67
- jest: "^29.6.4",
68
- nodemon: "^3.1.3",
69
- "ts-jest": "^29.1.1",
70
- "ts-node": "^10.9.2",
71
- tsconfig: "workspace:*",
72
- tsup: "^6.7.0",
73
- typescript: "^5.2.3",
74
- "zod-to-json-schema": "^3.23.5"
75
- },
76
- dependencies: {
77
- "@anthropic-ai/sdk": "^0.27.3",
78
- "@copilotkit/shared": "workspace:*",
79
- "@graphql-yoga/plugin-defer-stream": "^3.3.1",
80
- "@langchain/community": "^0.0.53",
81
- "@langchain/core": "^0.3.13",
82
- "@langchain/google-gauth": "^0.1.0",
83
- "@langchain/langgraph-sdk": "^0.0.16",
84
- "@langchain/openai": "^0.0.28",
85
- "class-transformer": "^0.5.1",
86
- express: "^4.19.2",
87
- graphql: "^16.8.1",
88
- "graphql-scalars": "^1.23.0",
89
- "graphql-yoga": "^5.3.1",
90
- "groq-sdk": "^0.5.0",
91
- langchain: "^0.3.3",
92
- openai: "^4.50.0",
93
- "partial-json": "^0.1.7",
94
- pino: "^9.2.0",
95
- "pino-pretty": "^11.2.1",
96
- "reflect-metadata": "^0.2.2",
97
- rxjs: "^7.8.1",
98
- "type-graphql": "2.0.0-rc.1",
99
- zod: "^3.23.3"
100
- },
101
- keywords: [
102
- "copilotkit",
103
- "copilot",
104
- "react",
105
- "nextjs",
106
- "nodejs",
107
- "ai",
108
- "assistant",
109
- "javascript",
110
- "automation",
111
- "textarea"
112
- ]
113
- };
114
- }
115
- });
116
-
117
- // src/lib/integrations/node-http/index.ts
118
- import { createYoga } from "graphql-yoga";
119
-
120
- // src/lib/integrations/shared.ts
121
- import { buildSchemaSync } from "type-graphql";
122
-
123
- // src/graphql/resolvers/copilot.resolver.ts
124
- import { Arg, Ctx, Mutation, Query, Resolver } from "type-graphql";
125
- import { ReplaySubject as ReplaySubject3, Subject, finalize, firstValueFrom as firstValueFrom2, shareReplay, skipWhile, take, takeWhile, tap } from "rxjs";
126
-
127
- // src/graphql/inputs/generate-copilot-response.input.ts
128
- import { Field as Field9, InputType as InputType9 } from "type-graphql";
129
-
130
- // src/graphql/inputs/message.input.ts
131
- import { Field, InputType } from "type-graphql";
132
-
133
- // src/graphql/types/enums.ts
134
- import { registerEnumType } from "type-graphql";
135
- var MessageRole;
136
- (function(MessageRole2) {
137
- MessageRole2["user"] = "user";
138
- MessageRole2["assistant"] = "assistant";
139
- MessageRole2["system"] = "system";
140
- MessageRole2["tool"] = "tool";
141
- })(MessageRole || (MessageRole = {}));
142
- var ActionExecutionScope;
143
- (function(ActionExecutionScope2) {
144
- ActionExecutionScope2["server"] = "server";
145
- ActionExecutionScope2["client"] = "client";
146
- ActionExecutionScope2["passThrough"] = "passThrough";
147
- })(ActionExecutionScope || (ActionExecutionScope = {}));
148
- var CopilotRequestType;
149
- (function(CopilotRequestType2) {
150
- CopilotRequestType2["Chat"] = "Chat";
151
- CopilotRequestType2["Task"] = "Task";
152
- CopilotRequestType2["TextareaCompletion"] = "TextareaCompletion";
153
- CopilotRequestType2["TextareaPopover"] = "TextareaPopover";
154
- CopilotRequestType2["Suggestion"] = "Suggestion";
155
- })(CopilotRequestType || (CopilotRequestType = {}));
156
- var ActionInputAvailability;
157
- (function(ActionInputAvailability2) {
158
- ActionInputAvailability2["disabled"] = "disabled";
159
- ActionInputAvailability2["enabled"] = "enabled";
160
- ActionInputAvailability2["remote"] = "remote";
161
- })(ActionInputAvailability || (ActionInputAvailability = {}));
162
- registerEnumType(MessageRole, {
163
- name: "MessageRole",
164
- description: "The role of the message"
165
- });
166
- registerEnumType(ActionExecutionScope, {
167
- name: "ActionExecutionScope",
168
- description: "The scope of the action"
169
- });
170
- registerEnumType(CopilotRequestType, {
171
- name: "CopilotRequestType",
172
- description: "The type of Copilot request"
173
- });
174
- registerEnumType(ActionInputAvailability, {
175
- name: "ActionInputAvailability",
176
- description: "The availability of the frontend action"
177
- });
178
-
179
- // src/graphql/inputs/message.input.ts
180
- function _ts_decorate(decorators, target, key, desc) {
181
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
182
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
183
- r = Reflect.decorate(decorators, target, key, desc);
184
- else
185
- for (var i = decorators.length - 1; i >= 0; i--)
186
- if (d = decorators[i])
187
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
188
- return c > 3 && r && Object.defineProperty(target, key, r), r;
189
- }
190
- __name(_ts_decorate, "_ts_decorate");
191
- function _ts_metadata(k, v) {
192
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
193
- return Reflect.metadata(k, v);
194
- }
195
- __name(_ts_metadata, "_ts_metadata");
196
- var MessageInput = class extends BaseMessageInput {
197
- textMessage;
198
- actionExecutionMessage;
199
- resultMessage;
200
- agentStateMessage;
201
- };
202
- __name(MessageInput, "MessageInput");
203
- _ts_decorate([
204
- Field(() => TextMessageInput, {
205
- nullable: true
206
- }),
207
- _ts_metadata("design:type", typeof TextMessageInput === "undefined" ? Object : TextMessageInput)
208
- ], MessageInput.prototype, "textMessage", void 0);
209
- _ts_decorate([
210
- Field(() => ActionExecutionMessageInput, {
211
- nullable: true
212
- }),
213
- _ts_metadata("design:type", typeof ActionExecutionMessageInput === "undefined" ? Object : ActionExecutionMessageInput)
214
- ], MessageInput.prototype, "actionExecutionMessage", void 0);
215
- _ts_decorate([
216
- Field(() => ResultMessageInput, {
217
- nullable: true
218
- }),
219
- _ts_metadata("design:type", typeof ResultMessageInput === "undefined" ? Object : ResultMessageInput)
220
- ], MessageInput.prototype, "resultMessage", void 0);
221
- _ts_decorate([
222
- Field(() => AgentStateMessageInput, {
223
- nullable: true
224
- }),
225
- _ts_metadata("design:type", typeof AgentStateMessageInput === "undefined" ? Object : AgentStateMessageInput)
226
- ], MessageInput.prototype, "agentStateMessage", void 0);
227
- MessageInput = _ts_decorate([
228
- InputType()
229
- ], MessageInput);
230
- var TextMessageInput = class {
231
- content;
232
- role;
233
- };
234
- __name(TextMessageInput, "TextMessageInput");
235
- _ts_decorate([
236
- Field(() => String),
237
- _ts_metadata("design:type", String)
238
- ], TextMessageInput.prototype, "content", void 0);
239
- _ts_decorate([
240
- Field(() => MessageRole),
241
- _ts_metadata("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
242
- ], TextMessageInput.prototype, "role", void 0);
243
- TextMessageInput = _ts_decorate([
244
- InputType()
245
- ], TextMessageInput);
246
- var ActionExecutionMessageInput = class {
247
- name;
248
- arguments;
249
- scope;
250
- };
251
- __name(ActionExecutionMessageInput, "ActionExecutionMessageInput");
252
- _ts_decorate([
253
- Field(() => String),
254
- _ts_metadata("design:type", String)
255
- ], ActionExecutionMessageInput.prototype, "name", void 0);
256
- _ts_decorate([
257
- Field(() => String),
258
- _ts_metadata("design:type", String)
259
- ], ActionExecutionMessageInput.prototype, "arguments", void 0);
260
- _ts_decorate([
261
- Field(() => ActionExecutionScope),
262
- _ts_metadata("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
263
- ], ActionExecutionMessageInput.prototype, "scope", void 0);
264
- ActionExecutionMessageInput = _ts_decorate([
265
- InputType()
266
- ], ActionExecutionMessageInput);
267
- var ResultMessageInput = class {
268
- actionExecutionId;
269
- actionName;
270
- result;
271
- };
272
- __name(ResultMessageInput, "ResultMessageInput");
273
- _ts_decorate([
274
- Field(() => String),
275
- _ts_metadata("design:type", String)
276
- ], ResultMessageInput.prototype, "actionExecutionId", void 0);
277
- _ts_decorate([
278
- Field(() => String),
279
- _ts_metadata("design:type", String)
280
- ], ResultMessageInput.prototype, "actionName", void 0);
281
- _ts_decorate([
282
- Field(() => String),
283
- _ts_metadata("design:type", String)
284
- ], ResultMessageInput.prototype, "result", void 0);
285
- ResultMessageInput = _ts_decorate([
286
- InputType()
287
- ], ResultMessageInput);
288
- var AgentStateMessageInput = class {
289
- threadId;
290
- agentName;
291
- role;
292
- state;
293
- running;
294
- nodeName;
295
- runId;
296
- active;
297
- };
298
- __name(AgentStateMessageInput, "AgentStateMessageInput");
299
- _ts_decorate([
300
- Field(() => String),
301
- _ts_metadata("design:type", String)
302
- ], AgentStateMessageInput.prototype, "threadId", void 0);
303
- _ts_decorate([
304
- Field(() => String),
305
- _ts_metadata("design:type", String)
306
- ], AgentStateMessageInput.prototype, "agentName", void 0);
307
- _ts_decorate([
308
- Field(() => MessageRole),
309
- _ts_metadata("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
310
- ], AgentStateMessageInput.prototype, "role", void 0);
311
- _ts_decorate([
312
- Field(() => String),
313
- _ts_metadata("design:type", String)
314
- ], AgentStateMessageInput.prototype, "state", void 0);
315
- _ts_decorate([
316
- Field(() => Boolean),
317
- _ts_metadata("design:type", Boolean)
318
- ], AgentStateMessageInput.prototype, "running", void 0);
319
- _ts_decorate([
320
- Field(() => String),
321
- _ts_metadata("design:type", String)
322
- ], AgentStateMessageInput.prototype, "nodeName", void 0);
323
- _ts_decorate([
324
- Field(() => String),
325
- _ts_metadata("design:type", String)
326
- ], AgentStateMessageInput.prototype, "runId", void 0);
327
- _ts_decorate([
328
- Field(() => Boolean),
329
- _ts_metadata("design:type", Boolean)
330
- ], AgentStateMessageInput.prototype, "active", void 0);
331
- AgentStateMessageInput = _ts_decorate([
332
- InputType()
333
- ], AgentStateMessageInput);
334
-
335
- // src/graphql/inputs/frontend.input.ts
336
- import { Field as Field3, InputType as InputType3 } from "type-graphql";
337
-
338
- // src/graphql/inputs/action.input.ts
339
- import { Field as Field2, InputType as InputType2 } from "type-graphql";
340
- function _ts_decorate2(decorators, target, key, desc) {
341
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
342
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
343
- r = Reflect.decorate(decorators, target, key, desc);
344
- else
345
- for (var i = decorators.length - 1; i >= 0; i--)
346
- if (d = decorators[i])
347
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
348
- return c > 3 && r && Object.defineProperty(target, key, r), r;
349
- }
350
- __name(_ts_decorate2, "_ts_decorate");
351
- function _ts_metadata2(k, v) {
352
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
353
- return Reflect.metadata(k, v);
354
- }
355
- __name(_ts_metadata2, "_ts_metadata");
356
- var ActionInput = class {
357
- name;
358
- description;
359
- jsonSchema;
360
- available;
361
- };
362
- __name(ActionInput, "ActionInput");
363
- _ts_decorate2([
364
- Field2(() => String),
365
- _ts_metadata2("design:type", String)
366
- ], ActionInput.prototype, "name", void 0);
367
- _ts_decorate2([
368
- Field2(() => String),
369
- _ts_metadata2("design:type", String)
370
- ], ActionInput.prototype, "description", void 0);
371
- _ts_decorate2([
372
- Field2(() => String),
373
- _ts_metadata2("design:type", String)
374
- ], ActionInput.prototype, "jsonSchema", void 0);
375
- _ts_decorate2([
376
- Field2(() => ActionInputAvailability, {
377
- nullable: true
378
- }),
379
- _ts_metadata2("design:type", typeof ActionInputAvailability === "undefined" ? Object : ActionInputAvailability)
380
- ], ActionInput.prototype, "available", void 0);
381
- ActionInput = _ts_decorate2([
382
- InputType2()
383
- ], ActionInput);
384
-
385
- // src/graphql/inputs/frontend.input.ts
386
- function _ts_decorate3(decorators, target, key, desc) {
387
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
388
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
389
- r = Reflect.decorate(decorators, target, key, desc);
390
- else
391
- for (var i = decorators.length - 1; i >= 0; i--)
392
- if (d = decorators[i])
393
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
394
- return c > 3 && r && Object.defineProperty(target, key, r), r;
395
- }
396
- __name(_ts_decorate3, "_ts_decorate");
397
- function _ts_metadata3(k, v) {
398
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
399
- return Reflect.metadata(k, v);
400
- }
401
- __name(_ts_metadata3, "_ts_metadata");
402
- var FrontendInput = class {
403
- toDeprecate_fullContext;
404
- actions;
405
- url;
406
- };
407
- __name(FrontendInput, "FrontendInput");
408
- _ts_decorate3([
409
- Field3(() => String, {
410
- nullable: true
411
- }),
412
- _ts_metadata3("design:type", String)
413
- ], FrontendInput.prototype, "toDeprecate_fullContext", void 0);
414
- _ts_decorate3([
415
- Field3(() => [
416
- ActionInput
417
- ]),
418
- _ts_metadata3("design:type", Array)
419
- ], FrontendInput.prototype, "actions", void 0);
420
- _ts_decorate3([
421
- Field3(() => String, {
422
- nullable: true
423
- }),
424
- _ts_metadata3("design:type", String)
425
- ], FrontendInput.prototype, "url", void 0);
426
- FrontendInput = _ts_decorate3([
427
- InputType3()
428
- ], FrontendInput);
429
-
430
- // src/graphql/inputs/cloud.input.ts
431
- import { Field as Field5, InputType as InputType5 } from "type-graphql";
432
-
433
- // src/graphql/inputs/cloud-guardrails.input.ts
434
- import { Field as Field4, InputType as InputType4 } from "type-graphql";
435
- function _ts_decorate4(decorators, target, key, desc) {
436
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
437
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
438
- r = Reflect.decorate(decorators, target, key, desc);
439
- else
440
- for (var i = decorators.length - 1; i >= 0; i--)
441
- if (d = decorators[i])
442
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
443
- return c > 3 && r && Object.defineProperty(target, key, r), r;
444
- }
445
- __name(_ts_decorate4, "_ts_decorate");
446
- function _ts_metadata4(k, v) {
447
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
448
- return Reflect.metadata(k, v);
449
- }
450
- __name(_ts_metadata4, "_ts_metadata");
451
- var GuardrailsRuleInput = class {
452
- allowList = [];
453
- denyList = [];
454
- };
455
- __name(GuardrailsRuleInput, "GuardrailsRuleInput");
456
- _ts_decorate4([
457
- Field4(() => [
458
- String
459
- ], {
460
- nullable: true
461
- }),
462
- _ts_metadata4("design:type", Array)
463
- ], GuardrailsRuleInput.prototype, "allowList", void 0);
464
- _ts_decorate4([
465
- Field4(() => [
466
- String
467
- ], {
468
- nullable: true
469
- }),
470
- _ts_metadata4("design:type", Array)
471
- ], GuardrailsRuleInput.prototype, "denyList", void 0);
472
- GuardrailsRuleInput = _ts_decorate4([
473
- InputType4()
474
- ], GuardrailsRuleInput);
475
- var GuardrailsInput = class {
476
- inputValidationRules;
477
- };
478
- __name(GuardrailsInput, "GuardrailsInput");
479
- _ts_decorate4([
480
- Field4(() => GuardrailsRuleInput, {
481
- nullable: false
482
- }),
483
- _ts_metadata4("design:type", typeof GuardrailsRuleInput === "undefined" ? Object : GuardrailsRuleInput)
484
- ], GuardrailsInput.prototype, "inputValidationRules", void 0);
485
- GuardrailsInput = _ts_decorate4([
486
- InputType4()
487
- ], GuardrailsInput);
488
-
489
- // src/graphql/inputs/cloud.input.ts
490
- function _ts_decorate5(decorators, target, key, desc) {
491
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
492
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
493
- r = Reflect.decorate(decorators, target, key, desc);
494
- else
495
- for (var i = decorators.length - 1; i >= 0; i--)
496
- if (d = decorators[i])
497
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
498
- return c > 3 && r && Object.defineProperty(target, key, r), r;
499
- }
500
- __name(_ts_decorate5, "_ts_decorate");
501
- function _ts_metadata5(k, v) {
502
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
503
- return Reflect.metadata(k, v);
504
- }
505
- __name(_ts_metadata5, "_ts_metadata");
506
- var CloudInput = class {
507
- guardrails;
508
- };
509
- __name(CloudInput, "CloudInput");
510
- _ts_decorate5([
511
- Field5(() => GuardrailsInput, {
512
- nullable: true
513
- }),
514
- _ts_metadata5("design:type", typeof GuardrailsInput === "undefined" ? Object : GuardrailsInput)
515
- ], CloudInput.prototype, "guardrails", void 0);
516
- CloudInput = _ts_decorate5([
517
- InputType5()
518
- ], CloudInput);
519
-
520
- // src/graphql/inputs/forwarded-parameters.input.ts
521
- import { Field as Field6, InputType as InputType6 } from "type-graphql";
522
- function _ts_decorate6(decorators, target, key, desc) {
523
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
524
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
525
- r = Reflect.decorate(decorators, target, key, desc);
526
- else
527
- for (var i = decorators.length - 1; i >= 0; i--)
528
- if (d = decorators[i])
529
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
530
- return c > 3 && r && Object.defineProperty(target, key, r), r;
531
- }
532
- __name(_ts_decorate6, "_ts_decorate");
533
- function _ts_metadata6(k, v) {
534
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
535
- return Reflect.metadata(k, v);
536
- }
537
- __name(_ts_metadata6, "_ts_metadata");
538
- var ForwardedParametersInput = class {
539
- model;
540
- maxTokens;
541
- stop;
542
- toolChoice;
543
- toolChoiceFunctionName;
544
- };
545
- __name(ForwardedParametersInput, "ForwardedParametersInput");
546
- _ts_decorate6([
547
- Field6(() => String, {
548
- nullable: true
549
- }),
550
- _ts_metadata6("design:type", String)
551
- ], ForwardedParametersInput.prototype, "model", void 0);
552
- _ts_decorate6([
553
- Field6(() => Number, {
554
- nullable: true
555
- }),
556
- _ts_metadata6("design:type", Number)
557
- ], ForwardedParametersInput.prototype, "maxTokens", void 0);
558
- _ts_decorate6([
559
- Field6(() => [
560
- String
561
- ], {
562
- nullable: true
563
- }),
564
- _ts_metadata6("design:type", Array)
565
- ], ForwardedParametersInput.prototype, "stop", void 0);
566
- _ts_decorate6([
567
- Field6(() => String, {
568
- nullable: true
569
- }),
570
- _ts_metadata6("design:type", typeof String === "undefined" ? Object : String)
571
- ], ForwardedParametersInput.prototype, "toolChoice", void 0);
572
- _ts_decorate6([
573
- Field6(() => String, {
574
- nullable: true
575
- }),
576
- _ts_metadata6("design:type", String)
577
- ], ForwardedParametersInput.prototype, "toolChoiceFunctionName", void 0);
578
- ForwardedParametersInput = _ts_decorate6([
579
- InputType6()
580
- ], ForwardedParametersInput);
581
-
582
- // src/graphql/inputs/agent-session.input.ts
583
- import { Field as Field7, InputType as InputType7 } from "type-graphql";
584
- function _ts_decorate7(decorators, target, key, desc) {
585
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
586
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
587
- r = Reflect.decorate(decorators, target, key, desc);
588
- else
589
- for (var i = decorators.length - 1; i >= 0; i--)
590
- if (d = decorators[i])
591
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
592
- return c > 3 && r && Object.defineProperty(target, key, r), r;
593
- }
594
- __name(_ts_decorate7, "_ts_decorate");
595
- function _ts_metadata7(k, v) {
596
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
597
- return Reflect.metadata(k, v);
598
- }
599
- __name(_ts_metadata7, "_ts_metadata");
600
- var AgentSessionInput = class {
601
- agentName;
602
- threadId;
603
- nodeName;
604
- };
605
- __name(AgentSessionInput, "AgentSessionInput");
606
- _ts_decorate7([
607
- Field7(() => String),
608
- _ts_metadata7("design:type", String)
609
- ], AgentSessionInput.prototype, "agentName", void 0);
610
- _ts_decorate7([
611
- Field7(() => String, {
612
- nullable: true
613
- }),
614
- _ts_metadata7("design:type", String)
615
- ], AgentSessionInput.prototype, "threadId", void 0);
616
- _ts_decorate7([
617
- Field7(() => String, {
618
- nullable: true
619
- }),
620
- _ts_metadata7("design:type", String)
621
- ], AgentSessionInput.prototype, "nodeName", void 0);
622
- AgentSessionInput = _ts_decorate7([
623
- InputType7()
624
- ], AgentSessionInput);
625
-
626
- // src/graphql/inputs/agent-state.input.ts
627
- import { Field as Field8, InputType as InputType8 } from "type-graphql";
628
- function _ts_decorate8(decorators, target, key, desc) {
629
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
630
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
631
- r = Reflect.decorate(decorators, target, key, desc);
632
- else
633
- for (var i = decorators.length - 1; i >= 0; i--)
634
- if (d = decorators[i])
635
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
636
- return c > 3 && r && Object.defineProperty(target, key, r), r;
637
- }
638
- __name(_ts_decorate8, "_ts_decorate");
639
- function _ts_metadata8(k, v) {
640
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
641
- return Reflect.metadata(k, v);
642
- }
643
- __name(_ts_metadata8, "_ts_metadata");
644
- var AgentStateInput = class {
645
- agentName;
646
- state;
647
- };
648
- __name(AgentStateInput, "AgentStateInput");
649
- _ts_decorate8([
650
- Field8(() => String),
651
- _ts_metadata8("design:type", String)
652
- ], AgentStateInput.prototype, "agentName", void 0);
653
- _ts_decorate8([
654
- Field8(() => String),
655
- _ts_metadata8("design:type", String)
656
- ], AgentStateInput.prototype, "state", void 0);
657
- AgentStateInput = _ts_decorate8([
658
- InputType8()
659
- ], AgentStateInput);
660
-
661
- // src/graphql/inputs/generate-copilot-response.input.ts
662
- function _ts_decorate9(decorators, target, key, desc) {
663
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
664
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
665
- r = Reflect.decorate(decorators, target, key, desc);
666
- else
667
- for (var i = decorators.length - 1; i >= 0; i--)
668
- if (d = decorators[i])
669
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
670
- return c > 3 && r && Object.defineProperty(target, key, r), r;
671
- }
672
- __name(_ts_decorate9, "_ts_decorate");
673
- function _ts_metadata9(k, v) {
674
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
675
- return Reflect.metadata(k, v);
676
- }
677
- __name(_ts_metadata9, "_ts_metadata");
678
- var GenerateCopilotResponseMetadataInput = class {
679
- requestType;
680
- };
681
- __name(GenerateCopilotResponseMetadataInput, "GenerateCopilotResponseMetadataInput");
682
- _ts_decorate9([
683
- Field9(() => CopilotRequestType, {
684
- nullable: true
685
- }),
686
- _ts_metadata9("design:type", typeof CopilotRequestType === "undefined" ? Object : CopilotRequestType)
687
- ], GenerateCopilotResponseMetadataInput.prototype, "requestType", void 0);
688
- GenerateCopilotResponseMetadataInput = _ts_decorate9([
689
- InputType9()
690
- ], GenerateCopilotResponseMetadataInput);
691
- var GenerateCopilotResponseInput = class {
692
- metadata;
693
- threadId;
694
- runId;
695
- messages;
696
- frontend;
697
- cloud;
698
- forwardedParameters;
699
- agentSession;
700
- agentState;
701
- agentStates;
702
- };
703
- __name(GenerateCopilotResponseInput, "GenerateCopilotResponseInput");
704
- _ts_decorate9([
705
- Field9(() => GenerateCopilotResponseMetadataInput, {
706
- nullable: false
707
- }),
708
- _ts_metadata9("design:type", typeof GenerateCopilotResponseMetadataInput === "undefined" ? Object : GenerateCopilotResponseMetadataInput)
709
- ], GenerateCopilotResponseInput.prototype, "metadata", void 0);
710
- _ts_decorate9([
711
- Field9(() => String, {
712
- nullable: true
713
- }),
714
- _ts_metadata9("design:type", String)
715
- ], GenerateCopilotResponseInput.prototype, "threadId", void 0);
716
- _ts_decorate9([
717
- Field9(() => String, {
718
- nullable: true
719
- }),
720
- _ts_metadata9("design:type", String)
721
- ], GenerateCopilotResponseInput.prototype, "runId", void 0);
722
- _ts_decorate9([
723
- Field9(() => [
724
- MessageInput
725
- ]),
726
- _ts_metadata9("design:type", Array)
727
- ], GenerateCopilotResponseInput.prototype, "messages", void 0);
728
- _ts_decorate9([
729
- Field9(() => FrontendInput),
730
- _ts_metadata9("design:type", typeof FrontendInput === "undefined" ? Object : FrontendInput)
731
- ], GenerateCopilotResponseInput.prototype, "frontend", void 0);
732
- _ts_decorate9([
733
- Field9(() => CloudInput, {
734
- nullable: true
735
- }),
736
- _ts_metadata9("design:type", typeof CloudInput === "undefined" ? Object : CloudInput)
737
- ], GenerateCopilotResponseInput.prototype, "cloud", void 0);
738
- _ts_decorate9([
739
- Field9(() => ForwardedParametersInput, {
740
- nullable: true
741
- }),
742
- _ts_metadata9("design:type", typeof ForwardedParametersInput === "undefined" ? Object : ForwardedParametersInput)
743
- ], GenerateCopilotResponseInput.prototype, "forwardedParameters", void 0);
744
- _ts_decorate9([
745
- Field9(() => AgentSessionInput, {
746
- nullable: true
747
- }),
748
- _ts_metadata9("design:type", typeof AgentSessionInput === "undefined" ? Object : AgentSessionInput)
749
- ], GenerateCopilotResponseInput.prototype, "agentSession", void 0);
750
- _ts_decorate9([
751
- Field9(() => AgentStateInput, {
752
- nullable: true
753
- }),
754
- _ts_metadata9("design:type", typeof AgentStateInput === "undefined" ? Object : AgentStateInput)
755
- ], GenerateCopilotResponseInput.prototype, "agentState", void 0);
756
- _ts_decorate9([
757
- Field9(() => [
758
- AgentStateInput
759
- ], {
760
- nullable: true
761
- }),
762
- _ts_metadata9("design:type", Array)
763
- ], GenerateCopilotResponseInput.prototype, "agentStates", void 0);
764
- GenerateCopilotResponseInput = _ts_decorate9([
765
- InputType9()
766
- ], GenerateCopilotResponseInput);
767
-
768
- // src/graphql/types/copilot-response.type.ts
769
- import { Field as Field11, InterfaceType, ObjectType as ObjectType2 } from "type-graphql";
770
-
771
- // src/graphql/types/message-status.type.ts
772
- import { Field as Field10, ObjectType, createUnionType, registerEnumType as registerEnumType2 } from "type-graphql";
773
- function _ts_decorate10(decorators, target, key, desc) {
774
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
775
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
776
- r = Reflect.decorate(decorators, target, key, desc);
777
- else
778
- for (var i = decorators.length - 1; i >= 0; i--)
779
- if (d = decorators[i])
780
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
781
- return c > 3 && r && Object.defineProperty(target, key, r), r;
782
- }
783
- __name(_ts_decorate10, "_ts_decorate");
784
- function _ts_metadata10(k, v) {
785
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
786
- return Reflect.metadata(k, v);
787
- }
788
- __name(_ts_metadata10, "_ts_metadata");
789
- var MessageStatusCode;
790
- (function(MessageStatusCode2) {
791
- MessageStatusCode2["Pending"] = "pending";
792
- MessageStatusCode2["Success"] = "success";
793
- MessageStatusCode2["Failed"] = "failed";
794
- })(MessageStatusCode || (MessageStatusCode = {}));
795
- registerEnumType2(MessageStatusCode, {
796
- name: "MessageStatusCode"
797
- });
798
- var BaseMessageStatus = /* @__PURE__ */ __name(class BaseMessageStatus2 {
799
- code;
800
- }, "BaseMessageStatus");
801
- _ts_decorate10([
802
- Field10(() => MessageStatusCode),
803
- _ts_metadata10("design:type", String)
804
- ], BaseMessageStatus.prototype, "code", void 0);
805
- BaseMessageStatus = _ts_decorate10([
806
- ObjectType()
807
- ], BaseMessageStatus);
808
- var PendingMessageStatus = class extends BaseMessageStatus {
809
- code = "pending";
810
- };
811
- __name(PendingMessageStatus, "PendingMessageStatus");
812
- PendingMessageStatus = _ts_decorate10([
813
- ObjectType()
814
- ], PendingMessageStatus);
815
- var SuccessMessageStatus = class extends BaseMessageStatus {
816
- code = "success";
817
- };
818
- __name(SuccessMessageStatus, "SuccessMessageStatus");
819
- SuccessMessageStatus = _ts_decorate10([
820
- ObjectType()
821
- ], SuccessMessageStatus);
822
- var FailedMessageStatus = class extends BaseMessageStatus {
823
- code = "failed";
824
- reason;
825
- };
826
- __name(FailedMessageStatus, "FailedMessageStatus");
827
- _ts_decorate10([
828
- Field10(() => String),
829
- _ts_metadata10("design:type", String)
830
- ], FailedMessageStatus.prototype, "reason", void 0);
831
- FailedMessageStatus = _ts_decorate10([
832
- ObjectType()
833
- ], FailedMessageStatus);
834
- var MessageStatusUnion = createUnionType({
835
- name: "MessageStatus",
836
- types: () => [
837
- PendingMessageStatus,
838
- SuccessMessageStatus,
839
- FailedMessageStatus
840
- ]
841
- });
842
-
843
- // src/graphql/types/copilot-response.type.ts
844
- function _ts_decorate11(decorators, target, key, desc) {
845
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
846
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
847
- r = Reflect.decorate(decorators, target, key, desc);
848
- else
849
- for (var i = decorators.length - 1; i >= 0; i--)
850
- if (d = decorators[i])
851
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
852
- return c > 3 && r && Object.defineProperty(target, key, r), r;
853
- }
854
- __name(_ts_decorate11, "_ts_decorate");
855
- function _ts_metadata11(k, v) {
856
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
857
- return Reflect.metadata(k, v);
858
- }
859
- __name(_ts_metadata11, "_ts_metadata");
860
- var BaseMessageOutput = /* @__PURE__ */ __name(class BaseMessageOutput2 {
861
- id;
862
- createdAt;
863
- status;
864
- }, "BaseMessageOutput");
865
- _ts_decorate11([
866
- Field11(() => String),
867
- _ts_metadata11("design:type", String)
868
- ], BaseMessageOutput.prototype, "id", void 0);
869
- _ts_decorate11([
870
- Field11(() => Date),
871
- _ts_metadata11("design:type", typeof Date === "undefined" ? Object : Date)
872
- ], BaseMessageOutput.prototype, "createdAt", void 0);
873
- _ts_decorate11([
874
- Field11(() => MessageStatusUnion),
875
- _ts_metadata11("design:type", Object)
876
- ], BaseMessageOutput.prototype, "status", void 0);
877
- BaseMessageOutput = _ts_decorate11([
878
- InterfaceType({
879
- resolveType(value) {
880
- if (value.hasOwnProperty("content")) {
881
- return TextMessageOutput;
882
- } else if (value.hasOwnProperty("name")) {
883
- return ActionExecutionMessageOutput;
884
- } else if (value.hasOwnProperty("result")) {
885
- return ResultMessageOutput;
886
- } else if (value.hasOwnProperty("state")) {
887
- return AgentStateMessageOutput;
888
- }
889
- return void 0;
890
- }
891
- })
892
- ], BaseMessageOutput);
893
- var TextMessageOutput = class {
894
- role;
895
- content;
896
- };
897
- __name(TextMessageOutput, "TextMessageOutput");
898
- _ts_decorate11([
899
- Field11(() => MessageRole),
900
- _ts_metadata11("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
901
- ], TextMessageOutput.prototype, "role", void 0);
902
- _ts_decorate11([
903
- Field11(() => [
904
- String
905
- ]),
906
- _ts_metadata11("design:type", Array)
907
- ], TextMessageOutput.prototype, "content", void 0);
908
- TextMessageOutput = _ts_decorate11([
909
- ObjectType2({
910
- implements: BaseMessageOutput
911
- })
912
- ], TextMessageOutput);
913
- var ActionExecutionMessageOutput = class {
914
- name;
915
- scope;
916
- arguments;
917
- };
918
- __name(ActionExecutionMessageOutput, "ActionExecutionMessageOutput");
919
- _ts_decorate11([
920
- Field11(() => String),
921
- _ts_metadata11("design:type", String)
922
- ], ActionExecutionMessageOutput.prototype, "name", void 0);
923
- _ts_decorate11([
924
- Field11(() => ActionExecutionScope),
925
- _ts_metadata11("design:type", typeof ActionExecutionScope === "undefined" ? Object : ActionExecutionScope)
926
- ], ActionExecutionMessageOutput.prototype, "scope", void 0);
927
- _ts_decorate11([
928
- Field11(() => [
929
- String
930
- ]),
931
- _ts_metadata11("design:type", Array)
932
- ], ActionExecutionMessageOutput.prototype, "arguments", void 0);
933
- ActionExecutionMessageOutput = _ts_decorate11([
934
- ObjectType2({
935
- implements: BaseMessageOutput
936
- })
937
- ], ActionExecutionMessageOutput);
938
- var ResultMessageOutput = class {
939
- actionExecutionId;
940
- actionName;
941
- result;
942
- };
943
- __name(ResultMessageOutput, "ResultMessageOutput");
944
- _ts_decorate11([
945
- Field11(() => String),
946
- _ts_metadata11("design:type", String)
947
- ], ResultMessageOutput.prototype, "actionExecutionId", void 0);
948
- _ts_decorate11([
949
- Field11(() => String),
950
- _ts_metadata11("design:type", String)
951
- ], ResultMessageOutput.prototype, "actionName", void 0);
952
- _ts_decorate11([
953
- Field11(() => String),
954
- _ts_metadata11("design:type", String)
955
- ], ResultMessageOutput.prototype, "result", void 0);
956
- ResultMessageOutput = _ts_decorate11([
957
- ObjectType2({
958
- implements: BaseMessageOutput
959
- })
960
- ], ResultMessageOutput);
961
- var AgentStateMessageOutput = class {
962
- threadId;
963
- agentName;
964
- nodeName;
965
- runId;
966
- active;
967
- role;
968
- state;
969
- running;
970
- };
971
- __name(AgentStateMessageOutput, "AgentStateMessageOutput");
972
- _ts_decorate11([
973
- Field11(() => String),
974
- _ts_metadata11("design:type", String)
975
- ], AgentStateMessageOutput.prototype, "threadId", void 0);
976
- _ts_decorate11([
977
- Field11(() => String),
978
- _ts_metadata11("design:type", String)
979
- ], AgentStateMessageOutput.prototype, "agentName", void 0);
980
- _ts_decorate11([
981
- Field11(() => String),
982
- _ts_metadata11("design:type", String)
983
- ], AgentStateMessageOutput.prototype, "nodeName", void 0);
984
- _ts_decorate11([
985
- Field11(() => String),
986
- _ts_metadata11("design:type", String)
987
- ], AgentStateMessageOutput.prototype, "runId", void 0);
988
- _ts_decorate11([
989
- Field11(() => Boolean),
990
- _ts_metadata11("design:type", Boolean)
991
- ], AgentStateMessageOutput.prototype, "active", void 0);
992
- _ts_decorate11([
993
- Field11(() => MessageRole),
994
- _ts_metadata11("design:type", typeof MessageRole === "undefined" ? Object : MessageRole)
995
- ], AgentStateMessageOutput.prototype, "role", void 0);
996
- _ts_decorate11([
997
- Field11(() => String),
998
- _ts_metadata11("design:type", String)
999
- ], AgentStateMessageOutput.prototype, "state", void 0);
1000
- _ts_decorate11([
1001
- Field11(() => Boolean),
1002
- _ts_metadata11("design:type", Boolean)
1003
- ], AgentStateMessageOutput.prototype, "running", void 0);
1004
- AgentStateMessageOutput = _ts_decorate11([
1005
- ObjectType2({
1006
- implements: BaseMessageOutput
1007
- })
1008
- ], AgentStateMessageOutput);
1009
- var CopilotResponse = class {
1010
- threadId;
1011
- status;
1012
- runId;
1013
- messages;
1014
- };
1015
- __name(CopilotResponse, "CopilotResponse");
1016
- _ts_decorate11([
1017
- Field11(() => String),
1018
- _ts_metadata11("design:type", String)
1019
- ], CopilotResponse.prototype, "threadId", void 0);
1020
- _ts_decorate11([
1021
- Field11(() => ResponseStatusUnion),
1022
- _ts_metadata11("design:type", Object)
1023
- ], CopilotResponse.prototype, "status", void 0);
1024
- _ts_decorate11([
1025
- Field11({
1026
- nullable: true
1027
- }),
1028
- _ts_metadata11("design:type", String)
1029
- ], CopilotResponse.prototype, "runId", void 0);
1030
- _ts_decorate11([
1031
- Field11(() => [
1032
- BaseMessageOutput
1033
- ]),
1034
- _ts_metadata11("design:type", Array)
1035
- ], CopilotResponse.prototype, "messages", void 0);
1036
- CopilotResponse = _ts_decorate11([
1037
- ObjectType2()
1038
- ], CopilotResponse);
1039
-
1040
- // src/graphql/resolvers/copilot.resolver.ts
1041
- import { Repeater } from "graphql-yoga";
1042
-
1043
- // src/service-adapters/events.ts
1044
- import { randomId as randomId3 } from "@copilotkit/shared";
1045
- import { of, concat, map, scan as scan2, concatMap, ReplaySubject as ReplaySubject2, firstValueFrom, from as from2 } from "rxjs";
1046
-
1047
- // src/lib/telemetry-client.ts
1048
- import { TelemetryClient } from "@copilotkit/shared";
1049
-
1050
- // src/lib/runtime/remote-action-constructors.ts
1051
- import { createHash as createHash2 } from "crypto";
1052
-
1053
- // src/agents/langgraph/event-source.ts
1054
- import { ReplaySubject, scan, mergeMap, catchError } from "rxjs";
1055
-
1056
- // src/agents/langgraph/events.ts
1057
- var LangGraphEventTypes;
1058
- (function(LangGraphEventTypes2) {
1059
- LangGraphEventTypes2["OnChainStart"] = "on_chain_start";
1060
- LangGraphEventTypes2["OnChainStream"] = "on_chain_stream";
1061
- LangGraphEventTypes2["OnChainEnd"] = "on_chain_end";
1062
- LangGraphEventTypes2["OnChatModelStart"] = "on_chat_model_start";
1063
- LangGraphEventTypes2["OnChatModelStream"] = "on_chat_model_stream";
1064
- LangGraphEventTypes2["OnChatModelEnd"] = "on_chat_model_end";
1065
- LangGraphEventTypes2["OnToolStart"] = "on_tool_start";
1066
- LangGraphEventTypes2["OnToolEnd"] = "on_tool_end";
1067
- LangGraphEventTypes2["OnCopilotKitStateSync"] = "on_copilotkit_state_sync";
1068
- LangGraphEventTypes2["OnCopilotKitEmitMessage"] = "on_copilotkit_emit_message";
1069
- LangGraphEventTypes2["OnCopilotKitEmitToolCall"] = "on_copilotkit_emit_tool_call";
1070
- LangGraphEventTypes2["OnCustomEvent"] = "on_custom_event";
1071
- })(LangGraphEventTypes || (LangGraphEventTypes = {}));
1072
- var CustomEventNames;
1073
- (function(CustomEventNames2) {
1074
- CustomEventNames2["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
1075
- CustomEventNames2["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
1076
- CustomEventNames2["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
1077
- CustomEventNames2["CopilotKitExit"] = "copilotkit_exit";
1078
- })(CustomEventNames || (CustomEventNames = {}));
1079
-
1080
- // src/agents/langgraph/event-source.ts
1081
- import { randomId } from "@copilotkit/shared";
1082
- var RemoteLangGraphEventSource = class {
1083
- eventStream$ = new ReplaySubject();
1084
- shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
1085
- if (typeof shouldEmitToolCalls === "boolean") {
1086
- return shouldEmitToolCalls;
1087
- }
1088
- if (Array.isArray(shouldEmitToolCalls)) {
1089
- return shouldEmitToolCalls.includes(toolCallName);
1090
- }
1091
- return shouldEmitToolCalls === toolCallName;
1092
- }
1093
- processLangGraphEvents() {
1094
- let lastEventWithState = null;
1095
- return this.eventStream$.pipe(scan((acc, event) => {
1096
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1097
- if (event.event === LangGraphEventTypes.OnChatModelStream) {
1098
- 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);
1099
- if (typeof content === "string") {
1100
- acc.content = content;
1101
- } else if (Array.isArray(content) && content.length > 0) {
1102
- acc.content = content[0].text;
1103
- } else {
1104
- acc.content = null;
1105
- }
1106
- const toolCallChunks = (
1107
- // @ts-expect-error -- LangGraph Platform implementation stores data outside of kwargs
1108
- ((_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)
1109
- );
1110
- 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);
1111
- if (toolCallChunks && toolCallChunks.length > 0) {
1112
- acc.prevToolCallMessageId = acc.toolCallMessageId;
1113
- acc.toolCallMessageId = toolCallMessageId;
1114
- if ((_p = toolCallChunks[0]) == null ? void 0 : _p.name) {
1115
- acc.toolCallName = toolCallChunks[0].name;
1116
- }
1117
- if ((_q = toolCallChunks[0]) == null ? void 0 : _q.id) {
1118
- acc.toolCallId = toolCallChunks[0].id;
1119
- }
1120
- acc.prevMessageId = acc.messageId;
1121
- acc.messageId = toolCallMessageId;
1122
- } else if (acc.content && acc.content != "") {
1123
- acc.prevMessageId = acc.messageId;
1124
- acc.messageId = toolCallMessageId;
1125
- } else {
1126
- acc.prevToolCallMessageId = acc.toolCallMessageId;
1127
- acc.prevMessageId = acc.messageId;
1128
- }
1129
- } else {
1130
- acc.prevToolCallMessageId = acc.toolCallMessageId;
1131
- acc.toolCallMessageId = null;
1132
- acc.prevMessageId = acc.messageId;
1133
- acc.messageId = null;
1134
- acc.toolCallName = null;
1135
- }
1136
- acc.event = event;
1137
- lastEventWithState = acc;
1138
- return acc;
1139
- }, {
1140
- event: null,
1141
- toolCallId: null,
1142
- toolCallMessageId: null,
1143
- prevToolCallMessageId: null,
1144
- messageId: null,
1145
- toolCallName: null,
1146
- prevMessageId: null,
1147
- content: null
1148
- }), mergeMap((eventWithState) => {
1149
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1150
- const events = [];
1151
- let shouldEmitMessages = true;
1152
- let shouldEmitToolCalls = false;
1153
- if (eventWithState.event.event == LangGraphEventTypes.OnChatModelStream) {
1154
- if ("copilotkit:emit-tool-calls" in (eventWithState.event.metadata || {})) {
1155
- shouldEmitToolCalls = eventWithState.event.metadata["copilotkit:emit-tool-calls"];
1156
- }
1157
- if ("copilotkit:emit-messages" in (eventWithState.event.metadata || {})) {
1158
- shouldEmitMessages = eventWithState.event.metadata["copilotkit:emit-messages"];
1159
- }
1160
- }
1161
- if (eventWithState.prevToolCallMessageId !== null && eventWithState.prevToolCallMessageId !== eventWithState.toolCallMessageId && this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1162
- events.push({
1163
- type: RuntimeEventTypes.ActionExecutionEnd
1164
- });
1165
- }
1166
- if (eventWithState.prevMessageId !== null && eventWithState.prevMessageId !== eventWithState.messageId && shouldEmitMessages) {
1167
- events.push({
1168
- type: RuntimeEventTypes.TextMessageEnd
1169
- });
1170
- }
1171
- switch (eventWithState.event.event) {
1172
- case LangGraphEventTypes.OnCustomEvent:
1173
- if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1174
- events.push({
1175
- type: RuntimeEventTypes.TextMessageStart,
1176
- messageId: eventWithState.event.data.message_id
1177
- });
1178
- events.push({
1179
- type: RuntimeEventTypes.TextMessageContent,
1180
- content: eventWithState.event.data.message
1181
- });
1182
- events.push({
1183
- type: RuntimeEventTypes.TextMessageEnd
1184
- });
1185
- } else if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1186
- events.push({
1187
- type: RuntimeEventTypes.ActionExecutionStart,
1188
- actionExecutionId: eventWithState.event.data.id,
1189
- actionName: eventWithState.event.data.name
1190
- });
1191
- events.push({
1192
- type: RuntimeEventTypes.ActionExecutionArgs,
1193
- args: JSON.stringify(eventWithState.event.data.args)
1194
- });
1195
- events.push({
1196
- type: RuntimeEventTypes.ActionExecutionEnd
1197
- });
1198
- }
1199
- break;
1200
- case LangGraphEventTypes.OnCopilotKitStateSync:
1201
- events.push({
1202
- type: RuntimeEventTypes.AgentStateMessage,
1203
- threadId: eventWithState.event.thread_id,
1204
- role: eventWithState.event.role,
1205
- agentName: eventWithState.event.agent_name,
1206
- nodeName: eventWithState.event.node_name,
1207
- runId: eventWithState.event.run_id,
1208
- active: eventWithState.event.active,
1209
- state: JSON.stringify(eventWithState.event.state),
1210
- running: eventWithState.event.running
1211
- });
1212
- break;
1213
- case LangGraphEventTypes.OnToolEnd:
1214
- break;
1215
- case LangGraphEventTypes.OnChatModelStream:
1216
- if (eventWithState.toolCallMessageId !== null && eventWithState.prevToolCallMessageId !== eventWithState.toolCallMessageId) {
1217
- if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1218
- events.push({
1219
- type: RuntimeEventTypes.ActionExecutionStart,
1220
- actionExecutionId: eventWithState.toolCallMessageId,
1221
- actionName: eventWithState.toolCallName,
1222
- scope: "client"
1223
- });
1224
- }
1225
- } else if (eventWithState.messageId !== null && eventWithState.prevMessageId !== eventWithState.messageId) {
1226
- if (shouldEmitMessages) {
1227
- events.push({
1228
- type: RuntimeEventTypes.TextMessageStart,
1229
- messageId: eventWithState.messageId
1230
- });
1231
- }
1232
- }
1233
- 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
1234
- ((_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);
1235
- const content = eventWithState.content;
1236
- if (args) {
1237
- if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
1238
- events.push({
1239
- type: RuntimeEventTypes.ActionExecutionArgs,
1240
- args
1241
- });
1242
- }
1243
- } else if (eventWithState.messageId !== null && content) {
1244
- if (shouldEmitMessages) {
1245
- events.push({
1246
- type: RuntimeEventTypes.TextMessageContent,
1247
- content
1248
- });
1249
- }
1250
- }
1251
- break;
1252
- }
1253
- return events;
1254
- }), catchError((error) => {
1255
- console.error(error);
1256
- const events = [];
1257
- if (lastEventWithState == null ? void 0 : lastEventWithState.messageId) {
1258
- events.push({
1259
- type: RuntimeEventTypes.TextMessageEnd
1260
- });
1261
- }
1262
- if (lastEventWithState == null ? void 0 : lastEventWithState.toolCallMessageId) {
1263
- events.push({
1264
- type: RuntimeEventTypes.ActionExecutionEnd
1265
- });
1266
- }
1267
- const messageId = randomId();
1268
- events.push({
1269
- type: RuntimeEventTypes.TextMessageStart,
1270
- messageId
1271
- });
1272
- events.push({
1273
- type: RuntimeEventTypes.TextMessageContent,
1274
- content: "\u274C An error occurred. Please try again."
1275
- });
1276
- events.push({
1277
- type: RuntimeEventTypes.TextMessageEnd
1278
- });
1279
- return events;
1280
- }));
1281
- }
1282
- };
1283
- __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
1284
-
1285
- // src/lib/runtime/remote-lg-action.ts
1286
- import { Client } from "@langchain/langgraph-sdk";
1287
- import { createHash, randomUUID } from "crypto";
1288
- import { parse as parsePartialJson } from "partial-json";
1289
- async function execute(args) {
1290
- return new ReadableStream({
1291
- async start(controller) {
1292
- try {
1293
- await streamEvents(controller, args);
1294
- controller.close();
1295
- } catch (err) {
1296
- }
1297
- }
1298
- });
1299
- }
1300
- __name(execute, "execute");
1301
- async function streamEvents(controller, args) {
1302
- var _a, _b, _c, _d, _e, _f;
1303
- const { deploymentUrl, langsmithApiKey, threadId: agrsInitialThreadId, agent, nodeName: initialNodeName, state: initialState, messages, actions, logger: logger2 } = args;
1304
- let nodeName = initialNodeName;
1305
- let state = initialState;
1306
- const { name, assistantId: initialAssistantId } = agent;
1307
- const client = new Client({
1308
- apiUrl: deploymentUrl,
1309
- apiKey: langsmithApiKey
1310
- });
1311
- let initialThreadId = agrsInitialThreadId;
1312
- const wasInitiatedWithExistingThread = !!initialThreadId;
1313
- if (initialThreadId && initialThreadId.startsWith("ck-")) {
1314
- initialThreadId = initialThreadId.substring(3);
1315
- }
1316
- const assistants = await client.assistants.search();
1317
- const retrievedAssistant = assistants.find((a) => a.name === name);
1318
- const threadId = initialThreadId ?? randomUUID();
1319
- if (initialThreadId === threadId) {
1320
- await client.threads.get(threadId);
1321
- } else {
1322
- await client.threads.create({
1323
- threadId
1324
- });
1325
- }
1326
- let agentState = {
1327
- values: {}
1328
- };
1329
- if (wasInitiatedWithExistingThread) {
1330
- agentState = await client.threads.getState(threadId);
1331
- }
1332
- const agentStateValues = agentState.values;
1333
- state.messages = agentStateValues.messages;
1334
- const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
1335
- let formattedMessages = [];
1336
- try {
1337
- formattedMessages = formatMessages(messages);
1338
- } catch (e) {
1339
- logger2.error(e, `Error event thrown: ${e.message}`);
1340
- }
1341
- state = langGraphDefaultMergeState(state, formattedMessages, actions, name);
1342
- if (mode === "continue") {
1343
- await client.threads.updateState(threadId, {
1344
- values: state,
1345
- asNode: nodeName
1346
- });
1347
- }
1348
- const assistantId = initialAssistantId ?? (retrievedAssistant == null ? void 0 : retrievedAssistant.assistant_id);
1349
- if (!assistantId) {
1350
- console.error(`
1351
- No agent found for the agent name specified in CopilotKit provider
1352
- Please check your available agents or provide an agent ID in the LangGraph Platform endpoint definition.
1353
-
1354
-
1355
- These are the available agents: [${assistants.map((a) => `${a.name} (ID: ${a.assistant_id})`).join(", ")}]
1356
- `);
1357
- throw new Error("No agent id found");
1358
- }
1359
- const graphInfo = await client.assistants.getGraph(assistantId);
1360
- const streamInput = mode === "start" ? state : null;
1361
- let streamingStateExtractor = new StreamingStateExtractor([]);
1362
- let prevNodeName = null;
1363
- let emitIntermediateStateUntilEnd = null;
1364
- let shouldExit = false;
1365
- let externalRunId = null;
1366
- const streamResponse2 = client.runs.stream(threadId, assistantId, {
1367
- input: streamInput,
1368
- streamMode: [
1369
- "events",
1370
- "values"
1371
- ]
1372
- });
1373
- const emit = /* @__PURE__ */ __name((message) => controller.enqueue(new TextEncoder().encode(message)), "emit");
1374
- let latestStateValues = {};
1375
- let updatedState = state;
1376
- let manuallyEmittedState = null;
1377
- let streamInfo = {
1378
- hashedLgcKey: createHash("sha256").update(langsmithApiKey).digest("hex")
1379
- };
1380
- try {
1381
- telemetry_client_default.capture("oss.runtime.agent_execution_stream_started", {
1382
- hashedLgcKey: streamInfo.hashedLgcKey
1383
- });
1384
- for await (const chunk of streamResponse2) {
1385
- if (![
1386
- "events",
1387
- "values",
1388
- "error"
1389
- ].includes(chunk.event))
1390
- continue;
1391
- if (chunk.event === "error") {
1392
- logger2.error(chunk, `Error event thrown: ${chunk.data.message}`);
1393
- throw new Error(`Error event thrown: ${chunk.data.message}`);
1394
- }
1395
- if (chunk.event === "values") {
1396
- latestStateValues = chunk.data;
1397
- continue;
1398
- }
1399
- const event = chunk.data;
1400
- const currentNodeName = event.name;
1401
- const eventType = event.event;
1402
- const runId = event.metadata.run_id;
1403
- externalRunId = runId;
1404
- const metadata = event.metadata;
1405
- 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) != "") {
1406
- streamInfo.provider = (_f = (_e = event.data) == null ? void 0 : _e.output) == null ? void 0 : _f.model;
1407
- }
1408
- if (metadata.langgraph_host != null && metadata.langgraph_host != "") {
1409
- streamInfo.langGraphHost = metadata.langgraph_host;
1410
- }
1411
- if (metadata.langgraph_version != null && metadata.langgraph_version != "") {
1412
- streamInfo.langGraphVersion = metadata.langgraph_version;
1413
- }
1414
- shouldExit = shouldExit || eventType === LangGraphEventTypes.OnCustomEvent && event.name === CustomEventNames.CopilotKitExit;
1415
- const emitIntermediateState = metadata["copilotkit:emit-intermediate-state"];
1416
- const manuallyEmitIntermediateState = eventType === LangGraphEventTypes.OnCustomEvent && event.name === CustomEventNames.CopilotKitManuallyEmitIntermediateState;
1417
- const exitingNode = nodeName === currentNodeName && eventType === LangGraphEventTypes.OnChainEnd;
1418
- if (exitingNode) {
1419
- manuallyEmittedState = null;
1420
- }
1421
- if (graphInfo["nodes"].some((node) => node.id === currentNodeName)) {
1422
- nodeName = currentNodeName;
1423
- }
1424
- updatedState = manuallyEmittedState ?? latestStateValues;
1425
- if (!nodeName) {
1426
- continue;
1427
- }
1428
- if (manuallyEmitIntermediateState) {
1429
- manuallyEmittedState = event.data;
1430
- emit(getStateSyncEvent({
1431
- threadId,
1432
- runId,
1433
- agentName: agent.name,
1434
- nodeName,
1435
- state: manuallyEmittedState,
1436
- running: true,
1437
- active: true
1438
- }));
1439
- continue;
1440
- }
1441
- if (emitIntermediateState && emitIntermediateStateUntilEnd == null) {
1442
- emitIntermediateStateUntilEnd = nodeName;
1443
- }
1444
- if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStart) {
1445
- streamingStateExtractor = new StreamingStateExtractor(emitIntermediateState);
1446
- }
1447
- if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStream) {
1448
- streamingStateExtractor.bufferToolCalls(event);
1449
- }
1450
- if (emitIntermediateStateUntilEnd !== null) {
1451
- updatedState = {
1452
- ...updatedState,
1453
- ...streamingStateExtractor.extractState()
1454
- };
1455
- }
1456
- if (!emitIntermediateState && currentNodeName === emitIntermediateStateUntilEnd && eventType === LangGraphEventTypes.OnChainEnd) {
1457
- emitIntermediateStateUntilEnd = null;
1458
- }
1459
- if (JSON.stringify(updatedState) !== JSON.stringify(state) || prevNodeName != nodeName || exitingNode) {
1460
- state = updatedState;
1461
- prevNodeName = nodeName;
1462
- emit(getStateSyncEvent({
1463
- threadId,
1464
- runId,
1465
- agentName: agent.name,
1466
- nodeName,
1467
- state,
1468
- running: true,
1469
- active: !exitingNode
1470
- }));
1471
- }
1472
- emit(JSON.stringify(event) + "\n");
1473
- }
1474
- state = await client.threads.getState(threadId);
1475
- const isEndNode = state.next.length === 0;
1476
- nodeName = Object.keys(state.metadata.writes)[0];
1477
- telemetry_client_default.capture("oss.runtime.agent_execution_stream_ended", streamInfo);
1478
- emit(getStateSyncEvent({
1479
- threadId,
1480
- runId: externalRunId,
1481
- agentName: agent.name,
1482
- nodeName: isEndNode ? "__end__" : nodeName,
1483
- state: state.values,
1484
- running: !shouldExit,
1485
- active: false
1486
- }));
1487
- return Promise.resolve();
1488
- } catch (e) {
1489
- return Promise.resolve();
1490
- }
1491
- }
1492
- __name(streamEvents, "streamEvents");
1493
- function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active }) {
1494
- const stateWithoutMessages = Object.keys(state).reduce((acc, key) => {
1495
- if (key !== "messages") {
1496
- acc[key] = state[key];
1497
- }
1498
- return acc;
1499
- }, {});
1500
- return JSON.stringify({
1501
- event: LangGraphEventTypes.OnCopilotKitStateSync,
1502
- thread_id: threadId,
1503
- run_id: runId,
1504
- agent_name: agentName,
1505
- node_name: nodeName,
1506
- active,
1507
- state: stateWithoutMessages,
1508
- running,
1509
- role: "assistant"
1510
- }) + "\n";
1511
- }
1512
- __name(getStateSyncEvent, "getStateSyncEvent");
1513
- var StreamingStateExtractor = /* @__PURE__ */ __name(class StreamingStateExtractor2 {
1514
- emitIntermediateState;
1515
- toolCallBuffer;
1516
- currentToolCall;
1517
- previouslyParsableState;
1518
- constructor(emitIntermediateState) {
1519
- this.emitIntermediateState = emitIntermediateState;
1520
- this.toolCallBuffer = {};
1521
- this.currentToolCall = null;
1522
- this.previouslyParsableState = {};
1523
- }
1524
- bufferToolCalls(event) {
1525
- if (event.data.chunk.tool_call_chunks.length > 0) {
1526
- const chunk = event.data.chunk.tool_call_chunks[0];
1527
- if (chunk.name !== null && chunk.name !== void 0) {
1528
- this.currentToolCall = chunk.name;
1529
- this.toolCallBuffer[this.currentToolCall] = chunk.args;
1530
- } else if (this.currentToolCall !== null && this.currentToolCall !== void 0) {
1531
- this.toolCallBuffer[this.currentToolCall] += chunk.args;
1532
- }
1533
- }
1534
- }
1535
- getEmitStateConfig(currentToolName) {
1536
- for (const config of this.emitIntermediateState) {
1537
- const stateKey = config["state_key"];
1538
- const tool = config["tool"];
1539
- const toolArgument = config["tool_argument"];
1540
- if (currentToolName === tool) {
1541
- return [
1542
- toolArgument,
1543
- stateKey
1544
- ];
1545
- }
1546
- }
1547
- return [
1548
- null,
1549
- null
1550
- ];
1551
- }
1552
- extractState() {
1553
- const state = {};
1554
- for (const [key, value] of Object.entries(this.toolCallBuffer)) {
1555
- const [argumentName, stateKey] = this.getEmitStateConfig(key);
1556
- if (stateKey === null) {
1557
- continue;
1558
- }
1559
- let parsedValue;
1560
- try {
1561
- parsedValue = parsePartialJson(value);
1562
- } catch (error) {
1563
- if (key in this.previouslyParsableState) {
1564
- parsedValue = this.previouslyParsableState[key];
1565
- } else {
1566
- continue;
1567
- }
1568
- }
1569
- this.previouslyParsableState[key] = parsedValue;
1570
- if (!argumentName) {
1571
- state[stateKey] = parsedValue;
1572
- } else {
1573
- state[stateKey] = parsedValue[argumentName];
1574
- }
1575
- }
1576
- return state;
1577
- }
1578
- }, "StreamingStateExtractor");
1579
- function langGraphDefaultMergeState(state, messages, actions, agentName) {
1580
- if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
1581
- messages = messages.slice(1);
1582
- }
1583
- const mergedMessages = state.messages || [];
1584
- const existingMessageIds = new Set(mergedMessages.map((message) => message.id));
1585
- const existingToolCallResults = /* @__PURE__ */ new Set();
1586
- for (const message of mergedMessages) {
1587
- if ("tool_call_id" in message) {
1588
- existingToolCallResults.add(message.tool_call_id);
1589
- }
1590
- }
1591
- for (const message of messages) {
1592
- if ("tool_calls" in message && message.tool_calls.length > 0 && message.tool_calls[0].name === agentName) {
1593
- continue;
1594
- }
1595
- if ("name" in message && message.name === agentName) {
1596
- continue;
1597
- }
1598
- if (!existingMessageIds.has(message.id)) {
1599
- if ("tool_call_id" in message && existingToolCallResults.has(message.tool_call_id)) {
1600
- console.warn("Warning: Duplicate tool call result, skipping:", message.tool_call_id);
1601
- continue;
1602
- }
1603
- mergedMessages.push(message);
1604
- } else {
1605
- for (let i = 0; i < mergedMessages.length; i++) {
1606
- if (mergedMessages[i].id === message.id && message.role === "assistant") {
1607
- if (("tool_calls" in mergedMessages[i] || "additional_kwargs" in mergedMessages[i]) && mergedMessages[i].content) {
1608
- message.tool_calls = mergedMessages[i]["tool_calls"];
1609
- message.additional_kwargs = mergedMessages[i].additional_kwargs;
1610
- }
1611
- mergedMessages[i] = message;
1612
- }
1613
- }
1614
- }
1615
- }
1616
- for (let i = 0; i < mergedMessages.length - 1; i++) {
1617
- const currentMessage = mergedMessages[i];
1618
- const nextMessage = mergedMessages[i + 1];
1619
- if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0 && "tool_call_id" in nextMessage) {
1620
- nextMessage.tool_call_id = currentMessage.tool_calls[0].id;
1621
- }
1622
- }
1623
- const correctedMessages = [];
1624
- for (let i = 0; i < mergedMessages.length; i++) {
1625
- const currentMessage = mergedMessages[i];
1626
- const nextMessage = mergedMessages[i + 1] || null;
1627
- const prevMessage = mergedMessages[i - 1] || null;
1628
- if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0) {
1629
- if (!nextMessage) {
1630
- console.warn("No next message to auto-correct tool call, skipping:", currentMessage.tool_calls[0].id);
1631
- continue;
1632
- }
1633
- if (!("tool_call_id" in nextMessage) || nextMessage.tool_call_id !== currentMessage.tool_calls[0].id) {
1634
- const toolMessage = mergedMessages.find((m) => "tool_call_id" in m && m.tool_call_id === currentMessage.tool_calls[0].id);
1635
- if (toolMessage) {
1636
- console.warn("Auto-corrected tool call alignment issue:", currentMessage.tool_calls[0].id);
1637
- correctedMessages.push(currentMessage, toolMessage);
1638
- continue;
1639
- } else {
1640
- console.warn("No corresponding tool call result found for tool call, skipping:", currentMessage.tool_calls[0].id);
1641
- continue;
1642
- }
1643
- }
1644
- correctedMessages.push(currentMessage);
1645
- continue;
1646
- }
1647
- if ("tool_call_id" in currentMessage) {
1648
- if (!prevMessage || !("tool_calls" in prevMessage)) {
1649
- console.warn("No previous tool call, skipping tool call result:", currentMessage.id);
1650
- continue;
1651
- }
1652
- if (prevMessage.tool_calls && prevMessage.tool_calls[0].id !== currentMessage.tool_call_id) {
1653
- console.warn("Tool call id is incorrect, skipping tool call result:", currentMessage.id);
1654
- continue;
1655
- }
1656
- correctedMessages.push(currentMessage);
1657
- continue;
1658
- }
1659
- correctedMessages.push(currentMessage);
1660
- }
1661
- return {
1662
- ...state,
1663
- messages: correctedMessages,
1664
- copilotkit: {
1665
- actions
1666
- }
1667
- };
1668
- }
1669
- __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1670
- function formatMessages(messages) {
1671
- return messages.map((message) => {
1672
- if (message.isTextMessage() && message.role === "assistant") {
1673
- return message;
1674
- }
1675
- if (message.isTextMessage() && message.role === "system") {
1676
- return message;
1677
- }
1678
- if (message.isTextMessage() && message.role === "user") {
1679
- return message;
1680
- }
1681
- if (message.isActionExecutionMessage()) {
1682
- const toolCall = {
1683
- name: message.name,
1684
- args: message.arguments,
1685
- id: message.id
1686
- };
1687
- return {
1688
- type: message.type,
1689
- content: "",
1690
- tool_calls: [
1691
- toolCall
1692
- ],
1693
- role: MessageRole.assistant,
1694
- id: message.id
1695
- };
1696
- }
1697
- if (message.isResultMessage()) {
1698
- return {
1699
- type: message.type,
1700
- content: message.result,
1701
- id: message.id,
1702
- tool_call_id: message.actionExecutionId,
1703
- name: message.actionName,
1704
- role: MessageRole.tool
1705
- };
1706
- }
1707
- throw new Error(`Unknown message type ${message.type}`);
1708
- });
1709
- }
1710
- __name(formatMessages, "formatMessages");
1711
-
1712
- // src/lib/runtime/remote-action-constructors.ts
1713
- function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
1714
- const agents = endpoint.agents.map((agent) => ({
1715
- name: agent.name,
1716
- description: agent.description,
1717
- parameters: [],
1718
- handler: async (_args) => {
1719
- },
1720
- langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1721
- var _a;
1722
- logger2.debug({
1723
- actionName: agent.name
1724
- }, "Executing LangGraph Platform agent");
1725
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
1726
- agentExecution: true,
1727
- type: "langgraph-platform",
1728
- agentsAmount: endpoint.agents.length,
1729
- hashedLgcKey: createHash2("sha256").update(endpoint.langsmithApiKey).digest("hex")
1730
- });
1731
- let state = {};
1732
- if (agentStates) {
1733
- const jsonState = (_a = agentStates.find((state2) => state2.agentName === name)) == null ? void 0 : _a.state;
1734
- if (jsonState) {
1735
- state = JSON.parse(jsonState);
1736
- }
1737
- }
1738
- try {
1739
- const response = await execute({
1740
- logger: logger2,
1741
- deploymentUrl: endpoint.deploymentUrl,
1742
- langsmithApiKey: endpoint.langsmithApiKey,
1743
- agent,
1744
- threadId,
1745
- nodeName,
1746
- messages,
1747
- state,
1748
- properties: graphqlContext.properties,
1749
- actions: actionInputsWithoutAgents.map((action) => ({
1750
- name: action.name,
1751
- description: action.description,
1752
- parameters: JSON.parse(action.jsonSchema)
1753
- }))
1754
- });
1755
- const eventSource = new RemoteLangGraphEventSource();
1756
- streamResponse(response, eventSource.eventStream$);
1757
- return eventSource.processLangGraphEvents();
1758
- } catch (error) {
1759
- logger2.error({
1760
- url: endpoint.deploymentUrl,
1761
- status: 500,
1762
- body: error.message
1763
- }, "Failed to execute LangGraph Platform agent");
1764
- throw new Error("Failed to execute LangGraph Platform agent");
1765
- }
1766
- }
1767
- }));
1768
- return [
1769
- ...agents
1770
- ];
1771
- }
1772
- __name(constructLGCRemoteAction, "constructLGCRemoteAction");
1773
- function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
1774
- const actions = json["actions"].map((action) => ({
1775
- name: action.name,
1776
- description: action.description,
1777
- parameters: action.parameters,
1778
- handler: async (args) => {
1779
- logger2.debug({
1780
- actionName: action.name,
1781
- args
1782
- }, "Executing remote action");
1783
- const headers = createHeaders(onBeforeRequest, graphqlContext);
1784
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
1785
- agentExecution: false,
1786
- type: "self-hosted",
1787
- agentsAmount: json["agents"].length
1788
- });
1789
- try {
1790
- const response = await fetch(`${url}/actions/execute`, {
1791
- method: "POST",
1792
- headers,
1793
- body: JSON.stringify({
1794
- name: action.name,
1795
- arguments: args,
1796
- properties: graphqlContext.properties
1797
- })
1798
- });
1799
- if (!response.ok) {
1800
- logger2.error({
1801
- url,
1802
- status: response.status,
1803
- body: await response.text()
1804
- }, "Failed to execute remote action");
1805
- return "Failed to execute remote action";
1806
- }
1807
- const requestResult = await response.json();
1808
- const result = requestResult["result"];
1809
- logger2.debug({
1810
- actionName: action.name,
1811
- result
1812
- }, "Executed remote action");
1813
- return result;
1814
- } catch (error) {
1815
- logger2.error({
1816
- error: error.message ? error.message : error + ""
1817
- }, "Failed to execute remote action");
1818
- return "Failed to execute remote action";
1819
- }
1820
- }
1821
- }));
1822
- const agents = json["agents"].map((agent) => ({
1823
- name: agent.name,
1824
- description: agent.description,
1825
- parameters: [],
1826
- handler: async (_args) => {
1827
- },
1828
- langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1829
- var _a;
1830
- logger2.debug({
1831
- actionName: agent.name
1832
- }, "Executing remote agent");
1833
- const headers = createHeaders(onBeforeRequest, graphqlContext);
1834
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
1835
- agentExecution: true,
1836
- type: "self-hosted",
1837
- agentsAmount: json["agents"].length
1838
- });
1839
- let state = {};
1840
- if (agentStates) {
1841
- const jsonState = (_a = agentStates.find((state2) => state2.agentName === name)) == null ? void 0 : _a.state;
1842
- if (jsonState) {
1843
- state = JSON.parse(jsonState);
1844
- }
1845
- }
1846
- const response = await fetch(`${url}/agents/execute`, {
1847
- method: "POST",
1848
- headers,
1849
- body: JSON.stringify({
1850
- name,
1851
- threadId,
1852
- nodeName,
1853
- messages,
1854
- state,
1855
- properties: graphqlContext.properties,
1856
- actions: actionInputsWithoutAgents.map((action) => ({
1857
- name: action.name,
1858
- description: action.description,
1859
- parameters: JSON.parse(action.jsonSchema)
1860
- }))
1861
- })
1862
- });
1863
- if (!response.ok) {
1864
- logger2.error({
1865
- url,
1866
- status: response.status,
1867
- body: await response.text()
1868
- }, "Failed to execute remote agent");
1869
- throw new Error("Failed to execute remote agent");
1870
- }
1871
- const eventSource = new RemoteLangGraphEventSource();
1872
- streamResponse(response.body, eventSource.eventStream$);
1873
- return eventSource.processLangGraphEvents();
1874
- }
1875
- }));
1876
- return [
1877
- ...actions,
1878
- ...agents
1879
- ];
1880
- }
1881
- __name(constructRemoteActions, "constructRemoteActions");
1882
- async function streamResponse(response, eventStream$) {
1883
- const reader = response.getReader();
1884
- const decoder = new TextDecoder();
1885
- let buffer = [];
1886
- function flushBuffer() {
1887
- const currentBuffer = buffer.join("");
1888
- if (currentBuffer.trim().length === 0) {
1889
- return;
1890
- }
1891
- const parts = currentBuffer.split("\n");
1892
- if (parts.length === 0) {
1893
- return;
1894
- }
1895
- const lastPartIsComplete = currentBuffer.endsWith("\n");
1896
- buffer = [];
1897
- if (!lastPartIsComplete) {
1898
- buffer.push(parts.pop());
1899
- }
1900
- parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1901
- eventStream$.next(JSON.parse(part));
1902
- });
1903
- }
1904
- __name(flushBuffer, "flushBuffer");
1905
- try {
1906
- while (true) {
1907
- const { done, value } = await reader.read();
1908
- if (!done) {
1909
- buffer.push(decoder.decode(value, {
1910
- stream: true
1911
- }));
1912
- }
1913
- flushBuffer();
1914
- if (done) {
1915
- break;
1916
- }
1917
- }
1918
- } catch (error) {
1919
- console.error("Error in stream", error);
1920
- eventStream$.error(error);
1921
- return;
1922
- }
1923
- eventStream$.complete();
1924
- }
1925
- __name(streamResponse, "streamResponse");
1926
- function createHeaders(onBeforeRequest, graphqlContext) {
1927
- const headers = {
1928
- "Content-Type": "application/json"
1929
- };
1930
- if (onBeforeRequest) {
1931
- const { headers: additionalHeaders } = onBeforeRequest({
1932
- ctx: graphqlContext
1933
- });
1934
- if (additionalHeaders) {
1935
- Object.assign(headers, additionalHeaders);
1936
- }
1937
- }
1938
- return headers;
1939
- }
1940
- __name(createHeaders, "createHeaders");
1941
-
1942
- // src/lib/runtime/remote-actions.ts
1943
- var EndpointType;
1944
- (function(EndpointType2) {
1945
- EndpointType2["CopilotKit"] = "copilotKit";
1946
- EndpointType2["LangGraphPlatform"] = "langgraph-platform";
1947
- })(EndpointType || (EndpointType = {}));
1948
- function isLangGraphAgentAction(action) {
1949
- if (!action) {
1950
- return false;
1951
- }
1952
- return typeof action.langGraphAgentHandler === "function";
1953
- }
1954
- __name(isLangGraphAgentAction, "isLangGraphAgentAction");
1955
- async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
1956
- logger2.debug({
1957
- url
1958
- }, "Fetching actions from url");
1959
- const headers = createHeaders(onBeforeRequest, graphqlContext);
1960
- try {
1961
- const response = await fetch(`${url}/info`, {
1962
- method: "POST",
1963
- headers,
1964
- body: JSON.stringify({
1965
- properties: graphqlContext.properties,
1966
- frontendUrl
1967
- })
1968
- });
1969
- if (!response.ok) {
1970
- logger2.error({
1971
- url,
1972
- status: response.status,
1973
- body: await response.text()
1974
- }, "Failed to fetch actions from url");
1975
- return {
1976
- actions: [],
1977
- agents: []
1978
- };
1979
- }
1980
- const json = await response.json();
1981
- logger2.debug({
1982
- json
1983
- }, "Fetched actions from url");
1984
- return json;
1985
- } catch (error) {
1986
- logger2.error({
1987
- error: error.message ? error.message : error + ""
1988
- }, "Failed to fetch actions from url");
1989
- return {
1990
- actions: [],
1991
- agents: []
1992
- };
1993
- }
1994
- }
1995
- __name(fetchRemoteInfo, "fetchRemoteInfo");
1996
- async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
1997
- const logger2 = graphqlContext.logger.child({
1998
- component: "remote-actions.fetchRemoteActions"
1999
- });
2000
- logger2.debug({
2001
- remoteEndpointDefinitions
2002
- }, "Fetching from remote endpoints");
2003
- const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
2004
- if (value.type === "langgraph-platform") {
2005
- return value;
2006
- }
2007
- return index === self.findIndex((t) => t.url === value.url);
2008
- });
2009
- const result = await Promise.all(filtered.map(async (endpoint) => {
2010
- if (endpoint.type === "langgraph-platform") {
2011
- return constructLGCRemoteAction({
2012
- endpoint,
2013
- messages,
2014
- graphqlContext,
2015
- logger: logger2.child({
2016
- component: "remote-actions.constructLGCRemoteAction",
2017
- endpoint
2018
- }),
2019
- agentStates
2020
- });
2021
- }
2022
- const json = await fetchRemoteInfo({
2023
- url: endpoint.url,
2024
- onBeforeRequest: endpoint.onBeforeRequest,
2025
- graphqlContext,
2026
- logger: logger2.child({
2027
- component: "remote-actions.fetchActionsFromUrl",
2028
- endpoint
2029
- }),
2030
- frontendUrl
2031
- });
2032
- return constructRemoteActions({
2033
- json,
2034
- messages,
2035
- url: endpoint.url,
2036
- onBeforeRequest: endpoint.onBeforeRequest,
2037
- graphqlContext,
2038
- logger: logger2.child({
2039
- component: "remote-actions.constructActions",
2040
- endpoint
2041
- }),
2042
- agentStates
2043
- });
2044
- }));
2045
- return result.flat();
2046
- }
2047
- __name(setupRemoteActions, "setupRemoteActions");
2048
-
2049
- // src/lib/telemetry-client.ts
2050
- import { createHash as createHash3 } from "crypto";
2051
-
2052
- // src/lib/runtime/copilot-runtime.ts
2053
- import { actionParametersToJsonSchema, randomId as randomId2 } from "@copilotkit/shared";
2054
-
2055
- // src/service-adapters/conversion.ts
2056
- import { plainToInstance } from "class-transformer";
2057
- function convertGqlInputToMessages(inputMessages) {
2058
- const messages = [];
2059
- for (const message of inputMessages) {
2060
- if (message.textMessage) {
2061
- messages.push(plainToInstance(TextMessage, {
2062
- id: message.id,
2063
- createdAt: message.createdAt,
2064
- role: message.textMessage.role,
2065
- content: message.textMessage.content
2066
- }));
2067
- } else if (message.actionExecutionMessage) {
2068
- messages.push(plainToInstance(ActionExecutionMessage, {
2069
- id: message.id,
2070
- createdAt: message.createdAt,
2071
- name: message.actionExecutionMessage.name,
2072
- arguments: JSON.parse(message.actionExecutionMessage.arguments),
2073
- scope: message.actionExecutionMessage.scope
2074
- }));
2075
- } else if (message.resultMessage) {
2076
- messages.push(plainToInstance(ResultMessage, {
2077
- id: message.id,
2078
- createdAt: message.createdAt,
2079
- actionExecutionId: message.resultMessage.actionExecutionId,
2080
- actionName: message.resultMessage.actionName,
2081
- result: message.resultMessage.result
2082
- }));
2083
- } else if (message.agentStateMessage) {
2084
- messages.push(plainToInstance(AgentStateMessage, {
2085
- id: message.id,
2086
- threadId: message.agentStateMessage.threadId,
2087
- createdAt: message.createdAt,
2088
- agentName: message.agentStateMessage.agentName,
2089
- nodeName: message.agentStateMessage.nodeName,
2090
- runId: message.agentStateMessage.runId,
2091
- active: message.agentStateMessage.active,
2092
- role: message.agentStateMessage.role,
2093
- state: JSON.parse(message.agentStateMessage.state),
2094
- running: message.agentStateMessage.running
2095
- }));
2096
- }
2097
- }
2098
- return messages;
2099
- }
2100
- __name(convertGqlInputToMessages, "convertGqlInputToMessages");
2101
-
2102
- // src/lib/runtime/copilot-runtime.ts
2103
- import { from } from "rxjs";
2104
- var CopilotRuntime = class {
2105
- actions;
2106
- remoteEndpointDefinitions;
2107
- langserve = [];
2108
- onBeforeRequest;
2109
- onAfterRequest;
2110
- constructor(params) {
2111
- var _a, _b;
2112
- this.actions = (params == null ? void 0 : params.actions) || [];
2113
- for (const chain of (params == null ? void 0 : params.langserve) || []) {
2114
- const remoteChain = new RemoteChain(chain);
2115
- this.langserve.push(remoteChain.toAction());
2116
- }
2117
- this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) ?? (params == null ? void 0 : params.remoteActions) ?? [];
2118
- this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
2119
- this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
2120
- }
2121
- async processRuntimeRequest(request) {
2122
- var _a;
2123
- const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, agentSession, url } = request;
2124
- const eventSource = new RuntimeEventSource();
2125
- try {
2126
- if (agentSession) {
2127
- return await this.processAgentRequest(request);
2128
- }
2129
- const messages = rawMessages.filter((message) => !message.agentStateMessage);
2130
- const inputMessages = convertGqlInputToMessages(messages);
2131
- const serverSideActions = await this.getServerSideActions(request);
2132
- const serverSideActionsInput = serverSideActions.map((action) => ({
2133
- name: action.name,
2134
- description: action.description,
2135
- jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
2136
- }));
2137
- const actionInputs = flattenToolCallsNoDuplicates([
2138
- ...serverSideActionsInput,
2139
- ...clientSideActionsInput.filter(
2140
- // Filter remote actions from CopilotKit core loop
2141
- (action) => action.available !== ActionInputAvailability.remote
2142
- )
2143
- ]);
2144
- await ((_a = this.onBeforeRequest) == null ? void 0 : _a.call(this, {
2145
- threadId,
2146
- runId,
2147
- inputMessages,
2148
- properties: graphqlContext.properties,
2149
- url
2150
- }));
2151
- const result = await serviceAdapter.process({
2152
- messages: inputMessages,
2153
- actions: actionInputs,
2154
- threadId,
2155
- runId,
2156
- eventSource,
2157
- forwardedParameters
2158
- });
2159
- outputMessagesPromise.then((outputMessages) => {
2160
- var _a2;
2161
- (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
2162
- threadId: result.threadId,
2163
- runId: result.runId,
2164
- inputMessages,
2165
- outputMessages,
2166
- properties: graphqlContext.properties,
2167
- url
2168
- });
2169
- }).catch((_error) => {
2170
- });
2171
- return {
2172
- threadId: result.threadId,
2173
- runId: result.runId,
2174
- eventSource,
2175
- serverSideActions,
2176
- actionInputsWithoutAgents: actionInputs.filter((action) => (
2177
- // TODO-AGENTS: do not exclude ALL server side actions
2178
- !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
2179
- ))
2180
- };
2181
- } catch (error) {
2182
- console.error("Error getting response:", error);
2183
- eventSource.sendErrorMessageToChat();
2184
- return {
2185
- threadId: threadId || randomId2(),
2186
- runId: runId || randomId2(),
2187
- eventSource,
2188
- serverSideActions: [],
2189
- actionInputsWithoutAgents: []
2190
- };
2191
- }
2192
- }
2193
- async processAgentRequest(request) {
2194
- var _a;
2195
- const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession } = request;
2196
- const { threadId, agentName, nodeName } = agentSession;
2197
- const serverSideActions = await this.getServerSideActions(request);
2198
- const messages = convertGqlInputToMessages(rawMessages);
2199
- const agent = serverSideActions.find((action) => action.name === agentName && isLangGraphAgentAction(action));
2200
- if (!agent) {
2201
- throw new Error(`Agent ${agentName} not found`);
2202
- }
2203
- const serverSideActionsInput = serverSideActions.filter((action) => !isLangGraphAgentAction(action)).map((action) => ({
2204
- name: action.name,
2205
- description: action.description,
2206
- jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
2207
- }));
2208
- const actionInputsWithoutAgents = flattenToolCallsNoDuplicates([
2209
- ...serverSideActionsInput,
2210
- ...request.actions
2211
- ]);
2212
- await ((_a = this.onBeforeRequest) == null ? void 0 : _a.call(this, {
2213
- threadId,
2214
- runId: void 0,
2215
- inputMessages: messages,
2216
- properties: graphqlContext.properties
2217
- }));
2218
- try {
2219
- const eventSource = new RuntimeEventSource();
2220
- const stream = await agent.langGraphAgentHandler({
2221
- name: agentName,
2222
- threadId,
2223
- nodeName,
2224
- actionInputsWithoutAgents
2225
- });
2226
- eventSource.stream(async (eventStream$) => {
2227
- from(stream).subscribe({
2228
- next: (event) => eventStream$.next(event),
2229
- error: (err) => console.error("Error in stream", err),
2230
- complete: () => eventStream$.complete()
2231
- });
2232
- });
2233
- outputMessagesPromise.then((outputMessages) => {
2234
- var _a2;
2235
- (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
2236
- threadId,
2237
- runId: void 0,
2238
- inputMessages: messages,
2239
- outputMessages,
2240
- properties: graphqlContext.properties
2241
- });
2242
- }).catch((_error) => {
2243
- });
2244
- return {
2245
- threadId,
2246
- runId: void 0,
2247
- eventSource,
2248
- serverSideActions: [],
2249
- actionInputsWithoutAgents
2250
- };
2251
- } catch (error) {
2252
- console.error("Error getting response:", error);
2253
- throw error;
2254
- }
2255
- }
2256
- async getServerSideActions(request) {
2257
- const { messages: rawMessages, graphqlContext, agentStates, url } = request;
2258
- const inputMessages = convertGqlInputToMessages(rawMessages);
2259
- const langserveFunctions = [];
2260
- for (const chainPromise of this.langserve) {
2261
- try {
2262
- const chain = await chainPromise;
2263
- langserveFunctions.push(chain);
2264
- } catch (error) {
2265
- console.error("Error loading langserve chain:", error);
2266
- }
2267
- }
2268
- const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
2269
- ...endpoint,
2270
- type: resolveEndpointType(endpoint)
2271
- }));
2272
- const remoteActions = await setupRemoteActions({
2273
- remoteEndpointDefinitions,
2274
- graphqlContext,
2275
- messages: inputMessages,
2276
- agentStates,
2277
- frontendUrl: url
2278
- });
2279
- const configuredActions = typeof this.actions === "function" ? this.actions({
2280
- properties: graphqlContext.properties,
2281
- url
2282
- }) : this.actions;
2283
- return [
2284
- ...configuredActions,
2285
- ...langserveFunctions,
2286
- ...remoteActions
2287
- ];
2288
- }
2289
- };
2290
- __name(CopilotRuntime, "CopilotRuntime");
2291
- function flattenToolCallsNoDuplicates(toolsByPriority) {
2292
- let allTools = [];
2293
- const allToolNames = [];
2294
- for (const tool of toolsByPriority) {
2295
- if (!allToolNames.includes(tool.name)) {
2296
- allTools.push(tool);
2297
- allToolNames.push(tool.name);
2298
- }
2299
- }
2300
- return allTools;
2301
- }
2302
- __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
2303
- function copilotKitEndpoint(config) {
2304
- return {
2305
- ...config,
2306
- type: EndpointType.CopilotKit
2307
- };
2308
- }
2309
- __name(copilotKitEndpoint, "copilotKitEndpoint");
2310
- function langGraphPlatformEndpoint(config) {
2311
- return {
2312
- ...config,
2313
- type: EndpointType.LangGraphPlatform
2314
- };
2315
- }
2316
- __name(langGraphPlatformEndpoint, "langGraphPlatformEndpoint");
2317
- function resolveEndpointType(endpoint) {
2318
- if (!endpoint.type) {
2319
- if ("langsmithApiKey" in endpoint && "deploymentUrl" in endpoint && "agents" in endpoint) {
2320
- return EndpointType.LangGraphPlatform;
2321
- } else {
2322
- return EndpointType.CopilotKit;
2323
- }
2324
- }
2325
- return endpoint.type;
2326
- }
2327
- __name(resolveEndpointType, "resolveEndpointType");
2328
-
2329
- // src/lib/telemetry-client.ts
2330
- var packageJson = require_package();
2331
- var telemetryClient = new TelemetryClient({
2332
- packageName: packageJson.name,
2333
- packageVersion: packageJson.version
2334
- });
2335
- function getRuntimeInstanceTelemetryInfo(runtime) {
2336
- const endpointsInfo = runtime.remoteEndpointDefinitions.reduce((acc, endpoint) => {
2337
- let info = {
2338
- ...acc
2339
- };
2340
- const endpointType = resolveEndpointType(endpoint);
2341
- if (!info.endpointTypes.includes(endpointType)) {
2342
- info = {
2343
- ...info,
2344
- endpointTypes: [
2345
- ...info.endpointTypes,
2346
- endpointType
2347
- ]
2348
- };
2349
- }
2350
- if (endpointType === EndpointType.LangGraphPlatform) {
2351
- const ep = endpoint;
2352
- info = {
2353
- ...info,
2354
- agentsAmount: ep.agents.length,
2355
- hashedKey: createHash3("sha256").update(ep.langsmithApiKey).digest("hex")
2356
- };
2357
- }
2358
- return info;
2359
- }, {
2360
- endpointTypes: [],
2361
- agentsAmount: null,
2362
- hashedKey: null
2363
- });
2364
- return {
2365
- actionsAmount: runtime.actions.length,
2366
- endpointsAmount: runtime.remoteEndpointDefinitions.length,
2367
- endpointTypes: endpointsInfo.endpointTypes,
2368
- agentsAmount: endpointsInfo.agentsAmount,
2369
- hashedLgcKey: endpointsInfo.hashedKey
2370
- };
2371
- }
2372
- __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
2373
- var telemetry_client_default = telemetryClient;
2374
-
2375
- // src/service-adapters/events.ts
2376
- var RuntimeEventTypes;
2377
- (function(RuntimeEventTypes2) {
2378
- RuntimeEventTypes2["TextMessageStart"] = "TextMessageStart";
2379
- RuntimeEventTypes2["TextMessageContent"] = "TextMessageContent";
2380
- RuntimeEventTypes2["TextMessageEnd"] = "TextMessageEnd";
2381
- RuntimeEventTypes2["ActionExecutionStart"] = "ActionExecutionStart";
2382
- RuntimeEventTypes2["ActionExecutionArgs"] = "ActionExecutionArgs";
2383
- RuntimeEventTypes2["ActionExecutionEnd"] = "ActionExecutionEnd";
2384
- RuntimeEventTypes2["ActionExecutionResult"] = "ActionExecutionResult";
2385
- RuntimeEventTypes2["AgentStateMessage"] = "AgentStateMessage";
2386
- })(RuntimeEventTypes || (RuntimeEventTypes = {}));
2387
- var RuntimeEventSubject = class extends ReplaySubject2 {
2388
- constructor() {
2389
- super();
2390
- }
2391
- sendTextMessageStart(messageId) {
2392
- this.next({
2393
- type: "TextMessageStart",
2394
- messageId
2395
- });
2396
- }
2397
- sendTextMessageContent(content) {
2398
- this.next({
2399
- type: "TextMessageContent",
2400
- content
2401
- });
2402
- }
2403
- sendTextMessageEnd() {
2404
- this.next({
2405
- type: "TextMessageEnd"
2406
- });
2407
- }
2408
- sendTextMessage(messageId, content) {
2409
- this.sendTextMessageStart(messageId);
2410
- this.sendTextMessageContent(content);
2411
- this.sendTextMessageEnd();
2412
- }
2413
- sendActionExecutionStart(actionExecutionId, actionName) {
2414
- this.next({
2415
- type: "ActionExecutionStart",
2416
- actionExecutionId,
2417
- actionName
2418
- });
2419
- }
2420
- sendActionExecutionArgs(args) {
2421
- this.next({
2422
- type: "ActionExecutionArgs",
2423
- args
2424
- });
2425
- }
2426
- sendActionExecutionEnd() {
2427
- this.next({
2428
- type: "ActionExecutionEnd"
2429
- });
2430
- }
2431
- sendActionExecution(actionExecutionId, toolName, args) {
2432
- this.sendActionExecutionStart(actionExecutionId, toolName);
2433
- this.sendActionExecutionArgs(args);
2434
- this.sendActionExecutionEnd();
2435
- }
2436
- sendActionExecutionResult(actionExecutionId, actionName, result) {
2437
- this.next({
2438
- type: "ActionExecutionResult",
2439
- actionName,
2440
- actionExecutionId,
2441
- result
2442
- });
2443
- }
2444
- sendAgentStateMessage(threadId, agentName, nodeName, runId, active, role, state, running) {
2445
- this.next({
2446
- type: "AgentStateMessage",
2447
- threadId,
2448
- agentName,
2449
- nodeName,
2450
- runId,
2451
- active,
2452
- role,
2453
- state,
2454
- running
2455
- });
2456
- }
2457
- };
2458
- __name(RuntimeEventSubject, "RuntimeEventSubject");
2459
- var RuntimeEventSource = class {
2460
- eventStream$ = new RuntimeEventSubject();
2461
- callback;
2462
- async stream(callback) {
2463
- this.callback = callback;
2464
- }
2465
- sendErrorMessageToChat() {
2466
- const errorMessage = "\u274C An error occurred. Please try again.";
2467
- if (!this.callback) {
2468
- this.stream(async (eventStream$) => {
2469
- eventStream$.sendTextMessage(randomId3(), errorMessage);
2470
- });
2471
- } else {
2472
- this.eventStream$.sendTextMessage(randomId3(), errorMessage);
2473
- }
2474
- }
2475
- processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents }) {
2476
- this.callback(this.eventStream$).catch((error) => {
2477
- console.error("Error in event source callback", error);
2478
- this.sendErrorMessageToChat();
2479
- });
2480
- return this.eventStream$.pipe(
2481
- // mark tools for server side execution
2482
- map((event) => {
2483
- if (event.type === "ActionExecutionStart") {
2484
- if (event.scope !== "passThrough") {
2485
- event.scope = serverSideActions.find((action) => action.name === event.actionName) ? "server" : "client";
2486
- }
2487
- }
2488
- return event;
2489
- }),
2490
- // track state
2491
- scan2((acc, event) => {
2492
- acc = {
2493
- ...acc
2494
- };
2495
- if (event.type === "ActionExecutionStart") {
2496
- acc.callActionServerSide = event.scope === "server";
2497
- acc.args = "";
2498
- acc.actionExecutionId = event.actionExecutionId;
2499
- if (acc.callActionServerSide) {
2500
- acc.action = serverSideActions.find((action) => action.name === event.actionName);
2501
- }
2502
- } else if (event.type === "ActionExecutionArgs") {
2503
- acc.args += event.args;
2504
- }
2505
- acc.event = event;
2506
- return acc;
2507
- }, {
2508
- event: null,
2509
- callActionServerSide: false,
2510
- args: "",
2511
- actionExecutionId: null,
2512
- action: null
2513
- }),
2514
- concatMap((eventWithState) => {
2515
- if (eventWithState.event.type === "ActionExecutionEnd" && eventWithState.callActionServerSide) {
2516
- const toolCallEventStream$ = new RuntimeEventSubject();
2517
- executeAction(toolCallEventStream$, guardrailsResult$ ? guardrailsResult$ : null, eventWithState.action, eventWithState.args, eventWithState.actionExecutionId, actionInputsWithoutAgents).catch((error) => {
2518
- console.error(error);
2519
- });
2520
- telemetry_client_default.capture("oss.runtime.server_action_executed", {});
2521
- return concat(of(eventWithState.event), toolCallEventStream$);
2522
- } else {
2523
- return of(eventWithState.event);
2524
- }
2525
- })
2526
- );
2527
- }
2528
- };
2529
- __name(RuntimeEventSource, "RuntimeEventSource");
2530
- async function executeAction(eventStream$, guardrailsResult$, action, actionArguments, actionExecutionId, actionInputsWithoutAgents) {
2531
- var _a;
2532
- if (guardrailsResult$) {
2533
- const { status } = await firstValueFrom(guardrailsResult$);
2534
- if (status === "denied") {
2535
- eventStream$.complete();
2536
- return;
2537
- }
2538
- }
2539
- let args = [];
2540
- if (actionArguments) {
2541
- try {
2542
- args = JSON.parse(actionArguments);
2543
- } catch (e) {
2544
- console.warn("Action argument unparsable", {
2545
- actionArguments
2546
- });
2547
- }
2548
- }
2549
- if (isLangGraphAgentAction(action)) {
2550
- eventStream$.sendActionExecutionResult(actionExecutionId, action.name, `${action.name} agent started`);
2551
- const stream = await action.langGraphAgentHandler({
2552
- name: action.name,
2553
- actionInputsWithoutAgents
2554
- });
2555
- from2(stream).subscribe({
2556
- next: (event) => eventStream$.next(event),
2557
- error: (err) => console.error("Error in stream", err),
2558
- complete: () => eventStream$.complete()
2559
- });
2560
- } else {
2561
- const result = await ((_a = action.handler) == null ? void 0 : _a.call(action, args));
2562
- await streamLangChainResponse({
2563
- result,
2564
- eventStream$,
2565
- actionExecution: {
2566
- name: action.name,
2567
- id: actionExecutionId
2568
- }
2569
- });
2570
- }
2571
- }
2572
- __name(executeAction, "executeAction");
2573
-
2574
- // src/graphql/resolvers/copilot.resolver.ts
2575
- import { GraphQLJSONObject } from "graphql-scalars";
2576
- import { plainToInstance as plainToInstance2 } from "class-transformer";
2577
- import { GraphQLError } from "graphql";
2578
- import { randomId as randomId4 } from "@copilotkit/shared";
2579
- function _ts_decorate12(decorators, target, key, desc) {
2580
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2581
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2582
- r = Reflect.decorate(decorators, target, key, desc);
2583
- else
2584
- for (var i = decorators.length - 1; i >= 0; i--)
2585
- if (d = decorators[i])
2586
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2587
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2588
- }
2589
- __name(_ts_decorate12, "_ts_decorate");
2590
- function _ts_metadata12(k, v) {
2591
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
2592
- return Reflect.metadata(k, v);
2593
- }
2594
- __name(_ts_metadata12, "_ts_metadata");
2595
- function _ts_param(paramIndex, decorator) {
2596
- return function(target, key) {
2597
- decorator(target, key, paramIndex);
2598
- };
2599
- }
2600
- __name(_ts_param, "_ts_param");
2601
- var invokeGuardrails = /* @__PURE__ */ __name(async ({ baseUrl, copilotCloudPublicApiKey, data, onResult, onError }) => {
2602
- var _a;
2603
- if (data.messages.length && ((_a = data.messages[data.messages.length - 1].textMessage) == null ? void 0 : _a.role) === MessageRole.user) {
2604
- const messages = data.messages.filter((m) => m.textMessage !== void 0 && (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant)).map((m) => ({
2605
- role: m.textMessage.role,
2606
- content: m.textMessage.content
2607
- }));
2608
- const lastMessage = messages[messages.length - 1];
2609
- const restOfMessages = messages.slice(0, -1);
2610
- const body = {
2611
- input: lastMessage.content,
2612
- validTopics: data.cloud.guardrails.inputValidationRules.allowList,
2613
- invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,
2614
- messages: restOfMessages
2615
- };
2616
- const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {
2617
- method: "POST",
2618
- headers: {
2619
- "Content-Type": "application/json",
2620
- "X-CopilotCloud-Public-API-Key": copilotCloudPublicApiKey
2621
- },
2622
- body: JSON.stringify(body)
2623
- });
2624
- if (guardrailsResult.ok) {
2625
- const resultJson = await guardrailsResult.json();
2626
- onResult(resultJson);
2627
- } else {
2628
- onError(await guardrailsResult.json());
2629
- }
2630
- }
2631
- }, "invokeGuardrails");
2632
- var CopilotResolver = class {
2633
- async hello() {
2634
- return "Hello World";
2635
- }
2636
- async generateCopilotResponse(ctx, data, properties) {
2637
- var _a, _b, _c;
2638
- telemetry_client_default.capture("oss.runtime.copilot_request_created", {
2639
- "cloud.guardrails.enabled": ((_a = data.cloud) == null ? void 0 : _a.guardrails) !== void 0,
2640
- requestType: data.metadata.requestType
2641
- });
2642
- let logger2 = ctx.logger.child({
2643
- component: "CopilotResolver.generateCopilotResponse"
2644
- });
2645
- logger2.debug({
2646
- data
2647
- }, "Generating Copilot response");
2648
- if (properties) {
2649
- logger2.debug("Properties provided, merging with context properties");
2650
- ctx.properties = {
2651
- ...ctx.properties,
2652
- ...properties
2653
- };
2654
- }
2655
- const copilotRuntime = ctx._copilotkit.runtime;
2656
- const serviceAdapter = ctx._copilotkit.serviceAdapter;
2657
- let copilotCloudPublicApiKey = null;
2658
- let copilotCloudBaseUrl;
2659
- if (data.cloud) {
2660
- logger2 = logger2.child({
2661
- cloud: true
2662
- });
2663
- logger2.debug("Cloud configuration provided, checking for public API key in headers");
2664
- const key = ctx.request.headers.get("x-copilotcloud-public-api-key");
2665
- if (key) {
2666
- logger2.debug("Public API key found in headers");
2667
- copilotCloudPublicApiKey = key;
2668
- } else {
2669
- logger2.error("Public API key not found in headers");
2670
- throw new GraphQLError("X-CopilotCloud-Public-API-Key header is required");
2671
- }
2672
- if (process.env.COPILOT_CLOUD_BASE_URL) {
2673
- copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;
2674
- } else if ((_b = ctx._copilotkit.cloud) == null ? void 0 : _b.baseUrl) {
2675
- copilotCloudBaseUrl = (_c = ctx._copilotkit.cloud) == null ? void 0 : _c.baseUrl;
2676
- } else {
2677
- copilotCloudBaseUrl = "https://api.cloud.copilotkit.ai";
2678
- }
2679
- logger2 = logger2.child({
2680
- copilotCloudBaseUrl
2681
- });
2682
- }
2683
- logger2.debug("Setting up subjects");
2684
- const responseStatus$ = new ReplaySubject3();
2685
- const interruptStreaming$ = new ReplaySubject3();
2686
- const guardrailsResult$ = new ReplaySubject3();
2687
- let outputMessages = [];
2688
- let resolveOutputMessagesPromise;
2689
- let rejectOutputMessagesPromise;
2690
- const outputMessagesPromise = new Promise((resolve, reject) => {
2691
- resolveOutputMessagesPromise = resolve;
2692
- rejectOutputMessagesPromise = reject;
2693
- });
2694
- logger2.debug("Processing");
2695
- const { eventSource, threadId = randomId4(), runId, serverSideActions, actionInputsWithoutAgents } = await copilotRuntime.processRuntimeRequest({
2696
- serviceAdapter,
2697
- messages: data.messages,
2698
- actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
2699
- threadId: data.threadId,
2700
- runId: data.runId,
2701
- publicApiKey: void 0,
2702
- outputMessagesPromise,
2703
- graphqlContext: ctx,
2704
- forwardedParameters: data.forwardedParameters,
2705
- agentSession: data.agentSession,
2706
- agentStates: data.agentStates,
2707
- url: data.frontend.url
2708
- });
2709
- logger2.debug("Event source created, creating response");
2710
- const response = {
2711
- threadId,
2712
- runId,
2713
- status: firstValueFrom2(responseStatus$),
2714
- messages: new Repeater(async (pushMessage, stopStreamingMessages) => {
2715
- var _a2, _b2;
2716
- logger2.debug("Messages repeater created");
2717
- if ((_a2 = data.cloud) == null ? void 0 : _a2.guardrails) {
2718
- logger2 = logger2.child({
2719
- guardrails: true
2720
- });
2721
- logger2.debug("Guardrails is enabled, validating input");
2722
- invokeGuardrails({
2723
- baseUrl: copilotCloudBaseUrl,
2724
- copilotCloudPublicApiKey,
2725
- data,
2726
- onResult: (result) => {
2727
- logger2.debug({
2728
- status: result.status
2729
- }, "Guardrails validation done");
2730
- guardrailsResult$.next(result);
2731
- if (result.status === "denied") {
2732
- responseStatus$.next(new GuardrailsValidationFailureResponse({
2733
- guardrailsReason: result.reason
2734
- }));
2735
- interruptStreaming$.next({
2736
- reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`
2737
- });
2738
- outputMessages = [
2739
- plainToInstance2(TextMessage, {
2740
- id: randomId4(),
2741
- createdAt: /* @__PURE__ */ new Date(),
2742
- content: result.reason,
2743
- role: MessageRole.assistant
2744
- })
2745
- ];
2746
- resolveOutputMessagesPromise(outputMessages);
2747
- }
2748
- },
2749
- onError: (err) => {
2750
- logger2.error({
2751
- err
2752
- }, "Error in guardrails validation");
2753
- responseStatus$.next(new UnknownErrorResponse({
2754
- description: `An unknown error has occurred in the guardrails validation`
2755
- }));
2756
- interruptStreaming$.next({
2757
- reason: `Interrupted due to unknown error in guardrails validation`
2758
- });
2759
- rejectOutputMessagesPromise(err);
2760
- }
2761
- });
2762
- }
2763
- let eventStreamSubscription;
2764
- const eventStream = eventSource.processRuntimeEvents({
2765
- serverSideActions,
2766
- guardrailsResult$: ((_b2 = data.cloud) == null ? void 0 : _b2.guardrails) ? guardrailsResult$ : null,
2767
- actionInputsWithoutAgents: actionInputsWithoutAgents.filter(
2768
- // TODO-AGENTS: do not exclude ALL server side actions
2769
- (action) => !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
2770
- )
2771
- }).pipe(
2772
- // shareReplay() ensures that later subscribers will see the whole stream instead of
2773
- // just the events that were emitted after the subscriber was added.
2774
- shareReplay(),
2775
- finalize(() => {
2776
- logger2.debug("Event stream finalized");
2777
- })
2778
- );
2779
- logger2.debug("Event stream created, subscribing to event stream");
2780
- eventStreamSubscription = eventStream.subscribe({
2781
- next: async (event) => {
2782
- switch (event.type) {
2783
- case RuntimeEventTypes.TextMessageStart:
2784
- const textMessageContentStream = eventStream.pipe(
2785
- // skip until this message start event
2786
- skipWhile((e) => e !== event),
2787
- // take until the message end event
2788
- takeWhile((e) => e.type != RuntimeEventTypes.TextMessageEnd)
2789
- );
2790
- const streamingTextStatus = new Subject();
2791
- const messageId = event.messageId;
2792
- pushMessage({
2793
- id: messageId,
2794
- status: firstValueFrom2(streamingTextStatus),
2795
- createdAt: /* @__PURE__ */ new Date(),
2796
- role: MessageRole.assistant,
2797
- content: new Repeater(async (pushTextChunk, stopStreamingText) => {
2798
- logger2.debug("Text message content repeater created");
2799
- const textChunks = [];
2800
- let textSubscription;
2801
- interruptStreaming$.pipe(shareReplay(), take(1), tap(({ reason, messageId: messageId2 }) => {
2802
- logger2.debug({
2803
- reason,
2804
- messageId: messageId2
2805
- }, "Text streaming interrupted");
2806
- streamingTextStatus.next(plainToInstance2(FailedMessageStatus, {
2807
- reason
2808
- }));
2809
- responseStatus$.next(new MessageStreamInterruptedResponse({
2810
- messageId: messageId2
2811
- }));
2812
- stopStreamingText();
2813
- textSubscription == null ? void 0 : textSubscription.unsubscribe();
2814
- })).subscribe();
2815
- logger2.debug("Subscribing to text message content stream");
2816
- textSubscription = textMessageContentStream.subscribe({
2817
- next: async (e) => {
2818
- if (e.type == RuntimeEventTypes.TextMessageContent) {
2819
- await pushTextChunk(e.content);
2820
- textChunks.push(e.content);
2821
- }
2822
- },
2823
- error: (err) => {
2824
- logger2.error({
2825
- err
2826
- }, "Error in text message content stream");
2827
- interruptStreaming$.next({
2828
- reason: "Error streaming message content",
2829
- messageId
2830
- });
2831
- stopStreamingText();
2832
- textSubscription == null ? void 0 : textSubscription.unsubscribe();
2833
- },
2834
- complete: () => {
2835
- logger2.debug("Text message content stream completed");
2836
- streamingTextStatus.next(new SuccessMessageStatus());
2837
- stopStreamingText();
2838
- textSubscription == null ? void 0 : textSubscription.unsubscribe();
2839
- outputMessages.push(plainToInstance2(TextMessage, {
2840
- id: messageId,
2841
- createdAt: /* @__PURE__ */ new Date(),
2842
- content: textChunks.join(""),
2843
- role: MessageRole.assistant
2844
- }));
2845
- }
2846
- });
2847
- })
2848
- });
2849
- break;
2850
- case RuntimeEventTypes.ActionExecutionStart:
2851
- logger2.debug("Action execution start event received");
2852
- const actionExecutionArgumentStream = eventStream.pipe(skipWhile((e) => e !== event), takeWhile((e) => e.type != RuntimeEventTypes.ActionExecutionEnd));
2853
- const streamingArgumentsStatus = new Subject();
2854
- pushMessage({
2855
- id: event.actionExecutionId,
2856
- status: firstValueFrom2(streamingArgumentsStatus),
2857
- createdAt: /* @__PURE__ */ new Date(),
2858
- name: event.actionName,
2859
- scope: event.scope,
2860
- arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
2861
- logger2.debug("Action execution argument stream created");
2862
- const argumentChunks = [];
2863
- let actionExecutionArgumentSubscription;
2864
- actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({
2865
- next: async (e) => {
2866
- if (e.type == RuntimeEventTypes.ActionExecutionArgs) {
2867
- await pushArgumentsChunk(e.args);
2868
- argumentChunks.push(e.args);
2869
- }
2870
- },
2871
- error: (err) => {
2872
- logger2.error({
2873
- err
2874
- }, "Error in action execution argument stream");
2875
- streamingArgumentsStatus.next(plainToInstance2(FailedMessageStatus, {
2876
- reason: "An unknown error has occurred in the action execution argument stream"
2877
- }));
2878
- stopStreamingArguments();
2879
- actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
2880
- },
2881
- complete: () => {
2882
- logger2.debug("Action execution argument stream completed");
2883
- streamingArgumentsStatus.next(new SuccessMessageStatus());
2884
- stopStreamingArguments();
2885
- actionExecutionArgumentSubscription == null ? void 0 : actionExecutionArgumentSubscription.unsubscribe();
2886
- outputMessages.push(plainToInstance2(ActionExecutionMessage, {
2887
- id: event.actionExecutionId,
2888
- createdAt: /* @__PURE__ */ new Date(),
2889
- name: event.actionName,
2890
- scope: event.scope,
2891
- arguments: argumentChunks.join("")
2892
- }));
2893
- }
2894
- });
2895
- })
2896
- });
2897
- break;
2898
- case RuntimeEventTypes.ActionExecutionResult:
2899
- logger2.debug({
2900
- result: event.result
2901
- }, "Action execution result event received");
2902
- pushMessage({
2903
- id: randomId4(),
2904
- status: new SuccessMessageStatus(),
2905
- createdAt: /* @__PURE__ */ new Date(),
2906
- actionExecutionId: event.actionExecutionId,
2907
- actionName: event.actionName,
2908
- result: event.result
2909
- });
2910
- outputMessages.push(plainToInstance2(ResultMessage, {
2911
- id: randomId4(),
2912
- createdAt: /* @__PURE__ */ new Date(),
2913
- actionExecutionId: event.actionExecutionId,
2914
- actionName: event.actionName,
2915
- result: event.result
2916
- }));
2917
- break;
2918
- case RuntimeEventTypes.AgentStateMessage:
2919
- logger2.debug({
2920
- event
2921
- }, "Agent message event received");
2922
- pushMessage({
2923
- id: randomId4(),
2924
- status: new SuccessMessageStatus(),
2925
- threadId: event.threadId,
2926
- agentName: event.agentName,
2927
- nodeName: event.nodeName,
2928
- runId: event.runId,
2929
- active: event.active,
2930
- state: event.state,
2931
- running: event.running,
2932
- role: MessageRole.assistant,
2933
- createdAt: /* @__PURE__ */ new Date()
2934
- });
2935
- outputMessages.push(plainToInstance2(AgentStateMessage, {
2936
- id: randomId4(),
2937
- threadId: event.threadId,
2938
- agentName: event.agentName,
2939
- nodeName: event.nodeName,
2940
- runId: event.runId,
2941
- active: event.active,
2942
- state: event.state,
2943
- running: event.running,
2944
- role: MessageRole.assistant,
2945
- createdAt: /* @__PURE__ */ new Date()
2946
- }));
2947
- break;
2948
- }
2949
- },
2950
- error: (err) => {
2951
- logger2.error({
2952
- err
2953
- }, "Error in event stream");
2954
- responseStatus$.next(new UnknownErrorResponse({
2955
- description: `An unknown error has occurred in the event stream`
2956
- }));
2957
- eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
2958
- stopStreamingMessages();
2959
- rejectOutputMessagesPromise(err);
2960
- },
2961
- complete: async () => {
2962
- var _a3;
2963
- logger2.debug("Event stream completed");
2964
- if ((_a3 = data.cloud) == null ? void 0 : _a3.guardrails) {
2965
- logger2.debug("Guardrails is enabled, waiting for guardrails result");
2966
- await firstValueFrom2(guardrailsResult$);
2967
- }
2968
- responseStatus$.next(new SuccessResponseStatus());
2969
- eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
2970
- stopStreamingMessages();
2971
- resolveOutputMessagesPromise(outputMessages);
2972
- }
2973
- });
2974
- })
2975
- };
2976
- return response;
2977
- }
2978
- };
2979
- __name(CopilotResolver, "CopilotResolver");
2980
- _ts_decorate12([
2981
- Query(() => String),
2982
- _ts_metadata12("design:type", Function),
2983
- _ts_metadata12("design:paramtypes", []),
2984
- _ts_metadata12("design:returntype", Promise)
2985
- ], CopilotResolver.prototype, "hello", null);
2986
- _ts_decorate12([
2987
- Mutation(() => CopilotResponse),
2988
- _ts_param(0, Ctx()),
2989
- _ts_param(1, Arg("data")),
2990
- _ts_param(2, Arg("properties", () => GraphQLJSONObject, {
2991
- nullable: true
2992
- })),
2993
- _ts_metadata12("design:type", Function),
2994
- _ts_metadata12("design:paramtypes", [
2995
- typeof GraphQLContext === "undefined" ? Object : GraphQLContext,
2996
- typeof GenerateCopilotResponseInput === "undefined" ? Object : GenerateCopilotResponseInput,
2997
- typeof CopilotRequestContextProperties === "undefined" ? Object : CopilotRequestContextProperties
2998
- ]),
2999
- _ts_metadata12("design:returntype", Promise)
3000
- ], CopilotResolver.prototype, "generateCopilotResponse", null);
3001
- CopilotResolver = _ts_decorate12([
3002
- Resolver(() => CopilotResponse)
3003
- ], CopilotResolver);
3004
-
3005
- // src/lib/integrations/shared.ts
3006
- import { useDeferStream } from "@graphql-yoga/plugin-defer-stream";
3007
-
3008
- // src/lib/logger.ts
3009
- import createPinoLogger from "pino";
3010
- import pretty from "pino-pretty";
3011
- function createLogger(options) {
3012
- const { level, component } = options || {};
3013
- const stream = pretty({
3014
- colorize: true
3015
- });
3016
- const logger2 = createPinoLogger({
3017
- level: process.env.LOG_LEVEL || level || "error",
3018
- redact: {
3019
- paths: [
3020
- "pid",
3021
- "hostname"
3022
- ],
3023
- remove: true
3024
- }
3025
- }, stream);
3026
- if (component) {
3027
- return logger2.child({
3028
- component
3029
- });
3030
- } else {
3031
- return logger2;
3032
- }
3033
- }
3034
- __name(createLogger, "createLogger");
3035
-
3036
- // src/lib/integrations/shared.ts
3037
- var logger = createLogger();
3038
- async function createContext(initialContext, copilotKitContext, contextLogger, properties = {}) {
3039
- logger.debug({
3040
- copilotKitContext
3041
- }, "Creating GraphQL context");
3042
- const ctx = {
3043
- ...initialContext,
3044
- _copilotkit: {
3045
- ...copilotKitContext
3046
- },
3047
- properties: {
3048
- ...properties
3049
- },
3050
- logger: contextLogger
3051
- };
3052
- return ctx;
3053
- }
3054
- __name(createContext, "createContext");
3055
- function buildSchema(options = {}) {
3056
- logger.debug("Building GraphQL schema...");
3057
- const schema = buildSchemaSync({
3058
- resolvers: [
3059
- CopilotResolver
3060
- ],
3061
- emitSchemaFile: options.emitSchemaFile
3062
- });
3063
- logger.debug("GraphQL schema built successfully");
3064
- return schema;
3065
- }
3066
- __name(buildSchema, "buildSchema");
3067
- function getCommonConfig(options) {
3068
- var _a;
3069
- const logLevel = process.env.LOG_LEVEL || options.logLevel || "error";
3070
- const logger2 = createLogger({
3071
- level: logLevel,
3072
- component: "getCommonConfig"
3073
- });
3074
- const contextLogger = createLogger({
3075
- level: logLevel
3076
- });
3077
- if (options.cloud) {
3078
- telemetry_client_default.setCloudConfiguration({
3079
- publicApiKey: options.cloud.publicApiKey,
3080
- baseUrl: options.cloud.baseUrl
3081
- });
3082
- }
3083
- if ((_a = options.properties) == null ? void 0 : _a._copilotkit) {
3084
- telemetry_client_default.setGlobalProperties({
3085
- _copilotkit: {
3086
- ...options.properties._copilotkit
3087
- }
3088
- });
3089
- }
3090
- telemetry_client_default.setGlobalProperties({
3091
- runtime: {
3092
- serviceAdapter: options.serviceAdapter.constructor.name
3093
- }
3094
- });
3095
- return {
3096
- logging: createLogger({
3097
- component: "Yoga GraphQL",
3098
- level: logLevel
3099
- }),
3100
- schema: buildSchema(),
3101
- plugins: [
3102
- useDeferStream()
3103
- ],
3104
- context: (ctx) => createContext(ctx, options, contextLogger, options.properties)
3105
- };
3106
- }
3107
- __name(getCommonConfig, "getCommonConfig");
3108
-
3109
- // src/lib/integrations/node-http/index.ts
3110
- function copilotRuntimeNodeHttpEndpoint(options) {
3111
- var _a;
3112
- const commonConfig = getCommonConfig(options);
3113
- telemetry_client_default.setGlobalProperties({
3114
- runtime: {
3115
- framework: "node-http"
3116
- }
3117
- });
3118
- if ((_a = options.properties) == null ? void 0 : _a._copilotkit) {
3119
- telemetry_client_default.setGlobalProperties({
3120
- _copilotkit: options.properties._copilotkit
3121
- });
3122
- }
3123
- telemetry_client_default.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options.runtime));
3124
- const logger2 = commonConfig.logging;
3125
- logger2.debug("Creating Node HTTP endpoint");
3126
- const yoga = createYoga({
3127
- ...commonConfig,
3128
- graphqlEndpoint: options.endpoint
3129
- });
3130
- return yoga;
3131
- }
3132
- __name(copilotRuntimeNodeHttpEndpoint, "copilotRuntimeNodeHttpEndpoint");
3133
-
3134
- export {
3135
- getRuntimeInstanceTelemetryInfo,
3136
- telemetry_client_default,
3137
- CopilotRuntime,
3138
- flattenToolCallsNoDuplicates,
3139
- copilotKitEndpoint,
3140
- langGraphPlatformEndpoint,
3141
- resolveEndpointType,
3142
- createContext,
3143
- buildSchema,
3144
- getCommonConfig,
3145
- copilotRuntimeNodeHttpEndpoint
3146
- };
3147
- //# sourceMappingURL=chunk-ZSWCEADS.mjs.map