@copilotkit/runtime 1.50.0-beta.0 → 1.50.0-beta.10

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 (132) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/chunk-2OZAGFV3.mjs +43 -0
  3. package/dist/chunk-2OZAGFV3.mjs.map +1 -0
  4. package/dist/chunk-62NE5S6M.mjs +226 -0
  5. package/dist/chunk-62NE5S6M.mjs.map +1 -0
  6. package/dist/chunk-6XRUR5UK.mjs +1 -0
  7. package/dist/chunk-6XRUR5UK.mjs.map +1 -0
  8. package/dist/chunk-AMUJQ6IR.mjs +50 -0
  9. package/dist/chunk-AMUJQ6IR.mjs.map +1 -0
  10. package/dist/chunk-BJEYMRDD.mjs +25 -0
  11. package/dist/chunk-BJEYMRDD.mjs.map +1 -0
  12. package/dist/chunk-DZV4ZIAR.mjs +3063 -0
  13. package/dist/chunk-DZV4ZIAR.mjs.map +1 -0
  14. package/dist/chunk-FHD4JECV.mjs +33 -0
  15. package/dist/chunk-FHD4JECV.mjs.map +1 -0
  16. package/dist/chunk-FMU55SEU.mjs +25 -0
  17. package/dist/chunk-FMU55SEU.mjs.map +1 -0
  18. package/dist/chunk-OWIGJONH.mjs +275 -0
  19. package/dist/chunk-OWIGJONH.mjs.map +1 -0
  20. package/dist/chunk-SBCOROE4.mjs +1112 -0
  21. package/dist/chunk-SBCOROE4.mjs.map +1 -0
  22. package/dist/chunk-TTUAEJLD.mjs +617 -0
  23. package/dist/chunk-TTUAEJLD.mjs.map +1 -0
  24. package/dist/chunk-XWBDEXDA.mjs +153 -0
  25. package/dist/chunk-XWBDEXDA.mjs.map +1 -0
  26. package/dist/chunk-Z752VE75.mjs +74 -0
  27. package/dist/chunk-Z752VE75.mjs.map +1 -0
  28. package/dist/graphql/message-conversion/index.d.ts +18 -0
  29. package/dist/graphql/message-conversion/index.js +725 -0
  30. package/dist/graphql/message-conversion/index.js.map +1 -0
  31. package/dist/graphql/message-conversion/index.mjs +245 -0
  32. package/dist/graphql/message-conversion/index.mjs.map +1 -0
  33. package/dist/graphql/types/base/index.d.ts +6 -0
  34. package/dist/graphql/types/base/index.js +63 -0
  35. package/dist/graphql/types/base/index.js.map +1 -0
  36. package/dist/graphql/types/base/index.mjs +8 -0
  37. package/dist/graphql/types/base/index.mjs.map +1 -0
  38. package/dist/graphql/types/converted/index.d.ts +2 -0
  39. package/dist/graphql/types/converted/index.js +294 -0
  40. package/dist/graphql/types/converted/index.js.map +1 -0
  41. package/dist/graphql/types/converted/index.mjs +20 -0
  42. package/dist/graphql/types/converted/index.mjs.map +1 -0
  43. package/dist/groq-adapter-50bc6e4a.d.ts +326 -0
  44. package/dist/index-adbd78f1.d.ts +154 -0
  45. package/dist/index.d.ts +136 -287
  46. package/dist/index.js +393 -287
  47. package/dist/index.js.map +1 -1
  48. package/dist/index.mjs +385 -276
  49. package/dist/index.mjs.map +1 -1
  50. package/dist/langgraph.d.ts +284 -0
  51. package/dist/langgraph.js +211 -0
  52. package/dist/langgraph.js.map +1 -0
  53. package/dist/langgraph.mjs +206 -0
  54. package/dist/langgraph.mjs.map +1 -0
  55. package/dist/langserve-74a52292.d.ts +242 -0
  56. package/dist/lib/cloud/index.d.ts +6 -0
  57. package/dist/lib/cloud/index.js +18 -0
  58. package/dist/lib/cloud/index.js.map +1 -0
  59. package/dist/lib/cloud/index.mjs +1 -0
  60. package/dist/lib/cloud/index.mjs.map +1 -0
  61. package/dist/lib/index.d.ts +266 -0
  62. package/dist/lib/index.js +4944 -0
  63. package/dist/lib/index.js.map +1 -0
  64. package/dist/lib/index.mjs +74 -0
  65. package/dist/lib/index.mjs.map +1 -0
  66. package/dist/lib/integrations/index.d.ts +28 -0
  67. package/dist/lib/integrations/index.js +3024 -0
  68. package/dist/lib/integrations/index.js.map +1 -0
  69. package/dist/lib/integrations/index.mjs +36 -0
  70. package/dist/lib/integrations/index.mjs.map +1 -0
  71. package/dist/lib/integrations/nest/index.d.ts +16 -0
  72. package/dist/lib/integrations/nest/index.js +2937 -0
  73. package/dist/lib/integrations/nest/index.js.map +1 -0
  74. package/dist/lib/integrations/nest/index.mjs +13 -0
  75. package/dist/lib/integrations/nest/index.mjs.map +1 -0
  76. package/dist/lib/integrations/node-express/index.d.ts +16 -0
  77. package/dist/lib/integrations/node-express/index.js +2937 -0
  78. package/dist/lib/integrations/node-express/index.js.map +1 -0
  79. package/dist/lib/integrations/node-express/index.mjs +13 -0
  80. package/dist/lib/integrations/node-express/index.mjs.map +1 -0
  81. package/dist/lib/integrations/node-http/index.d.ts +16 -0
  82. package/dist/lib/integrations/node-http/index.js +2923 -0
  83. package/dist/lib/integrations/node-http/index.js.map +1 -0
  84. package/dist/lib/integrations/node-http/index.mjs +12 -0
  85. package/dist/lib/integrations/node-http/index.mjs.map +1 -0
  86. package/dist/service-adapters/index.d.ts +166 -0
  87. package/dist/service-adapters/index.js +1800 -0
  88. package/dist/service-adapters/index.js.map +1 -0
  89. package/dist/service-adapters/index.mjs +36 -0
  90. package/dist/service-adapters/index.mjs.map +1 -0
  91. package/dist/service-adapters/shared/index.d.ts +9 -0
  92. package/dist/service-adapters/shared/index.js +72 -0
  93. package/dist/service-adapters/shared/index.js.map +1 -0
  94. package/dist/service-adapters/shared/index.mjs +8 -0
  95. package/dist/service-adapters/shared/index.mjs.map +1 -0
  96. package/dist/shared-f6d43ef8.d.ts +446 -0
  97. package/dist/utils/index.d.ts +65 -0
  98. package/dist/utils/index.js +175 -0
  99. package/dist/utils/index.js.map +1 -0
  100. package/dist/utils/index.mjs +12 -0
  101. package/dist/utils/index.mjs.map +1 -0
  102. package/dist/v2/index.d.ts +1 -0
  103. package/dist/v2/index.js +7 -0
  104. package/dist/v2/index.js.map +1 -1
  105. package/dist/v2/index.mjs +1 -0
  106. package/dist/v2/index.mjs.map +1 -1
  107. package/package.json +71 -33
  108. package/src/graphql/message-conversion/agui-to-gql.test.ts +2 -2
  109. package/src/graphql/message-conversion/gql-to-agui.test.ts +30 -28
  110. package/src/graphql/message-conversion/roundtrip-conversion.test.ts +8 -8
  111. package/src/langgraph.ts +1 -0
  112. package/src/lib/index.ts +42 -1
  113. package/src/lib/integrations/nextjs/app-router.ts +3 -1
  114. package/src/lib/integrations/node-http/index.ts +132 -11
  115. package/src/lib/integrations/shared.ts +2 -2
  116. package/src/lib/runtime/agent-integrations/{langgraph.agent.ts → langgraph/agent.ts} +5 -30
  117. package/src/lib/runtime/agent-integrations/langgraph/consts.ts +34 -0
  118. package/src/lib/runtime/agent-integrations/langgraph/index.ts +2 -0
  119. package/src/lib/runtime/copilot-runtime.ts +51 -68
  120. package/src/lib/runtime/telemetry-agent-runner.ts +134 -0
  121. package/src/service-adapters/anthropic/anthropic-adapter.ts +16 -3
  122. package/src/service-adapters/bedrock/bedrock-adapter.ts +4 -1
  123. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +2 -1
  124. package/src/service-adapters/google/google-genai-adapter.ts +9 -4
  125. package/src/service-adapters/groq/groq-adapter.ts +16 -3
  126. package/src/service-adapters/langchain/langchain-adapter.ts +5 -3
  127. package/src/service-adapters/langchain/langserve.ts +2 -1
  128. package/src/service-adapters/openai/openai-adapter.ts +17 -3
  129. package/src/service-adapters/openai/openai-assistant-adapter.ts +26 -11
  130. package/src/service-adapters/unify/unify-adapter.ts +3 -1
  131. package/src/v2/index.ts +1 -0
  132. package/tsup.config.ts +5 -2
package/dist/index.js CHANGED
@@ -1,13 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  require('reflect-metadata');
4
- var OpenAI = require('openai');
5
4
  var shared = require('@copilotkit/shared');
6
5
  var messages = require('@langchain/core/messages');
7
6
  var tools = require('@langchain/core/tools');
8
- var promises = require('@langchain/core/callbacks/promises');
9
- var googleGauth = require('@langchain/google-gauth');
10
- var groqSdk = require('groq-sdk');
11
7
  var typeGraphql = require('type-graphql');
12
8
  var rxjs = require('rxjs');
13
9
  var graphqlScalars = require('graphql-scalars');
@@ -16,25 +12,17 @@ var classTransformer = require('class-transformer');
16
12
  var graphql = require('graphql');
17
13
  var crypto = require('crypto');
18
14
  var runtime = require('@copilotkitnext/runtime');
19
- var client = require('@ag-ui/client');
20
- var langgraph = require('@ag-ui/langgraph');
21
15
  var agent = require('@copilotkitnext/agent');
22
16
  var pluginDeferStream = require('@graphql-yoga/plugin-defer-stream');
23
17
  var createPinoLogger = require('pino');
24
18
  var pretty = require('pino-pretty');
25
19
  var vercel = require('hono/vercel');
26
20
  var stream = require('stream');
27
- var remote = require('langchain/runnables/remote');
28
- var Anthropic = require('@anthropic-ai/sdk');
29
- var ollama = require('@langchain/community/llms/ollama');
30
- var aws = require('@langchain/aws');
31
21
 
32
22
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
33
23
 
34
- var OpenAI__default = /*#__PURE__*/_interopDefault(OpenAI);
35
24
  var createPinoLogger__default = /*#__PURE__*/_interopDefault(createPinoLogger);
36
25
  var pretty__default = /*#__PURE__*/_interopDefault(pretty);
37
- var Anthropic__default = /*#__PURE__*/_interopDefault(Anthropic);
38
26
 
39
27
  var __create = Object.create;
40
28
  var __defProp = Object.defineProperty;
@@ -43,7 +31,14 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
43
31
  var __getProtoOf = Object.getPrototypeOf;
44
32
  var __hasOwnProp = Object.prototype.hasOwnProperty;
45
33
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
46
- var __commonJS = (cb, mod) => function __require() {
34
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
35
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
36
+ }) : x)(function(x) {
37
+ if (typeof require !== "undefined")
38
+ return require.apply(this, arguments);
39
+ throw new Error('Dynamic require of "' + x + '" is not supported');
40
+ });
41
+ var __commonJS = (cb, mod) => function __require2() {
47
42
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
48
43
  };
49
44
  var __copyProps = (to, from, except, desc) => {
@@ -77,7 +72,7 @@ var require_package = __commonJS({
77
72
  publishConfig: {
78
73
  access: "public"
79
74
  },
80
- version: "1.50.0-beta.0",
75
+ version: "1.50.0-beta.9",
81
76
  sideEffects: false,
82
77
  main: "./dist/index.js",
83
78
  module: "./dist/index.mjs",
@@ -91,6 +86,11 @@ var require_package = __commonJS({
91
86
  import: "./dist/v2/index.mjs",
92
87
  require: "./dist/v2/index.js",
93
88
  types: "./dist/v2/index.d.ts"
89
+ },
90
+ "./langgraph": {
91
+ import: "./dist/langgraph.mjs",
92
+ require: "./dist/langgraph.js",
93
+ types: "./dist/langgraph.d.ts"
94
94
  }
95
95
  },
96
96
  types: "./dist/index.d.ts",
@@ -120,29 +120,21 @@ var require_package = __commonJS({
120
120
  tsconfig: "workspace:*",
121
121
  tsup: "^6.7.0",
122
122
  typescript: "^5.2.3",
123
- vitest: "^3.2.4",
124
- "zod-to-json-schema": "^3.23.5"
123
+ vitest: "^3.2.4"
125
124
  },
126
125
  dependencies: {
127
- "@anthropic-ai/sdk": "^0.57.0",
128
126
  "@copilotkit/shared": "workspace:*",
129
- "@copilotkitnext/agent": "0.0.22",
130
- "@copilotkitnext/runtime": "0.0.22",
127
+ "@copilotkitnext/agent": "0.0.28",
128
+ "@copilotkitnext/runtime": "0.0.28",
131
129
  "@graphql-yoga/plugin-defer-stream": "^3.3.1",
132
- "@langchain/aws": "^0.1.9",
133
- "@langchain/community": "^0.3.29",
130
+ "@hono/node-server": "^1.13.5",
134
131
  "@langchain/core": "^0.3.38",
135
- "@langchain/google-gauth": "^0.1.0",
136
- "@langchain/langgraph-sdk": "^0.0.70",
137
- "@langchain/openai": "^0.4.2",
138
132
  "@scarf/scarf": "^1.3.0",
139
133
  "class-transformer": "^0.5.1",
140
134
  "class-validator": "^0.14.1",
141
135
  graphql: "^16.8.1",
142
136
  "graphql-scalars": "^1.23.0",
143
137
  "graphql-yoga": "^5.3.1",
144
- "groq-sdk": "^0.5.0",
145
- "@hono/node-server": "^1.13.5",
146
138
  hono: "^4.10.3",
147
139
  langchain: "^0.3.3",
148
140
  openai: "^4.85.1",
@@ -155,11 +147,52 @@ var require_package = __commonJS({
155
147
  zod: "^3.23.3"
156
148
  },
157
149
  peerDependencies: {
158
- "@ag-ui/client": ">=0.0.39",
159
- "@ag-ui/core": ">=0.0.39",
160
- "@ag-ui/encoder": ">=0.0.39",
161
- "@ag-ui/langgraph": ">=0.0.18",
162
- "@ag-ui/proto": ">=0.0.39"
150
+ "@anthropic-ai/sdk": "^0.57.0",
151
+ "@ag-ui/client": "^0.0.42",
152
+ "@ag-ui/core": ">=0.0.42",
153
+ "@ag-ui/encoder": ">=0.0.42",
154
+ "@ag-ui/langgraph": ">=0.0.20",
155
+ "@ag-ui/proto": ">=0.0.42",
156
+ "@langchain/aws": "^0.1.9",
157
+ "@langchain/community": "^0.3.58",
158
+ "@langchain/google-gauth": "^0.1.0",
159
+ "@langchain/langgraph-sdk": "^0.0.70",
160
+ "@langchain/openai": "^0.4.2",
161
+ "groq-sdk": ">=0.3.0 <1.0.0",
162
+ langchain: "^0.3.3",
163
+ openai: "^4.85.1"
164
+ },
165
+ peerDependenciesMeta: {
166
+ "@anthropic-ai/sdk": {
167
+ optional: true
168
+ },
169
+ "@ag-ui/langgraph": {
170
+ optional: true
171
+ },
172
+ "@langchain/aws": {
173
+ optional: true
174
+ },
175
+ "@langchain/community": {
176
+ optional: true
177
+ },
178
+ "@langchain/google-gauth": {
179
+ optional: true
180
+ },
181
+ "@langchain/langgraph-sdk": {
182
+ optional: true
183
+ },
184
+ "@langchain/openai": {
185
+ optional: true
186
+ },
187
+ "groq-sdk": {
188
+ optional: true
189
+ },
190
+ langchain: {
191
+ optional: true
192
+ },
193
+ openai: {
194
+ optional: true
195
+ }
163
196
  },
164
197
  keywords: [
165
198
  "copilotkit",
@@ -410,13 +443,22 @@ var OpenAIAdapter = class {
410
443
  return "OpenAIAdapter";
411
444
  }
412
445
  constructor(params) {
413
- this._openai = (params == null ? void 0 : params.openai) || new OpenAI__default.default({});
446
+ if (params == null ? void 0 : params.openai) {
447
+ this._openai = params.openai;
448
+ }
414
449
  if (params == null ? void 0 : params.model) {
415
450
  this.model = params.model;
416
451
  }
417
452
  this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
418
453
  this.keepSystemRole = (params == null ? void 0 : params.keepSystemRole) ?? false;
419
454
  }
455
+ ensureOpenAI() {
456
+ if (!this._openai) {
457
+ const OpenAI = __require("openai").default;
458
+ this._openai = new OpenAI();
459
+ }
460
+ return this._openai;
461
+ }
420
462
  async process(request) {
421
463
  const { threadId: threadIdFromRequest, model = this.model, messages, actions, eventSource, forwardedParameters } = request;
422
464
  const tools = actions.map(convertActionInputToOpenAITool);
@@ -451,7 +493,8 @@ var OpenAIAdapter = class {
451
493
  };
452
494
  }
453
495
  try {
454
- const stream = this.openai.beta.chat.completions.stream({
496
+ const openai = this.ensureOpenAI();
497
+ const stream = openai.beta.chat.completions.stream({
455
498
  model,
456
499
  stream: true,
457
500
  messages: openaiMessages,
@@ -811,26 +854,32 @@ var LangChainAdapter = class {
811
854
  threadId
812
855
  };
813
856
  } finally {
814
- await promises.awaitAllCallbacks();
857
+ const { awaitAllCallbacks } = __require("@langchain/core/callbacks/promises");
858
+ await awaitAllCallbacks();
815
859
  }
816
860
  }
817
861
  };
818
862
  __name(LangChainAdapter, "LangChainAdapter");
863
+
864
+ // src/service-adapters/google/google-genai-adapter.ts
819
865
  var DEFAULT_MODEL2 = "gemini-1.5-pro";
820
866
  var GoogleGenerativeAIAdapter = class extends LangChainAdapter {
821
867
  provider = "google";
822
868
  model = DEFAULT_MODEL2;
823
869
  constructor(options) {
824
870
  super({
825
- chainFn: async ({ messages: messages$1, tools, threadId }) => {
826
- const filteredMessages = messages$1.filter((message) => {
827
- if (!(message instanceof messages.AIMessage)) {
871
+ chainFn: async ({ messages, tools, threadId }) => {
872
+ const { ChatGoogle } = __require("@langchain/google-gauth");
873
+ const { AIMessage: AIMessage2 } = __require("@langchain/core/messages");
874
+ const filteredMessages = messages.filter((message) => {
875
+ if (!(message instanceof AIMessage2)) {
828
876
  return true;
829
877
  }
830
- return message.content && String(message.content).trim().length > 0 || message.tool_calls && message.tool_calls.length > 0;
878
+ const aiMsg = message;
879
+ return aiMsg.content && String(aiMsg.content).trim().length > 0 || aiMsg.tool_calls && aiMsg.tool_calls.length > 0;
831
880
  });
832
881
  this.model = (options == null ? void 0 : options.model) ?? "gemini-1.5-pro";
833
- const model = new googleGauth.ChatGoogle({
882
+ const model = new ChatGoogle({
834
883
  apiKey: (options == null ? void 0 : options.apiKey) ?? process.env.GOOGLE_API_KEY,
835
884
  modelName: this.model,
836
885
  apiVersion: "v1beta"
@@ -845,8 +894,10 @@ var GoogleGenerativeAIAdapter = class extends LangChainAdapter {
845
894
  }
846
895
  };
847
896
  __name(GoogleGenerativeAIAdapter, "GoogleGenerativeAIAdapter");
897
+
898
+ // src/service-adapters/openai/openai-assistant-adapter.ts
848
899
  var OpenAIAssistantAdapter = class {
849
- openai;
900
+ _openai;
850
901
  codeInterpreterEnabled;
851
902
  assistantId;
852
903
  fileSearchEnabled;
@@ -856,19 +907,29 @@ var OpenAIAssistantAdapter = class {
856
907
  return "OpenAIAssistantAdapter";
857
908
  }
858
909
  constructor(params) {
859
- this.openai = params.openai || new OpenAI__default.default({});
910
+ if (params.openai) {
911
+ this._openai = params.openai;
912
+ }
860
913
  this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;
861
914
  this.fileSearchEnabled = params.fileSearchEnabled === false || true;
862
915
  this.assistantId = params.assistantId;
863
916
  this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
864
917
  this.keepSystemRole = (params == null ? void 0 : params.keepSystemRole) ?? false;
865
918
  }
919
+ ensureOpenAI() {
920
+ if (!this._openai) {
921
+ const OpenAI = __require("openai").default;
922
+ this._openai = new OpenAI({});
923
+ }
924
+ return this._openai;
925
+ }
866
926
  async process(request) {
867
927
  var _a, _b;
868
928
  const { messages, actions, eventSource, runId, forwardedParameters } = request;
869
929
  let threadId = (_b = (_a = request.extensions) == null ? void 0 : _a.openaiAssistantAPI) == null ? void 0 : _b.threadId;
930
+ const openai = this.ensureOpenAI();
870
931
  if (!threadId) {
871
- threadId = (await this.openai.beta.threads.create()).id;
932
+ threadId = (await openai.beta.threads.create()).id;
872
933
  }
873
934
  const lastMessage = messages.at(-1);
874
935
  let nextRunId = void 0;
@@ -892,7 +953,8 @@ var OpenAIAssistantAdapter = class {
892
953
  };
893
954
  }
894
955
  async submitToolOutputs(threadId, runId, messages, eventSource) {
895
- let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);
956
+ const openai = this.ensureOpenAI();
957
+ let run = await openai.beta.threads.runs.retrieve(threadId, runId);
896
958
  if (!run.required_action) {
897
959
  throw new Error("No tool outputs required");
898
960
  }
@@ -907,7 +969,7 @@ var OpenAIAssistantAdapter = class {
907
969
  output: message.result
908
970
  };
909
971
  });
910
- const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {
972
+ const stream = openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {
911
973
  tool_outputs: toolOutputs,
912
974
  ...this.disableParallelToolCalls && {
913
975
  parallel_tool_calls: false
@@ -917,6 +979,7 @@ var OpenAIAssistantAdapter = class {
917
979
  return runId;
918
980
  }
919
981
  async submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters) {
982
+ const openai = this.ensureOpenAI();
920
983
  messages = [
921
984
  ...messages
922
985
  ];
@@ -928,7 +991,7 @@ var OpenAIAssistantAdapter = class {
928
991
  if (userMessage.role !== "user") {
929
992
  throw new Error("No user message found");
930
993
  }
931
- await this.openai.beta.threads.messages.create(threadId, {
994
+ await openai.beta.threads.messages.create(threadId, {
932
995
  role: "user",
933
996
  content: userMessage.content
934
997
  });
@@ -946,7 +1009,7 @@ var OpenAIAssistantAdapter = class {
946
1009
  }
947
1010
  ] : []
948
1011
  ];
949
- let stream = this.openai.beta.threads.runs.stream(threadId, {
1012
+ let stream = openai.beta.threads.runs.stream(threadId, {
950
1013
  assistant_id: this.assistantId,
951
1014
  instructions,
952
1015
  tools,
@@ -1065,7 +1128,8 @@ var UnifyAdapter = class {
1065
1128
  }
1066
1129
  async process(request) {
1067
1130
  const tools = request.actions.map(convertActionInputToOpenAITool);
1068
- const openai = new OpenAI__default.default({
1131
+ const OpenAI = __require("openai").default;
1132
+ const openai = new OpenAI({
1069
1133
  apiKey: this.apiKey,
1070
1134
  baseURL: "https://api.unify.ai/v0/"
1071
1135
  });
@@ -1176,12 +1240,21 @@ var GroqAdapter = class {
1176
1240
  return "GroqAdapter";
1177
1241
  }
1178
1242
  constructor(params) {
1179
- this._groq = (params == null ? void 0 : params.groq) || new groqSdk.Groq({});
1243
+ if (params == null ? void 0 : params.groq) {
1244
+ this._groq = params.groq;
1245
+ }
1180
1246
  if (params == null ? void 0 : params.model) {
1181
1247
  this.model = params.model;
1182
1248
  }
1183
1249
  this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
1184
1250
  }
1251
+ ensureGroq() {
1252
+ if (!this._groq) {
1253
+ const { Groq } = __require("groq-sdk");
1254
+ this._groq = new Groq({});
1255
+ }
1256
+ return this._groq;
1257
+ }
1185
1258
  async process(request) {
1186
1259
  const { threadId, model = this.model, messages, actions, eventSource, forwardedParameters } = request;
1187
1260
  const tools = actions.map(convertActionInputToOpenAITool);
@@ -1200,7 +1273,8 @@ var GroqAdapter = class {
1200
1273
  }
1201
1274
  let stream;
1202
1275
  try {
1203
- stream = await this.groq.chat.completions.create({
1276
+ const groq = this.ensureGroq();
1277
+ stream = await groq.chat.completions.create({
1204
1278
  model,
1205
1279
  stream: true,
1206
1280
  messages: openaiMessages,
@@ -3166,6 +3240,82 @@ function aguiMessageWithImageToGQLMessage(message) {
3166
3240
  });
3167
3241
  }
3168
3242
  __name(aguiMessageWithImageToGQLMessage, "aguiMessageWithImageToGQLMessage");
3243
+ var TelemetryAgentRunner = class {
3244
+ _runner;
3245
+ hashedLgcKey;
3246
+ constructor(config2) {
3247
+ this._runner = (config2 == null ? void 0 : config2.runner) ?? new runtime.InMemoryAgentRunner();
3248
+ this.hashedLgcKey = (config2 == null ? void 0 : config2.langsmithApiKey) ? crypto.createHash("sha256").update(config2.langsmithApiKey).digest("hex") : void 0;
3249
+ }
3250
+ /**
3251
+ * Runs an agent with telemetry tracking.
3252
+ * Wraps the underlying runner's Observable stream with telemetry events.
3253
+ */
3254
+ run(...args) {
3255
+ const streamInfo = {
3256
+ hashedLgcKey: this.hashedLgcKey
3257
+ };
3258
+ let streamErrored = false;
3259
+ telemetry_client_default.capture("oss.runtime.agent_execution_stream_started", {
3260
+ hashedLgcKey: this.hashedLgcKey
3261
+ });
3262
+ return this._runner.run(...args).pipe(
3263
+ // Extract metadata from events if available
3264
+ rxjs.tap((event) => {
3265
+ var _a;
3266
+ const rawEvent = event.rawEvent;
3267
+ if (rawEvent == null ? void 0 : rawEvent.data) {
3268
+ const data = rawEvent.data;
3269
+ if ((_a = data == null ? void 0 : data.output) == null ? void 0 : _a.model) {
3270
+ streamInfo.model = data.output.model;
3271
+ streamInfo.provider = data.output.model;
3272
+ }
3273
+ }
3274
+ if (rawEvent == null ? void 0 : rawEvent.metadata) {
3275
+ const metadata = rawEvent.metadata;
3276
+ if (metadata == null ? void 0 : metadata.langgraph_host) {
3277
+ streamInfo.langGraphHost = metadata.langgraph_host;
3278
+ }
3279
+ if (metadata == null ? void 0 : metadata.langgraph_version) {
3280
+ streamInfo.langGraphVersion = metadata.langgraph_version;
3281
+ }
3282
+ }
3283
+ }),
3284
+ rxjs.catchError((error) => {
3285
+ streamErrored = true;
3286
+ telemetry_client_default.capture("oss.runtime.agent_execution_stream_errored", {
3287
+ ...streamInfo,
3288
+ error: error instanceof Error ? error.message : String(error)
3289
+ });
3290
+ throw error;
3291
+ }),
3292
+ rxjs.finalize(() => {
3293
+ if (!streamErrored) {
3294
+ telemetry_client_default.capture("oss.runtime.agent_execution_stream_ended", streamInfo);
3295
+ }
3296
+ })
3297
+ );
3298
+ }
3299
+ /**
3300
+ * Delegates to the underlying runner's connect method
3301
+ */
3302
+ connect(...args) {
3303
+ return this._runner.connect(...args);
3304
+ }
3305
+ /**
3306
+ * Delegates to the underlying runner's isRunning method
3307
+ */
3308
+ isRunning(...args) {
3309
+ return this._runner.isRunning(...args);
3310
+ }
3311
+ /**
3312
+ * Delegates to the underlying runner's stop method
3313
+ */
3314
+ stop(...args) {
3315
+ return this._runner.stop(...args);
3316
+ }
3317
+ };
3318
+ __name(TelemetryAgentRunner, "TelemetryAgentRunner");
3169
3319
 
3170
3320
  // src/lib/runtime/types.ts
3171
3321
  var EndpointType;
@@ -3309,199 +3459,6 @@ When using these tools:
3309
3459
  7. Always check tool responses to determine your next action`;
3310
3460
  }
3311
3461
  __name(generateMcpToolInstructions, "generateMcpToolInstructions");
3312
-
3313
- // src/agents/langgraph/events.ts
3314
- var LangGraphEventTypes;
3315
- (function(LangGraphEventTypes2) {
3316
- LangGraphEventTypes2["OnChainStart"] = "on_chain_start";
3317
- LangGraphEventTypes2["OnChainStream"] = "on_chain_stream";
3318
- LangGraphEventTypes2["OnChainEnd"] = "on_chain_end";
3319
- LangGraphEventTypes2["OnChatModelStart"] = "on_chat_model_start";
3320
- LangGraphEventTypes2["OnChatModelStream"] = "on_chat_model_stream";
3321
- LangGraphEventTypes2["OnChatModelEnd"] = "on_chat_model_end";
3322
- LangGraphEventTypes2["OnToolStart"] = "on_tool_start";
3323
- LangGraphEventTypes2["OnToolEnd"] = "on_tool_end";
3324
- LangGraphEventTypes2["OnCopilotKitStateSync"] = "on_copilotkit_state_sync";
3325
- LangGraphEventTypes2["OnCopilotKitEmitMessage"] = "on_copilotkit_emit_message";
3326
- LangGraphEventTypes2["OnCopilotKitEmitToolCall"] = "on_copilotkit_emit_tool_call";
3327
- LangGraphEventTypes2["OnCustomEvent"] = "on_custom_event";
3328
- LangGraphEventTypes2["OnInterrupt"] = "on_interrupt";
3329
- LangGraphEventTypes2["OnCopilotKitInterrupt"] = "on_copilotkit_interrupt";
3330
- LangGraphEventTypes2["OnCopilotKitError"] = "on_copilotkit_error";
3331
- })(LangGraphEventTypes || (LangGraphEventTypes = {}));
3332
- var MetaEventNames;
3333
- (function(MetaEventNames2) {
3334
- MetaEventNames2["LangGraphInterruptEvent"] = "LangGraphInterruptEvent";
3335
- MetaEventNames2["CopilotKitLangGraphInterruptEvent"] = "CopilotKitLangGraphInterruptEvent";
3336
- })(MetaEventNames || (MetaEventNames = {}));
3337
- var CustomEventNames;
3338
- (function(CustomEventNames3) {
3339
- CustomEventNames3["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
3340
- CustomEventNames3["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
3341
- CustomEventNames3["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
3342
- CustomEventNames3["CopilotKitExit"] = "copilotkit_exit";
3343
- })(CustomEventNames || (CustomEventNames = {}));
3344
- exports.CustomEventNames = void 0;
3345
- (function(CustomEventNames3) {
3346
- CustomEventNames3["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
3347
- CustomEventNames3["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
3348
- CustomEventNames3["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
3349
- CustomEventNames3["CopilotKitExit"] = "copilotkit_exit";
3350
- })(exports.CustomEventNames || (exports.CustomEventNames = {}));
3351
- var LangGraphAgent = class extends langgraph.LangGraphAgent {
3352
- constructor(config2) {
3353
- super(config2);
3354
- }
3355
- // @ts-ignore
3356
- clone() {
3357
- return new LangGraphAgent(this.config);
3358
- }
3359
- dispatchEvent(event) {
3360
- if (event.type === client.EventType.CUSTOM) {
3361
- const customEvent = event;
3362
- if (customEvent.name === "copilotkit_manually_emit_message") {
3363
- this.subscriber.next({
3364
- type: client.EventType.TEXT_MESSAGE_START,
3365
- role: "assistant",
3366
- messageId: customEvent.value.message_id,
3367
- rawEvent: event
3368
- });
3369
- this.subscriber.next({
3370
- type: client.EventType.TEXT_MESSAGE_CONTENT,
3371
- messageId: customEvent.value.message_id,
3372
- delta: customEvent.value.message,
3373
- rawEvent: event
3374
- });
3375
- this.subscriber.next({
3376
- type: client.EventType.TEXT_MESSAGE_END,
3377
- messageId: customEvent.value.message_id,
3378
- rawEvent: event
3379
- });
3380
- return true;
3381
- }
3382
- if (customEvent.name === "copilotkit_manually_emit_tool_call") {
3383
- this.subscriber.next({
3384
- type: client.EventType.TOOL_CALL_START,
3385
- toolCallId: customEvent.value.id,
3386
- toolCallName: customEvent.value.name,
3387
- parentMessageId: customEvent.value.id,
3388
- rawEvent: event
3389
- });
3390
- this.subscriber.next({
3391
- type: client.EventType.TOOL_CALL_ARGS,
3392
- toolCallId: customEvent.value.id,
3393
- delta: customEvent.value.args,
3394
- rawEvent: event
3395
- });
3396
- this.subscriber.next({
3397
- type: client.EventType.TOOL_CALL_END,
3398
- toolCallId: customEvent.value.id,
3399
- rawEvent: event
3400
- });
3401
- return true;
3402
- }
3403
- if (customEvent.name === "copilotkit_manually_emit_intermediate_state") {
3404
- this.activeRun.manuallyEmittedState = customEvent.value;
3405
- this.dispatchEvent({
3406
- type: client.EventType.STATE_SNAPSHOT,
3407
- snapshot: this.getStateSnapshot({
3408
- values: this.activeRun.manuallyEmittedState
3409
- }),
3410
- rawEvent: event
3411
- });
3412
- return true;
3413
- }
3414
- if (customEvent.name === "copilotkit_exit") {
3415
- this.subscriber.next({
3416
- type: client.EventType.CUSTOM,
3417
- name: "Exit",
3418
- value: true
3419
- });
3420
- return true;
3421
- }
3422
- }
3423
- const rawEvent = event.rawEvent;
3424
- if (!rawEvent) {
3425
- this.subscriber.next(event);
3426
- return true;
3427
- }
3428
- const isMessageEvent = event.type === client.EventType.TEXT_MESSAGE_START || event.type === client.EventType.TEXT_MESSAGE_CONTENT || event.type === client.EventType.TEXT_MESSAGE_END;
3429
- const isToolEvent = event.type === client.EventType.TOOL_CALL_START || event.type === client.EventType.TOOL_CALL_ARGS || event.type === client.EventType.TOOL_CALL_END;
3430
- if ("copilotkit:emit-tool-calls" in (rawEvent.metadata || {})) {
3431
- if (rawEvent.metadata["copilotkit:emit-tool-calls"] === false && isToolEvent) {
3432
- return false;
3433
- }
3434
- }
3435
- if ("copilotkit:emit-messages" in (rawEvent.metadata || {})) {
3436
- if (rawEvent.metadata["copilotkit:emit-messages"] === false && isMessageEvent) {
3437
- return false;
3438
- }
3439
- }
3440
- this.subscriber.next(event);
3441
- return true;
3442
- }
3443
- // @ts-ignore
3444
- run(input) {
3445
- return super.run(input).pipe(rxjs.map((processedEvent) => {
3446
- var _a, _b, _c, _d, _e;
3447
- if (processedEvent.type === client.EventType.RAW) {
3448
- const event = processedEvent.event ?? processedEvent.rawEvent;
3449
- const eventType = event.event;
3450
- const toolCallData = (_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.tool_call_chunks) == null ? void 0 : _c[0];
3451
- const toolCallUsedToPredictState = (_e = (_d = event.metadata) == null ? void 0 : _d["copilotkit:emit-intermediate-state"]) == null ? void 0 : _e.some((predictStateTool) => predictStateTool.tool === (toolCallData == null ? void 0 : toolCallData.name));
3452
- if (eventType === LangGraphEventTypes.OnChatModelStream && toolCallUsedToPredictState) {
3453
- return {
3454
- type: client.EventType.CUSTOM,
3455
- name: "PredictState",
3456
- value: event.metadata["copilotkit:emit-intermediate-state"]
3457
- };
3458
- }
3459
- }
3460
- return processedEvent;
3461
- }));
3462
- }
3463
- langGraphDefaultMergeState(state, messages, input) {
3464
- const aguiMergedState = super.langGraphDefaultMergeState(state, messages, input);
3465
- const { tools: returnedTools, "ag-ui": agui } = aguiMergedState;
3466
- const rawCombinedTools = [
3467
- ...returnedTools ?? [],
3468
- ...(agui == null ? void 0 : agui.tools) ?? []
3469
- ];
3470
- const combinedTools = Array.from(new Map(rawCombinedTools.map((t) => [
3471
- (t == null ? void 0 : t.id) ?? (t == null ? void 0 : t.name) ?? (t == null ? void 0 : t.key) ?? JSON.stringify(t),
3472
- t
3473
- ])).values());
3474
- return {
3475
- ...aguiMergedState,
3476
- copilotkit: {
3477
- actions: combinedTools,
3478
- context: (agui == null ? void 0 : agui.context) ?? []
3479
- }
3480
- };
3481
- }
3482
- async getSchemaKeys() {
3483
- const CONSTANT_KEYS = [
3484
- "copilotkit"
3485
- ];
3486
- const schemaKeys = await super.getSchemaKeys();
3487
- return {
3488
- config: schemaKeys.config,
3489
- input: schemaKeys.input ? [
3490
- ...schemaKeys.input,
3491
- ...CONSTANT_KEYS
3492
- ] : null,
3493
- output: schemaKeys.output ? [
3494
- ...schemaKeys.output,
3495
- ...CONSTANT_KEYS
3496
- ] : null,
3497
- context: schemaKeys.context ? [
3498
- ...schemaKeys.context,
3499
- ...CONSTANT_KEYS
3500
- ] : null
3501
- };
3502
- }
3503
- };
3504
- __name(LangGraphAgent, "LangGraphAgent");
3505
3462
  var CopilotRuntime = class {
3506
3463
  params;
3507
3464
  observability;
@@ -3511,12 +3468,15 @@ var CopilotRuntime = class {
3511
3468
  _instance;
3512
3469
  constructor(params) {
3513
3470
  const agents = (params == null ? void 0 : params.agents) ?? {};
3471
+ const endpointAgents = this.assignEndpointsToAgents((params == null ? void 0 : params.remoteEndpoints) ?? []);
3514
3472
  this.runtimeArgs = {
3515
3473
  agents: {
3516
- ...this.assignEndpointsToAgents((params == null ? void 0 : params.remoteEndpoints) ?? []),
3474
+ ...endpointAgents,
3517
3475
  ...agents
3518
3476
  },
3519
- runner: (params == null ? void 0 : params.runner) ?? new runtime.InMemoryAgentRunner(),
3477
+ // Use TelemetryAgentRunner by default to track agent execution telemetry
3478
+ // Users can pass their own runner which will be wrapped for telemetry
3479
+ runner: (params == null ? void 0 : params.runner) ?? new TelemetryAgentRunner(),
3520
3480
  // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready
3521
3481
  // transcriptionService: params?.transcriptionService,
3522
3482
  beforeRequestMiddleware: this.createOnBeforeRequestHandler(params).bind(this),
@@ -3532,29 +3492,16 @@ var CopilotRuntime = class {
3532
3492
  return this._instance;
3533
3493
  }
3534
3494
  assignEndpointsToAgents(endpoints) {
3535
- return endpoints.reduce((acc, endpoint) => {
3536
- if (resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform) {
3537
- let lgAgents = {};
3538
- const lgEndpoint = endpoint;
3539
- lgEndpoint.agents.forEach((agent) => {
3540
- const graphId = agent.assistantId ?? agent.name;
3541
- lgAgents[graphId] = new LangGraphAgent({
3542
- deploymentUrl: lgEndpoint.deploymentUrl,
3543
- langsmithApiKey: lgEndpoint.langsmithApiKey,
3544
- graphId
3545
- });
3546
- });
3547
- return {
3548
- ...acc,
3549
- ...lgAgents
3550
- };
3551
- }
3552
- return acc;
3553
- }, {});
3495
+ let result = {};
3496
+ if (endpoints.some((endpoint) => resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform)) {
3497
+ throw new shared.CopilotKitMisuseError({
3498
+ message: 'LangGraphPlatformEndpoint in remoteEndpoints is deprecated. Please use the "agents" option instead with LangGraphAgent from "@copilotkit/runtime/langgraph". Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: "...", graphId: "..." }) }'
3499
+ });
3500
+ }
3501
+ return result;
3554
3502
  }
3555
3503
  handleServiceAdapter(serviceAdapter) {
3556
3504
  this.runtimeArgs.agents = Promise.resolve(this.runtimeArgs.agents ?? {}).then(async (agents) => {
3557
- var _a;
3558
3505
  let agentsList = agents;
3559
3506
  const isAgentsListEmpty = !Object.keys(agents).length;
3560
3507
  const hasServiceAdapter = Boolean(serviceAdapter);
@@ -3572,7 +3519,7 @@ var CopilotRuntime = class {
3572
3519
  model: `${serviceAdapter.provider}/${serviceAdapter.model}`
3573
3520
  });
3574
3521
  }
3575
- if ((_a = this.params.actions) == null ? void 0 : _a.length) {
3522
+ if (this.params.actions) {
3576
3523
  const mcpTools = await this.getToolsFromMCP();
3577
3524
  agentsList = this.assignToolsToAgents(agents, [
3578
3525
  ...this.getToolsFromActions(this.params.actions),
@@ -3593,7 +3540,8 @@ var CopilotRuntime = class {
3593
3540
  return {
3594
3541
  name: action.name,
3595
3542
  description: action.description || "",
3596
- parameters: zodSchema
3543
+ parameters: zodSchema,
3544
+ execute: () => Promise.resolve()
3597
3545
  };
3598
3546
  });
3599
3547
  }
@@ -3744,7 +3692,8 @@ var CopilotRuntime = class {
3744
3692
  return {
3745
3693
  name: toolName,
3746
3694
  description: tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,
3747
- parameters: zodSchema
3695
+ parameters: zodSchema,
3696
+ execute: () => Promise.resolve()
3748
3697
  };
3749
3698
  });
3750
3699
  this.mcpToolsCache.set(endpointUrl, toolDefs);
@@ -3895,6 +3844,38 @@ _ts_decorate19([
3895
3844
  AgentsResponse = _ts_decorate19([
3896
3845
  typeGraphql.ObjectType()
3897
3846
  ], AgentsResponse);
3847
+
3848
+ // src/agents/langgraph/events.ts
3849
+ var LangGraphEventTypes;
3850
+ (function(LangGraphEventTypes2) {
3851
+ LangGraphEventTypes2["OnChainStart"] = "on_chain_start";
3852
+ LangGraphEventTypes2["OnChainStream"] = "on_chain_stream";
3853
+ LangGraphEventTypes2["OnChainEnd"] = "on_chain_end";
3854
+ LangGraphEventTypes2["OnChatModelStart"] = "on_chat_model_start";
3855
+ LangGraphEventTypes2["OnChatModelStream"] = "on_chat_model_stream";
3856
+ LangGraphEventTypes2["OnChatModelEnd"] = "on_chat_model_end";
3857
+ LangGraphEventTypes2["OnToolStart"] = "on_tool_start";
3858
+ LangGraphEventTypes2["OnToolEnd"] = "on_tool_end";
3859
+ LangGraphEventTypes2["OnCopilotKitStateSync"] = "on_copilotkit_state_sync";
3860
+ LangGraphEventTypes2["OnCopilotKitEmitMessage"] = "on_copilotkit_emit_message";
3861
+ LangGraphEventTypes2["OnCopilotKitEmitToolCall"] = "on_copilotkit_emit_tool_call";
3862
+ LangGraphEventTypes2["OnCustomEvent"] = "on_custom_event";
3863
+ LangGraphEventTypes2["OnInterrupt"] = "on_interrupt";
3864
+ LangGraphEventTypes2["OnCopilotKitInterrupt"] = "on_copilotkit_interrupt";
3865
+ LangGraphEventTypes2["OnCopilotKitError"] = "on_copilotkit_error";
3866
+ })(LangGraphEventTypes || (LangGraphEventTypes = {}));
3867
+ var MetaEventNames;
3868
+ (function(MetaEventNames2) {
3869
+ MetaEventNames2["LangGraphInterruptEvent"] = "LangGraphInterruptEvent";
3870
+ MetaEventNames2["CopilotKitLangGraphInterruptEvent"] = "CopilotKitLangGraphInterruptEvent";
3871
+ })(MetaEventNames || (MetaEventNames = {}));
3872
+ var CustomEventNames;
3873
+ (function(CustomEventNames2) {
3874
+ CustomEventNames2["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
3875
+ CustomEventNames2["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
3876
+ CustomEventNames2["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
3877
+ CustomEventNames2["CopilotKitExit"] = "copilotkit_exit";
3878
+ })(CustomEventNames || (CustomEventNames = {}));
3898
3879
  function _ts_decorate20(decorators, target, key, desc) {
3899
3880
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3900
3881
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -4726,7 +4707,9 @@ function copilotRuntimeNextJSAppRouterEndpoint(options) {
4726
4707
  const logger2 = commonConfig.logging;
4727
4708
  logger2.debug("Creating NextJS App Router endpoint");
4728
4709
  const serviceAdapter = options.serviceAdapter;
4729
- options.runtime.handleServiceAdapter(serviceAdapter);
4710
+ if (serviceAdapter) {
4711
+ options.runtime.handleServiceAdapter(serviceAdapter);
4712
+ }
4730
4713
  const copilotRoute = runtime.createCopilotEndpointSingleRoute({
4731
4714
  runtime: options.runtime.instance,
4732
4715
  basePath: options.baseUrl ?? options.endpoint
@@ -4756,12 +4739,59 @@ function readableStreamToNodeStream(webStream) {
4756
4739
  }
4757
4740
  __name(readableStreamToNodeStream, "readableStreamToNodeStream");
4758
4741
  function getFullUrl(req) {
4759
- const path = req.url || "/";
4742
+ const expressPath = req.originalUrl ?? (req.baseUrl ? `${req.baseUrl}${req.url ?? ""}` : void 0);
4743
+ const path = expressPath || req.url || "/";
4760
4744
  const host = req.headers["x-forwarded-host"] || req.headers.host || "localhost";
4761
4745
  const proto = req.headers["x-forwarded-proto"] || (req.socket.encrypted ? "https" : "http");
4762
4746
  return `${proto}://${host}${path}`;
4763
4747
  }
4764
4748
  __name(getFullUrl, "getFullUrl");
4749
+ function toHeaders(rawHeaders) {
4750
+ const headers = new Headers();
4751
+ for (const [key, value] of Object.entries(rawHeaders)) {
4752
+ if (value === void 0)
4753
+ continue;
4754
+ if (Array.isArray(value)) {
4755
+ value.forEach((entry) => headers.append(key, entry));
4756
+ continue;
4757
+ }
4758
+ headers.append(key, value);
4759
+ }
4760
+ return headers;
4761
+ }
4762
+ __name(toHeaders, "toHeaders");
4763
+ function isStreamConsumed(req) {
4764
+ const readableState = req._readableState;
4765
+ return Boolean(req.readableEnded || req.complete || (readableState == null ? void 0 : readableState.ended) || (readableState == null ? void 0 : readableState.endEmitted));
4766
+ }
4767
+ __name(isStreamConsumed, "isStreamConsumed");
4768
+ function synthesizeBodyFromParsedBody(parsedBody, headers) {
4769
+ if (parsedBody === null || parsedBody === void 0) {
4770
+ return {
4771
+ body: null
4772
+ };
4773
+ }
4774
+ if (parsedBody instanceof Buffer || parsedBody instanceof Uint8Array) {
4775
+ return {
4776
+ body: parsedBody
4777
+ };
4778
+ }
4779
+ if (typeof parsedBody === "string") {
4780
+ return {
4781
+ body: parsedBody,
4782
+ contentType: headers.get("content-type") ?? "text/plain"
4783
+ };
4784
+ }
4785
+ return {
4786
+ body: JSON.stringify(parsedBody),
4787
+ contentType: "application/json"
4788
+ };
4789
+ }
4790
+ __name(synthesizeBodyFromParsedBody, "synthesizeBodyFromParsedBody");
4791
+ function isDisturbedOrLockedError(error) {
4792
+ return error instanceof TypeError && typeof error.message === "string" && (error.message.includes("disturbed") || error.message.includes("locked"));
4793
+ }
4794
+ __name(isDisturbedOrLockedError, "isDisturbedOrLockedError");
4765
4795
  function copilotRuntimeNodeHttpEndpoint(options) {
4766
4796
  var _a;
4767
4797
  const commonConfig = getCommonConfig(options);
@@ -4779,7 +4809,9 @@ function copilotRuntimeNodeHttpEndpoint(options) {
4779
4809
  const logger2 = commonConfig.logging;
4780
4810
  logger2.debug("Creating Node HTTP endpoint");
4781
4811
  const serviceAdapter = options.serviceAdapter;
4782
- options.runtime.handleServiceAdapter(serviceAdapter);
4812
+ if (serviceAdapter) {
4813
+ options.runtime.handleServiceAdapter(serviceAdapter);
4814
+ }
4783
4815
  const honoApp = runtime.createCopilotEndpointSingleRoute({
4784
4816
  runtime: options.runtime.instance,
4785
4817
  basePath: options.baseUrl ?? options.endpoint
@@ -4787,14 +4819,59 @@ function copilotRuntimeNodeHttpEndpoint(options) {
4787
4819
  return /* @__PURE__ */ __name(async function handler(req, res) {
4788
4820
  const url = getFullUrl(req);
4789
4821
  const hasBody = req.method !== "GET" && req.method !== "HEAD";
4790
- const request = new Request(url, {
4822
+ const baseHeaders = toHeaders(req.headers);
4823
+ const parsedBody = req.body;
4824
+ const streamConsumed = isStreamConsumed(req) || parsedBody !== void 0;
4825
+ const canStream = hasBody && !streamConsumed;
4826
+ let requestBody = void 0;
4827
+ let useDuplex = false;
4828
+ if (hasBody && canStream) {
4829
+ requestBody = req;
4830
+ useDuplex = true;
4831
+ }
4832
+ if (hasBody && streamConsumed) {
4833
+ if (parsedBody !== void 0) {
4834
+ const synthesized = synthesizeBodyFromParsedBody(parsedBody, baseHeaders);
4835
+ requestBody = synthesized.body ?? void 0;
4836
+ baseHeaders.delete("content-length");
4837
+ if (synthesized.contentType) {
4838
+ baseHeaders.set("content-type", synthesized.contentType);
4839
+ }
4840
+ logger2.debug("Request stream already consumed; using parsed req.body to rebuild request.");
4841
+ } else {
4842
+ logger2.warn("Request stream consumed with no available body; sending empty payload.");
4843
+ requestBody = void 0;
4844
+ }
4845
+ }
4846
+ const buildRequest = /* @__PURE__ */ __name((body, headers, duplex) => new Request(url, {
4791
4847
  method: req.method,
4792
- headers: req.headers,
4793
- body: hasBody ? req : void 0,
4794
- // Node/undici extension
4795
- duplex: hasBody ? "half" : void 0
4796
- });
4797
- const response = await honoApp.fetch(request);
4848
+ headers,
4849
+ body,
4850
+ duplex: duplex ? "half" : void 0
4851
+ }), "buildRequest");
4852
+ let response;
4853
+ try {
4854
+ response = await honoApp.fetch(buildRequest(requestBody, baseHeaders, useDuplex));
4855
+ } catch (error) {
4856
+ if (isDisturbedOrLockedError(error) && hasBody) {
4857
+ logger2.warn("Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.");
4858
+ const fallbackHeaders = new Headers(baseHeaders);
4859
+ let fallbackBody;
4860
+ if (parsedBody !== void 0) {
4861
+ const synthesized = synthesizeBodyFromParsedBody(parsedBody, fallbackHeaders);
4862
+ fallbackBody = synthesized.body ?? void 0;
4863
+ fallbackHeaders.delete("content-length");
4864
+ if (synthesized.contentType) {
4865
+ fallbackHeaders.set("content-type", synthesized.contentType);
4866
+ }
4867
+ } else {
4868
+ fallbackBody = void 0;
4869
+ }
4870
+ response = await honoApp.fetch(buildRequest(fallbackBody, fallbackHeaders, false));
4871
+ } else {
4872
+ throw error;
4873
+ }
4874
+ }
4798
4875
  res.statusCode = response.status;
4799
4876
  response.headers.forEach((value, key) => {
4800
4877
  res.setHeader(key, value);
@@ -4857,6 +4934,22 @@ function copilotRuntimeNestEndpoint(options) {
4857
4934
  return copilotRuntimeNodeHttpEndpoint(options);
4858
4935
  }
4859
4936
  __name(copilotRuntimeNestEndpoint, "copilotRuntimeNestEndpoint");
4937
+
4938
+ // src/lib/index.ts
4939
+ var LangGraphAgent = class {
4940
+ constructor() {
4941
+ throw new Error("LangGraphAgent import from @copilotkit/runtime is deprecated. Please import it from @copilotkit/runtime/langgraph instead");
4942
+ }
4943
+ };
4944
+ __name(LangGraphAgent, "LangGraphAgent");
4945
+ var LangGraphHttpAgent = class {
4946
+ constructor() {
4947
+ throw new Error("LangGraphHttpAgent import from @copilotkit/runtime is deprecated. Please import it from @copilotkit/runtime/langgraph instead");
4948
+ }
4949
+ };
4950
+ __name(LangGraphHttpAgent, "LangGraphHttpAgent");
4951
+
4952
+ // src/service-adapters/langchain/langserve.ts
4860
4953
  var RemoteChain = class {
4861
4954
  name;
4862
4955
  description;
@@ -4879,7 +4972,8 @@ var RemoteChain = class {
4879
4972
  description: this.description,
4880
4973
  parameters: this.parameters,
4881
4974
  handler: async (args) => {
4882
- const runnable = new remote.RemoteRunnable({
4975
+ const { RemoteRunnable } = __require("langchain/runnables/remote");
4976
+ const runnable = new RemoteRunnable({
4883
4977
  url: this.chainUrl
4884
4978
  });
4885
4979
  let input;
@@ -5091,7 +5185,9 @@ var AnthropicAdapter = class {
5091
5185
  return "AnthropicAdapter";
5092
5186
  }
5093
5187
  constructor(params) {
5094
- this._anthropic = (params == null ? void 0 : params.anthropic) || new Anthropic__default.default({});
5188
+ if (params == null ? void 0 : params.anthropic) {
5189
+ this._anthropic = params.anthropic;
5190
+ }
5095
5191
  if (params == null ? void 0 : params.model) {
5096
5192
  this.model = params.model;
5097
5193
  }
@@ -5099,6 +5195,13 @@ var AnthropicAdapter = class {
5099
5195
  enabled: false
5100
5196
  };
5101
5197
  }
5198
+ ensureAnthropic() {
5199
+ if (!this._anthropic) {
5200
+ const Anthropic = __require("@anthropic-ai/sdk").default;
5201
+ this._anthropic = new Anthropic({});
5202
+ }
5203
+ return this._anthropic;
5204
+ }
5102
5205
  /**
5103
5206
  * Adds cache control to system prompt
5104
5207
  */
@@ -5239,7 +5342,8 @@ var AnthropicAdapter = class {
5239
5342
  },
5240
5343
  stream: true
5241
5344
  };
5242
- const stream = await this.anthropic.messages.create(createParams);
5345
+ const anthropic = this.ensureAnthropic();
5346
+ const stream = await anthropic.messages.create(createParams);
5243
5347
  eventSource.stream(async (eventStream$) => {
5244
5348
  let mode = null;
5245
5349
  let didOutputText = false;
@@ -5384,11 +5488,12 @@ var ExperimentalOllamaAdapter = class {
5384
5488
  }
5385
5489
  async process(request) {
5386
5490
  const { messages, actions, eventSource } = request;
5387
- const ollama$1 = new ollama.Ollama({
5491
+ const { Ollama } = __require("@langchain/community/llms/ollama");
5492
+ const ollama = new Ollama({
5388
5493
  model: this.model
5389
5494
  });
5390
5495
  const contents = messages.filter((m) => m.isTextMessage()).map((m) => m.content);
5391
- const _stream = await ollama$1.stream(contents);
5496
+ const _stream = await ollama.stream(contents);
5392
5497
  eventSource.stream(async (eventStream$) => {
5393
5498
  const currentMessageId = shared.randomId();
5394
5499
  eventStream$.sendTextMessageStart({
@@ -5411,6 +5516,8 @@ var ExperimentalOllamaAdapter = class {
5411
5516
  }
5412
5517
  };
5413
5518
  __name(ExperimentalOllamaAdapter, "ExperimentalOllamaAdapter");
5519
+
5520
+ // src/service-adapters/bedrock/bedrock-adapter.ts
5414
5521
  var DEFAULT_MODEL6 = "amazon.nova-lite-v1:0";
5415
5522
  var BedrockAdapter = class extends LangChainAdapter {
5416
5523
  provider = "bedrock";
@@ -5418,8 +5525,9 @@ var BedrockAdapter = class extends LangChainAdapter {
5418
5525
  constructor(options) {
5419
5526
  super({
5420
5527
  chainFn: async ({ messages, tools, threadId }) => {
5528
+ const { ChatBedrockConverse } = __require("@langchain/aws");
5421
5529
  this.model = (options == null ? void 0 : options.model) ?? "amazon.nova-lite-v1:0";
5422
- const model = new aws.ChatBedrockConverse({
5530
+ const model = new ChatBedrockConverse({
5423
5531
  model: this.model,
5424
5532
  region: (options == null ? void 0 : options.region) ?? "us-east-1",
5425
5533
  credentials: (options == null ? void 0 : options.credentials) ? {
@@ -5446,10 +5554,6 @@ var EmptyAdapter = class {
5446
5554
  __name(EmptyAdapter, "EmptyAdapter");
5447
5555
  var ExperimentalEmptyAdapter = EmptyAdapter;
5448
5556
 
5449
- Object.defineProperty(exports, 'LangGraphHttpAgent', {
5450
- enumerable: true,
5451
- get: function () { return langgraph.LangGraphHttpAgent; }
5452
- });
5453
5557
  exports.AnthropicAdapter = AnthropicAdapter;
5454
5558
  exports.BedrockAdapter = BedrockAdapter;
5455
5559
  exports.CopilotRuntime = CopilotRuntime;
@@ -5461,10 +5565,12 @@ exports.GroqAdapter = GroqAdapter;
5461
5565
  exports.GuardrailsValidationFailureResponse = GuardrailsValidationFailureResponse;
5462
5566
  exports.LangChainAdapter = LangChainAdapter;
5463
5567
  exports.LangGraphAgent = LangGraphAgent;
5568
+ exports.LangGraphHttpAgent = LangGraphHttpAgent;
5464
5569
  exports.MessageStreamInterruptedResponse = MessageStreamInterruptedResponse;
5465
5570
  exports.OpenAIAdapter = OpenAIAdapter;
5466
5571
  exports.OpenAIAssistantAdapter = OpenAIAssistantAdapter;
5467
5572
  exports.RemoteChain = RemoteChain;
5573
+ exports.TelemetryAgentRunner = TelemetryAgentRunner;
5468
5574
  exports.UnifyAdapter = UnifyAdapter;
5469
5575
  exports.UnknownErrorResponse = UnknownErrorResponse;
5470
5576
  exports.addCustomHeaderPlugin = addCustomHeaderPlugin;