@copilotkit/runtime 0.0.0-mme-load-agent-state-20250117154700

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