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

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