@copilotkit/runtime 0.0.0-fix-debug-infosys-20251107151227 → 0.0.0-fix-restore-handle-method-node-http-20251222114321

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 (142) hide show
  1. package/CHANGELOG.md +259 -3
  2. package/dist/index.d.ts +1493 -28
  3. package/dist/index.js +2568 -5467
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +5429 -99
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/{lib/index.d.ts → langgraph.d.ts} +104 -32
  8. package/dist/langgraph.js +211 -0
  9. package/dist/langgraph.js.map +1 -0
  10. package/dist/{chunk-XPALJ76U.mjs → langgraph.mjs} +57 -26
  11. package/dist/langgraph.mjs.map +1 -0
  12. package/dist/v2/index.d.ts +2 -0
  13. package/dist/v2/index.js +22 -0
  14. package/dist/v2/index.js.map +1 -0
  15. package/dist/v2/index.mjs +5 -0
  16. package/dist/v2/index.mjs.map +1 -0
  17. package/package.json +64 -20
  18. package/src/graphql/message-conversion/agui-to-gql.test.ts +1263 -0
  19. package/src/graphql/message-conversion/agui-to-gql.ts +333 -0
  20. package/src/graphql/message-conversion/gql-to-agui.test.ts +1580 -0
  21. package/src/graphql/message-conversion/gql-to-agui.ts +278 -0
  22. package/src/graphql/message-conversion/index.ts +2 -0
  23. package/src/graphql/message-conversion/roundtrip-conversion.test.ts +526 -0
  24. package/src/graphql/resolvers/copilot.resolver.ts +3 -51
  25. package/src/graphql/resolvers/state.resolver.ts +3 -2
  26. package/src/graphql/types/converted/index.ts +32 -6
  27. package/src/graphql/types/enums.ts +2 -2
  28. package/src/graphql/types/message-status.type.ts +3 -1
  29. package/src/langgraph.ts +1 -0
  30. package/src/lib/index.ts +42 -1
  31. package/src/lib/integrations/nextjs/app-router.ts +12 -11
  32. package/src/lib/integrations/nextjs/pages-router.ts +4 -11
  33. package/src/lib/integrations/node-http/index.ts +10 -5
  34. package/src/lib/integrations/shared.ts +1 -1
  35. package/src/lib/observability.ts +87 -0
  36. package/src/lib/runtime/{langgraph/langgraph-agent.ts → agent-integrations/langgraph/agent.ts} +10 -30
  37. package/src/lib/runtime/agent-integrations/langgraph/consts.ts +34 -0
  38. package/src/lib/runtime/agent-integrations/langgraph/index.ts +2 -0
  39. package/src/lib/runtime/copilot-runtime.ts +387 -1360
  40. package/src/lib/runtime/telemetry-agent-runner.ts +139 -0
  41. package/src/lib/runtime/types.ts +49 -0
  42. package/src/lib/runtime/utils.ts +87 -0
  43. package/src/lib/telemetry-client.ts +6 -5
  44. package/src/service-adapters/anthropic/anthropic-adapter.ts +21 -4
  45. package/src/service-adapters/bedrock/bedrock-adapter.ts +10 -2
  46. package/src/service-adapters/empty/empty-adapter.ts +3 -0
  47. package/src/service-adapters/events.ts +0 -254
  48. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +7 -2
  49. package/src/service-adapters/google/google-genai-adapter.ts +33 -7
  50. package/src/service-adapters/groq/groq-adapter.ts +21 -4
  51. package/src/service-adapters/langchain/langchain-adapter.ts +8 -3
  52. package/src/service-adapters/langchain/langserve.ts +2 -1
  53. package/src/service-adapters/openai/openai-adapter.ts +22 -4
  54. package/src/service-adapters/openai/openai-assistant-adapter.ts +30 -11
  55. package/src/service-adapters/service-adapter.ts +3 -0
  56. package/src/service-adapters/unify/unify-adapter.ts +9 -2
  57. package/src/v2/index.ts +3 -0
  58. package/tsup.config.ts +6 -2
  59. package/dist/chunk-27JKTS6P.mjs +0 -1704
  60. package/dist/chunk-27JKTS6P.mjs.map +0 -1
  61. package/dist/chunk-2DHC2YFK.mjs +0 -6026
  62. package/dist/chunk-2DHC2YFK.mjs.map +0 -1
  63. package/dist/chunk-2OZAGFV3.mjs +0 -43
  64. package/dist/chunk-2OZAGFV3.mjs.map +0 -1
  65. package/dist/chunk-5HHH4SZ3.mjs +0 -25
  66. package/dist/chunk-5HHH4SZ3.mjs.map +0 -1
  67. package/dist/chunk-AMUJQ6IR.mjs +0 -50
  68. package/dist/chunk-AMUJQ6IR.mjs.map +0 -1
  69. package/dist/chunk-FHD4JECV.mjs +0 -33
  70. package/dist/chunk-FHD4JECV.mjs.map +0 -1
  71. package/dist/chunk-FVG3IQG7.mjs +0 -25
  72. package/dist/chunk-FVG3IQG7.mjs.map +0 -1
  73. package/dist/chunk-QU2FLIQB.mjs +0 -80
  74. package/dist/chunk-QU2FLIQB.mjs.map +0 -1
  75. package/dist/chunk-SHBDMA63.mjs +0 -141
  76. package/dist/chunk-SHBDMA63.mjs.map +0 -1
  77. package/dist/chunk-XPALJ76U.mjs.map +0 -1
  78. package/dist/chunk-XWBDEXDA.mjs +0 -153
  79. package/dist/chunk-XWBDEXDA.mjs.map +0 -1
  80. package/dist/graphql/types/base/index.d.ts +0 -6
  81. package/dist/graphql/types/base/index.js +0 -63
  82. package/dist/graphql/types/base/index.js.map +0 -1
  83. package/dist/graphql/types/base/index.mjs +0 -8
  84. package/dist/graphql/types/base/index.mjs.map +0 -1
  85. package/dist/graphql/types/converted/index.d.ts +0 -2
  86. package/dist/graphql/types/converted/index.js +0 -200
  87. package/dist/graphql/types/converted/index.js.map +0 -1
  88. package/dist/graphql/types/converted/index.mjs +0 -19
  89. package/dist/graphql/types/converted/index.mjs.map +0 -1
  90. package/dist/groq-adapter-c8aec5c5.d.ts +0 -321
  91. package/dist/index-96b330da.d.ts +0 -119
  92. package/dist/langserve-0c6100e3.d.ts +0 -257
  93. package/dist/lib/cloud/index.d.ts +0 -6
  94. package/dist/lib/cloud/index.js +0 -18
  95. package/dist/lib/cloud/index.js.map +0 -1
  96. package/dist/lib/cloud/index.mjs +0 -1
  97. package/dist/lib/cloud/index.mjs.map +0 -1
  98. package/dist/lib/index.js +0 -7849
  99. package/dist/lib/index.js.map +0 -1
  100. package/dist/lib/index.mjs +0 -76
  101. package/dist/lib/index.mjs.map +0 -1
  102. package/dist/lib/integrations/index.d.ts +0 -34
  103. package/dist/lib/integrations/index.js +0 -3055
  104. package/dist/lib/integrations/index.js.map +0 -1
  105. package/dist/lib/integrations/index.mjs +0 -37
  106. package/dist/lib/integrations/index.mjs.map +0 -1
  107. package/dist/lib/integrations/nest/index.d.ts +0 -15
  108. package/dist/lib/integrations/nest/index.js +0 -2962
  109. package/dist/lib/integrations/nest/index.js.map +0 -1
  110. package/dist/lib/integrations/nest/index.mjs +0 -14
  111. package/dist/lib/integrations/nest/index.mjs.map +0 -1
  112. package/dist/lib/integrations/node-express/index.d.ts +0 -15
  113. package/dist/lib/integrations/node-express/index.js +0 -2962
  114. package/dist/lib/integrations/node-express/index.js.map +0 -1
  115. package/dist/lib/integrations/node-express/index.mjs +0 -14
  116. package/dist/lib/integrations/node-express/index.mjs.map +0 -1
  117. package/dist/lib/integrations/node-http/index.d.ts +0 -15
  118. package/dist/lib/integrations/node-http/index.js +0 -2948
  119. package/dist/lib/integrations/node-http/index.js.map +0 -1
  120. package/dist/lib/integrations/node-http/index.mjs +0 -13
  121. package/dist/lib/integrations/node-http/index.mjs.map +0 -1
  122. package/dist/service-adapters/index.d.ts +0 -162
  123. package/dist/service-adapters/index.js +0 -1787
  124. package/dist/service-adapters/index.js.map +0 -1
  125. package/dist/service-adapters/index.mjs +0 -34
  126. package/dist/service-adapters/index.mjs.map +0 -1
  127. package/dist/service-adapters/shared/index.d.ts +0 -9
  128. package/dist/service-adapters/shared/index.js +0 -72
  129. package/dist/service-adapters/shared/index.js.map +0 -1
  130. package/dist/service-adapters/shared/index.mjs +0 -8
  131. package/dist/service-adapters/shared/index.mjs.map +0 -1
  132. package/dist/shared-0a7346ce.d.ts +0 -466
  133. package/dist/utils/index.d.ts +0 -65
  134. package/dist/utils/index.js +0 -175
  135. package/dist/utils/index.js.map +0 -1
  136. package/dist/utils/index.mjs +0 -12
  137. package/dist/utils/index.mjs.map +0 -1
  138. package/src/lib/runtime/__tests__/remote-action-constructors.test.ts +0 -246
  139. package/src/lib/runtime/agui-action.ts +0 -180
  140. package/src/lib/runtime/remote-action-constructors.ts +0 -331
  141. package/src/lib/runtime/remote-actions.ts +0 -217
  142. package/src/lib/runtime/remote-lg-action.ts +0 -1006
@@ -0,0 +1,139 @@
1
+ /**
2
+ * TelemetryAgentRunner - A wrapper around AgentRunner that adds telemetry
3
+ * for agent execution streams.
4
+ *
5
+ * This captures the following telemetry events:
6
+ * - oss.runtime.agent_execution_stream_started - when an agent execution starts
7
+ * - oss.runtime.agent_execution_stream_ended - when an agent execution completes
8
+ * - oss.runtime.agent_execution_stream_errored - when an agent execution fails
9
+ */
10
+
11
+ import { type AgentRunner, InMemoryAgentRunner } from "@copilotkitnext/runtime";
12
+ import { createHash } from "node:crypto";
13
+ import { tap, catchError, finalize } from "rxjs";
14
+ import telemetry from "../telemetry-client";
15
+ import type { AgentExecutionResponseInfo } from "@copilotkit/shared/src/telemetry/events";
16
+
17
+ /**
18
+ * Configuration options for TelemetryAgentRunner
19
+ */
20
+ export interface TelemetryAgentRunnerConfig {
21
+ /**
22
+ * The underlying runner to delegate to
23
+ * If not provided, defaults to InMemoryAgentRunner
24
+ */
25
+ runner?: AgentRunner;
26
+
27
+ /**
28
+ * Optional LangSmith API key (will be hashed for telemetry)
29
+ */
30
+ langsmithApiKey?: string;
31
+ }
32
+
33
+ /**
34
+ * An AgentRunner wrapper that adds telemetry tracking for agent executions.
35
+ *
36
+ * Usage:
37
+ * ```ts
38
+ * const runtime = new CopilotRuntime({
39
+ * runner: new TelemetryAgentRunner(),
40
+ * // or with custom runner:
41
+ * runner: new TelemetryAgentRunner({ runner: customRunner }),
42
+ * });
43
+ * ```
44
+ */
45
+ export class TelemetryAgentRunner implements AgentRunner {
46
+ private readonly _runner: AgentRunner;
47
+ private readonly hashedLgcKey: string | undefined;
48
+
49
+ constructor(config?: TelemetryAgentRunnerConfig) {
50
+ this._runner = config?.runner ?? new InMemoryAgentRunner();
51
+ this.hashedLgcKey = config?.langsmithApiKey
52
+ ? createHash("sha256").update(config.langsmithApiKey).digest("hex")
53
+ : undefined;
54
+ }
55
+
56
+ /**
57
+ * Runs an agent with telemetry tracking.
58
+ * Wraps the underlying runner's Observable stream with telemetry events.
59
+ */
60
+ run(...args: Parameters<AgentRunner["run"]>): ReturnType<AgentRunner["run"]> {
61
+ const streamInfo: AgentExecutionResponseInfo = {
62
+ hashedLgcKey: this.hashedLgcKey,
63
+ };
64
+ let streamErrored = false;
65
+
66
+ // Capture stream started event
67
+ telemetry.capture("oss.runtime.agent_execution_stream_started", {
68
+ hashedLgcKey: this.hashedLgcKey,
69
+ });
70
+
71
+ // Delegate to the underlying runner and wrap with telemetry
72
+ return this._runner.run(...args).pipe(
73
+ // Extract metadata from events if available
74
+ tap((event) => {
75
+ // Try to extract provider/model info from raw events
76
+ const rawEvent = (
77
+ event as {
78
+ rawEvent?: { metadata?: Record<string, unknown>; data?: Record<string, unknown> };
79
+ }
80
+ ).rawEvent;
81
+ if (rawEvent?.data) {
82
+ const data = rawEvent.data as { output?: { model?: string } };
83
+ if (data?.output?.model) {
84
+ streamInfo.model = data.output.model;
85
+ streamInfo.provider = data.output.model;
86
+ }
87
+ }
88
+ if (rawEvent?.metadata) {
89
+ const metadata = rawEvent.metadata as {
90
+ langgraph_host?: string;
91
+ langgraph_version?: string;
92
+ };
93
+ if (metadata?.langgraph_host) {
94
+ streamInfo.langGraphHost = metadata.langgraph_host;
95
+ }
96
+ if (metadata?.langgraph_version) {
97
+ streamInfo.langGraphVersion = metadata.langgraph_version;
98
+ }
99
+ }
100
+ }),
101
+ catchError((error) => {
102
+ // Capture stream error event
103
+ streamErrored = true;
104
+ telemetry.capture("oss.runtime.agent_execution_stream_errored", {
105
+ ...streamInfo,
106
+ error: error instanceof Error ? error.message : String(error),
107
+ });
108
+ throw error;
109
+ }),
110
+ finalize(() => {
111
+ // Capture stream ended event (only if not errored)
112
+ if (!streamErrored) {
113
+ telemetry.capture("oss.runtime.agent_execution_stream_ended", streamInfo);
114
+ }
115
+ }),
116
+ );
117
+ }
118
+
119
+ /**
120
+ * Delegates to the underlying runner's connect method
121
+ */
122
+ connect(...args: Parameters<AgentRunner["connect"]>): ReturnType<AgentRunner["connect"]> {
123
+ return this._runner.connect(...args);
124
+ }
125
+
126
+ /**
127
+ * Delegates to the underlying runner's isRunning method
128
+ */
129
+ isRunning(...args: Parameters<AgentRunner["isRunning"]>): ReturnType<AgentRunner["isRunning"]> {
130
+ return this._runner.isRunning(...args);
131
+ }
132
+
133
+ /**
134
+ * Delegates to the underlying runner's stop method
135
+ */
136
+ stop(...args: Parameters<AgentRunner["stop"]>): ReturnType<AgentRunner["stop"]> {
137
+ return this._runner.stop(...args);
138
+ }
139
+ }
@@ -0,0 +1,49 @@
1
+ import { GraphQLContext } from "../integrations";
2
+ import { ActionInput } from "../../graphql/inputs/action.input";
3
+ import { Message } from "../../graphql/types/converted";
4
+ import { MetaEventInput } from "../../graphql/inputs/meta-event.input";
5
+
6
+ export interface BaseEndpointDefinition<TActionType extends EndpointType> {
7
+ type?: TActionType;
8
+ }
9
+
10
+ export interface CopilotKitEndpoint extends BaseEndpointDefinition<EndpointType.CopilotKit> {
11
+ url: string;
12
+ onBeforeRequest?: ({ ctx }: { ctx: GraphQLContext }) => {
13
+ headers?: Record<string, string> | undefined;
14
+ };
15
+ }
16
+
17
+ export interface LangGraphPlatformAgent {
18
+ name: string;
19
+ description: string;
20
+ assistantId?: string;
21
+ }
22
+
23
+ export interface LangGraphPlatformEndpoint
24
+ extends BaseEndpointDefinition<EndpointType.LangGraphPlatform> {
25
+ deploymentUrl: string;
26
+ langsmithApiKey?: string | null;
27
+ agents: LangGraphPlatformAgent[];
28
+ }
29
+
30
+ export type RemoteActionInfoResponse = {
31
+ actions: any[];
32
+ agents: any[];
33
+ };
34
+
35
+ export type RemoteAgentHandlerParams = {
36
+ name: string;
37
+ actionInputsWithoutAgents: ActionInput[];
38
+ threadId?: string;
39
+ nodeName?: string;
40
+ additionalMessages?: Message[];
41
+ metaEvents?: MetaEventInput[];
42
+ };
43
+
44
+ export type EndpointDefinition = CopilotKitEndpoint | LangGraphPlatformEndpoint;
45
+
46
+ export enum EndpointType {
47
+ CopilotKit = "copilotKit",
48
+ LangGraphPlatform = "langgraph-platform",
49
+ }
@@ -0,0 +1,87 @@
1
+ import { GraphQLContext } from "../integrations";
2
+ import { Logger } from "pino";
3
+ import { CopilotKitEndpoint, RemoteActionInfoResponse } from "./types";
4
+ import {
5
+ Action,
6
+ CopilotKitError,
7
+ CopilotKitLowLevelError,
8
+ ResolvedCopilotKitError,
9
+ } from "@copilotkit/shared";
10
+
11
+ async function fetchRemoteInfo({
12
+ url,
13
+ onBeforeRequest,
14
+ graphqlContext,
15
+ logger,
16
+ frontendUrl,
17
+ }: {
18
+ url: string;
19
+ onBeforeRequest?: CopilotKitEndpoint["onBeforeRequest"];
20
+ graphqlContext: GraphQLContext;
21
+ logger: Logger;
22
+ frontendUrl?: string;
23
+ }): Promise<RemoteActionInfoResponse> {
24
+ logger.debug({ url }, "Fetching actions from url");
25
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
26
+
27
+ const fetchUrl = `${url}/info`;
28
+ try {
29
+ const response = await fetch(fetchUrl, {
30
+ method: "POST",
31
+ headers,
32
+ body: JSON.stringify({ properties: graphqlContext.properties, frontendUrl }),
33
+ });
34
+
35
+ if (!response.ok) {
36
+ logger.error(
37
+ { url, status: response.status, body: await response.text() },
38
+ "Failed to fetch actions from url",
39
+ );
40
+ throw new ResolvedCopilotKitError({
41
+ status: response.status,
42
+ url: fetchUrl,
43
+ isRemoteEndpoint: true,
44
+ });
45
+ }
46
+
47
+ const json = await response.json();
48
+ logger.debug({ json }, "Fetched actions from url");
49
+ return json;
50
+ } catch (error) {
51
+ if (error instanceof CopilotKitError) {
52
+ throw error;
53
+ }
54
+ throw new CopilotKitLowLevelError({ error, url: fetchUrl });
55
+ }
56
+ }
57
+
58
+ // Utility to determine if an error is a user configuration issue vs system error
59
+ export function isUserConfigurationError(error: any): boolean {
60
+ return (
61
+ (error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError) &&
62
+ (error.code === "NETWORK_ERROR" ||
63
+ error.code === "AUTHENTICATION_ERROR" ||
64
+ error.statusCode === 401 ||
65
+ error.statusCode === 403 ||
66
+ error.message?.toLowerCase().includes("authentication") ||
67
+ error.message?.toLowerCase().includes("api key"))
68
+ );
69
+ }
70
+
71
+ export function createHeaders(
72
+ onBeforeRequest: CopilotKitEndpoint["onBeforeRequest"],
73
+ graphqlContext: GraphQLContext,
74
+ ) {
75
+ const headers = {
76
+ "Content-Type": "application/json",
77
+ };
78
+
79
+ if (onBeforeRequest) {
80
+ const { headers: additionalHeaders } = onBeforeRequest({ ctx: graphqlContext });
81
+ if (additionalHeaders) {
82
+ Object.assign(headers, additionalHeaders);
83
+ }
84
+ }
85
+
86
+ return headers;
87
+ }
@@ -1,9 +1,9 @@
1
1
  import { TelemetryClient } from "@copilotkit/shared";
2
- import { EndpointType, LangGraphPlatformEndpoint } from "./runtime/remote-actions";
3
2
  import { createHash } from "node:crypto";
4
3
  import { CopilotRuntime, resolveEndpointType } from "./runtime/copilot-runtime";
5
4
  import { RuntimeInstanceCreatedInfo } from "@copilotkit/shared/src/telemetry/events";
6
5
  import { CreateCopilotRuntimeServerOptions } from "./integrations/shared";
6
+ import { EndpointType, LangGraphPlatformEndpoint } from "./runtime/types";
7
7
  const packageJson = require("../../package.json");
8
8
 
9
9
  const telemetryClient = new TelemetryClient({
@@ -15,7 +15,8 @@ export function getRuntimeInstanceTelemetryInfo(
15
15
  options: CreateCopilotRuntimeServerOptions,
16
16
  ): RuntimeInstanceCreatedInfo {
17
17
  const runtime = options.runtime;
18
- const endpointsInfo = runtime.remoteEndpointDefinitions.reduce(
18
+ const remoteEndpoints = runtime.params?.remoteEndpoints ?? [];
19
+ const endpointsInfo = remoteEndpoints.reduce(
19
20
  (acc, endpoint) => {
20
21
  let info = { ...acc };
21
22
 
@@ -49,10 +50,10 @@ export function getRuntimeInstanceTelemetryInfo(
49
50
  const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;
50
51
 
51
52
  return {
52
- actionsAmount: runtime.actions.length,
53
- endpointsAmount: runtime.remoteEndpointDefinitions.length,
53
+ actionsAmount: runtime.params?.actions?.length ?? 0,
54
+ endpointsAmount: remoteEndpoints.length,
54
55
  endpointTypes: endpointsInfo.endpointTypes,
55
- agentsAmount: endpointsInfo.agentsAmount,
56
+ agentsAmount: Object.keys(runtime.instance.agents).length,
56
57
  hashedLgcKey: endpointsInfo.hashedKey,
57
58
  "cloud.api_key_provided": apiKeyProvided,
58
59
  ...(apiKeyProvided ? { "cloud.public_api_key": publicApiKey } : {}),
@@ -22,7 +22,7 @@
22
22
  * });
23
23
  * ```
24
24
  */
25
- import Anthropic from "@anthropic-ai/sdk";
25
+ import type Anthropic from "@anthropic-ai/sdk";
26
26
  import {
27
27
  CopilotServiceAdapter,
28
28
  CopilotRuntimeChatCompletionRequest,
@@ -71,22 +71,38 @@ export interface AnthropicAdapterParams {
71
71
  }
72
72
 
73
73
  export class AnthropicAdapter implements CopilotServiceAdapter {
74
- private model: string = DEFAULT_MODEL;
74
+ public model: string = DEFAULT_MODEL;
75
+ public provider = "anthropic";
75
76
  private promptCaching: AnthropicPromptCachingConfig;
76
77
 
77
78
  private _anthropic: Anthropic;
78
79
  public get anthropic(): Anthropic {
79
80
  return this._anthropic;
80
81
  }
82
+ public get name() {
83
+ return "AnthropicAdapter";
84
+ }
81
85
 
82
86
  constructor(params?: AnthropicAdapterParams) {
83
- this._anthropic = params?.anthropic || new Anthropic({});
87
+ if (params?.anthropic) {
88
+ this._anthropic = params.anthropic;
89
+ }
90
+ // If no instance provided, we'll lazy-load in ensureAnthropic()
84
91
  if (params?.model) {
85
92
  this.model = params.model;
86
93
  }
87
94
  this.promptCaching = params?.promptCaching || { enabled: false };
88
95
  }
89
96
 
97
+ private ensureAnthropic(): Anthropic {
98
+ if (!this._anthropic) {
99
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
100
+ const Anthropic = require("@anthropic-ai/sdk").default;
101
+ this._anthropic = new Anthropic({});
102
+ }
103
+ return this._anthropic;
104
+ }
105
+
90
106
  /**
91
107
  * Adds cache control to system prompt
92
108
  */
@@ -302,7 +318,8 @@ export class AnthropicAdapter implements CopilotServiceAdapter {
302
318
  stream: true,
303
319
  };
304
320
 
305
- const stream = await this.anthropic.messages.create(createParams);
321
+ const anthropic = this.ensureAnthropic();
322
+ const stream = await anthropic.messages.create(createParams);
306
323
 
307
324
  eventSource.stream(async (eventStream$) => {
308
325
  let mode: "function" | "message" | null = null;
@@ -19,7 +19,6 @@
19
19
  * ```
20
20
  */
21
21
 
22
- import { ChatBedrockConverse } from "@langchain/aws";
23
22
  import { LangChainAdapter } from "../langchain/langchain-adapter";
24
23
 
25
24
  export interface BedrockAdapterParams {
@@ -44,12 +43,21 @@ export interface BedrockAdapterParams {
44
43
  };
45
44
  }
46
45
 
46
+ const DEFAULT_MODEL = "amazon.nova-lite-v1:0";
47
+
47
48
  export class BedrockAdapter extends LangChainAdapter {
49
+ public provider = "bedrock";
50
+ public model: string = DEFAULT_MODEL;
48
51
  constructor(options?: BedrockAdapterParams) {
49
52
  super({
50
53
  chainFn: async ({ messages, tools, threadId }) => {
54
+ // Lazy require for optional peer dependency
55
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
56
+ const { ChatBedrockConverse } = require("@langchain/aws");
57
+
58
+ this.model = options?.model ?? "amazon.nova-lite-v1:0";
51
59
  const model = new ChatBedrockConverse({
52
- model: options?.model ?? "amazon.nova-lite-v1:0",
60
+ model: this.model,
53
61
  region: options?.region ?? "us-east-1",
54
62
  credentials: options?.credentials
55
63
  ? {
@@ -30,6 +30,9 @@ export class EmptyAdapter implements CopilotServiceAdapter {
30
30
  threadId: request.threadId || randomUUID(),
31
31
  };
32
32
  }
33
+ public get name() {
34
+ return "EmptyAdapter";
35
+ }
33
36
  }
34
37
 
35
38
  export const ExperimentalEmptyAdapter = EmptyAdapter;
@@ -23,7 +23,6 @@ import {
23
23
  import { ActionInput } from "../graphql/inputs/action.input";
24
24
  import { ActionExecutionMessage, ResultMessage, TextMessage } from "../graphql/types/converted";
25
25
  import { GuardrailsResult } from "../graphql/types/guardrails-result.type";
26
- import { isRemoteAgentAction } from "../lib/runtime/remote-actions";
27
26
  import { generateHelpfulErrorMessage } from "../lib/streaming";
28
27
  import telemetry from "../lib/telemetry-client";
29
28
  import { streamLangChainResponse } from "./langchain/utils";
@@ -262,259 +261,6 @@ export class RuntimeEventSource {
262
261
  async stream(callback: EventSourceCallback): Promise<void> {
263
262
  this.callback = callback;
264
263
  }
265
-
266
- sendErrorMessageToChat(message = "An error occurred. Please try again.") {
267
- const errorMessage = `❌ ${message}`;
268
- if (!this.callback) {
269
- this.stream(async (eventStream$) => {
270
- eventStream$.sendTextMessage(randomId(), errorMessage);
271
- });
272
- } else {
273
- this.eventStream$.sendTextMessage(randomId(), errorMessage);
274
- }
275
- }
276
-
277
- processRuntimeEvents({
278
- serverSideActions,
279
- guardrailsResult$,
280
- actionInputsWithoutAgents,
281
- threadId,
282
- }: {
283
- serverSideActions: Action<any>[];
284
- guardrailsResult$?: Subject<GuardrailsResult>;
285
- actionInputsWithoutAgents: ActionInput[];
286
- threadId: string;
287
- }) {
288
- this.callback(this.eventStream$).catch(async (error) => {
289
- // Convert streaming errors to structured errors, but preserve already structured ones
290
- const structuredError = ensureStructuredError(error, convertStreamingErrorToStructured);
291
-
292
- // Call the runtime error handler if provided
293
- if (this.errorHandler && this.errorContext) {
294
- try {
295
- await this.errorHandler(structuredError, this.errorContext);
296
- } catch (errorHandlerError) {
297
- console.error("Error in streaming error handler:", errorHandlerError);
298
- }
299
- }
300
-
301
- this.eventStream$.error(structuredError);
302
- this.eventStream$.complete();
303
- });
304
- return this.eventStream$.pipe(
305
- // track state
306
- scan(
307
- (acc, event) => {
308
- // It seems like this is needed so that rxjs recognizes the object has changed
309
- // This fixes an issue where action were executed multiple times
310
- // Not investigating further for now (Markus)
311
- acc = { ...acc };
312
-
313
- if (event.type === RuntimeEventTypes.ActionExecutionStart) {
314
- acc.callActionServerSide =
315
- serverSideActions.find((action) => action.name === event.actionName) !== undefined;
316
- acc.args = "";
317
- acc.actionExecutionId = event.actionExecutionId;
318
- if (acc.callActionServerSide) {
319
- acc.action = serverSideActions.find((action) => action.name === event.actionName);
320
- }
321
- acc.actionExecutionParentMessageId = event.parentMessageId;
322
- } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {
323
- acc.args += event.args;
324
- }
325
-
326
- acc.event = event;
327
-
328
- return acc;
329
- },
330
- {
331
- event: null,
332
- callActionServerSide: false,
333
- args: "",
334
- actionExecutionId: null,
335
- action: null,
336
- actionExecutionParentMessageId: null,
337
- } as RuntimeEventWithState,
338
- ),
339
- concatMap((eventWithState) => {
340
- if (
341
- eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&
342
- eventWithState.callActionServerSide
343
- ) {
344
- const toolCallEventStream$ = new RuntimeEventSubject();
345
- executeAction(
346
- toolCallEventStream$,
347
- guardrailsResult$ ? guardrailsResult$ : null,
348
- eventWithState.action!,
349
- eventWithState.args,
350
- eventWithState.actionExecutionParentMessageId,
351
- eventWithState.actionExecutionId,
352
- actionInputsWithoutAgents,
353
- threadId,
354
- ).catch((error) => {});
355
-
356
- telemetry.capture("oss.runtime.server_action_executed", {});
357
- return concat(of(eventWithState.event!), toolCallEventStream$).pipe(
358
- catchError((error) => {
359
- // Convert streaming errors to structured errors and send as action result, but preserve already structured ones
360
- const structuredError = ensureStructuredError(
361
- error,
362
- convertStreamingErrorToStructured,
363
- );
364
-
365
- // Call the runtime error handler if provided
366
- if (this.errorHandler && this.errorContext) {
367
- // Use from() to handle async error handler
368
- from(
369
- this.errorHandler(structuredError, {
370
- ...this.errorContext,
371
- action: {
372
- name: eventWithState.action!.name,
373
- executionId: eventWithState.actionExecutionId,
374
- },
375
- }),
376
- ).subscribe({
377
- error: (errorHandlerError) => {
378
- console.error("Error in action execution error handler:", errorHandlerError);
379
- },
380
- });
381
- }
382
-
383
- toolCallEventStream$.sendActionExecutionResult({
384
- actionExecutionId: eventWithState.actionExecutionId!,
385
- actionName: eventWithState.action!.name,
386
- error: {
387
- code: structuredError.code,
388
- message: structuredError.message,
389
- },
390
- });
391
-
392
- return EMPTY;
393
- }),
394
- );
395
- } else {
396
- return of(eventWithState.event!);
397
- }
398
- }),
399
- );
400
- }
401
- }
402
-
403
- async function executeAction(
404
- eventStream$: RuntimeEventSubject,
405
- guardrailsResult$: Subject<GuardrailsResult> | null,
406
- action: Action<any>,
407
- actionArguments: string,
408
- actionExecutionParentMessageId: string | null,
409
- actionExecutionId: string,
410
- actionInputsWithoutAgents: ActionInput[],
411
- threadId: string,
412
- ) {
413
- if (guardrailsResult$) {
414
- const { status } = await firstValueFrom(guardrailsResult$);
415
-
416
- if (status === "denied") {
417
- eventStream$.complete();
418
- return;
419
- }
420
- }
421
-
422
- // Prepare arguments for function calling
423
- let args: Record<string, any>[] = [];
424
- if (actionArguments) {
425
- try {
426
- args = JSON.parse(actionArguments);
427
- } catch (e) {
428
- console.error("Action argument unparsable", { actionArguments });
429
- eventStream$.sendActionExecutionResult({
430
- actionExecutionId,
431
- actionName: action.name,
432
- error: {
433
- code: "INVALID_ARGUMENTS",
434
- message: "Failed to parse action arguments",
435
- },
436
- });
437
- return;
438
- }
439
- }
440
-
441
- // handle LangGraph agents
442
- if (isRemoteAgentAction(action)) {
443
- const result = `${action.name} agent started`;
444
-
445
- const agentExecution = plainToInstance(ActionExecutionMessage, {
446
- id: actionExecutionId,
447
- createdAt: new Date(),
448
- name: action.name,
449
- arguments: JSON.parse(actionArguments),
450
- parentMessageId: actionExecutionParentMessageId ?? actionExecutionId,
451
- });
452
-
453
- const agentExecutionResult = plainToInstance(ResultMessage, {
454
- id: "result-" + actionExecutionId,
455
- createdAt: new Date(),
456
- actionExecutionId,
457
- actionName: action.name,
458
- result,
459
- });
460
-
461
- eventStream$.sendActionExecutionResult({
462
- actionExecutionId,
463
- actionName: action.name,
464
- result,
465
- });
466
-
467
- const stream = await action.remoteAgentHandler({
468
- name: action.name,
469
- threadId,
470
- actionInputsWithoutAgents,
471
- additionalMessages: [agentExecution, agentExecutionResult],
472
- });
473
-
474
- // forward to eventStream$
475
- from(stream).subscribe({
476
- next: (event) => eventStream$.next(event),
477
- error: (err) => {
478
- // Preserve already structured CopilotKit errors, only convert unstructured errors
479
- const structuredError = ensureStructuredError(err, convertStreamingErrorToStructured);
480
- eventStream$.sendActionExecutionResult({
481
- actionExecutionId,
482
- actionName: action.name,
483
- error: {
484
- code: structuredError.code,
485
- message: structuredError.message,
486
- },
487
- });
488
- eventStream$.complete();
489
- },
490
- complete: () => eventStream$.complete(),
491
- });
492
- } else {
493
- // call the function
494
- try {
495
- const result = await action.handler?.(args);
496
- await streamLangChainResponse({
497
- result,
498
- eventStream$,
499
- actionExecution: {
500
- name: action.name,
501
- id: actionExecutionId,
502
- returnDirect: action.additionalConfig?.returnDirect,
503
- },
504
- });
505
- } catch (e) {
506
- console.error("Error in action handler", e);
507
- eventStream$.sendActionExecutionResult({
508
- actionExecutionId,
509
- actionName: action.name,
510
- error: {
511
- code: "HANDLER_ERROR",
512
- message: e.message,
513
- },
514
- });
515
- eventStream$.complete();
516
- }
517
- }
518
264
  }
519
265
 
520
266
  function convertStreamingErrorToStructured(error: any): CopilotKitError {