@copilotkit/runtime 0.0.0-0.0.0-max-changeset-10101010101010-20260109191632

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 (122) hide show
  1. package/.eslintrc.js +7 -0
  2. package/CHANGELOG.md +2905 -0
  3. package/LICENSE +21 -0
  4. package/README.md +76 -0
  5. package/__snapshots__/schema/schema.graphql +371 -0
  6. package/dist/index.d.ts +1495 -0
  7. package/dist/index.js +5644 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/index.mjs +5601 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/langgraph.d.ts +284 -0
  12. package/dist/langgraph.js +211 -0
  13. package/dist/langgraph.js.map +1 -0
  14. package/dist/langgraph.mjs +206 -0
  15. package/dist/langgraph.mjs.map +1 -0
  16. package/dist/v2/index.d.ts +2 -0
  17. package/dist/v2/index.js +22 -0
  18. package/dist/v2/index.js.map +1 -0
  19. package/dist/v2/index.mjs +5 -0
  20. package/dist/v2/index.mjs.map +1 -0
  21. package/jest.config.js +10 -0
  22. package/package.json +143 -0
  23. package/scripts/generate-gql-schema.ts +13 -0
  24. package/src/agents/langgraph/event-source.ts +329 -0
  25. package/src/agents/langgraph/events.ts +377 -0
  26. package/src/graphql/inputs/action.input.ts +16 -0
  27. package/src/graphql/inputs/agent-session.input.ts +13 -0
  28. package/src/graphql/inputs/agent-state.input.ts +13 -0
  29. package/src/graphql/inputs/cloud-guardrails.input.ts +16 -0
  30. package/src/graphql/inputs/cloud.input.ts +8 -0
  31. package/src/graphql/inputs/context-property.input.ts +10 -0
  32. package/src/graphql/inputs/copilot-context.input.ts +10 -0
  33. package/src/graphql/inputs/custom-property.input.ts +15 -0
  34. package/src/graphql/inputs/extensions.input.ts +21 -0
  35. package/src/graphql/inputs/forwarded-parameters.input.ts +22 -0
  36. package/src/graphql/inputs/frontend.input.ts +14 -0
  37. package/src/graphql/inputs/generate-copilot-response.input.ts +59 -0
  38. package/src/graphql/inputs/load-agent-state.input.ts +10 -0
  39. package/src/graphql/inputs/message.input.ts +110 -0
  40. package/src/graphql/inputs/meta-event.input.ts +18 -0
  41. package/src/graphql/message-conversion/agui-to-gql.test.ts +1263 -0
  42. package/src/graphql/message-conversion/agui-to-gql.ts +333 -0
  43. package/src/graphql/message-conversion/gql-to-agui.test.ts +1580 -0
  44. package/src/graphql/message-conversion/gql-to-agui.ts +278 -0
  45. package/src/graphql/message-conversion/index.ts +2 -0
  46. package/src/graphql/message-conversion/roundtrip-conversion.test.ts +526 -0
  47. package/src/graphql/resolvers/copilot.resolver.ts +708 -0
  48. package/src/graphql/resolvers/state.resolver.ts +27 -0
  49. package/src/graphql/types/agents-response.type.ts +19 -0
  50. package/src/graphql/types/base/index.ts +10 -0
  51. package/src/graphql/types/converted/index.ts +176 -0
  52. package/src/graphql/types/copilot-response.type.ts +138 -0
  53. package/src/graphql/types/enums.ts +38 -0
  54. package/src/graphql/types/extensions-response.type.ts +23 -0
  55. package/src/graphql/types/guardrails-result.type.ts +20 -0
  56. package/src/graphql/types/load-agent-state-response.type.ts +17 -0
  57. package/src/graphql/types/message-status.type.ts +42 -0
  58. package/src/graphql/types/meta-events.type.ts +71 -0
  59. package/src/graphql/types/response-status.type.ts +66 -0
  60. package/src/index.ts +4 -0
  61. package/src/langgraph.ts +1 -0
  62. package/src/lib/cloud/index.ts +4 -0
  63. package/src/lib/error-messages.ts +200 -0
  64. package/src/lib/index.ts +52 -0
  65. package/src/lib/integrations/index.ts +6 -0
  66. package/src/lib/integrations/nest/index.ts +14 -0
  67. package/src/lib/integrations/nextjs/app-router.ts +38 -0
  68. package/src/lib/integrations/nextjs/pages-router.ts +39 -0
  69. package/src/lib/integrations/node-express/index.ts +14 -0
  70. package/src/lib/integrations/node-http/index.ts +143 -0
  71. package/src/lib/integrations/node-http/request-handler.ts +111 -0
  72. package/src/lib/integrations/shared.ts +161 -0
  73. package/src/lib/logger.ts +28 -0
  74. package/src/lib/observability.ts +160 -0
  75. package/src/lib/runtime/__tests__/copilot-runtime-error.test.ts +169 -0
  76. package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +464 -0
  77. package/src/lib/runtime/agent-integrations/langgraph/agent.ts +209 -0
  78. package/src/lib/runtime/agent-integrations/langgraph/consts.ts +34 -0
  79. package/src/lib/runtime/agent-integrations/langgraph/index.ts +2 -0
  80. package/src/lib/runtime/copilot-runtime.ts +710 -0
  81. package/src/lib/runtime/mcp-tools-utils.ts +254 -0
  82. package/src/lib/runtime/retry-utils.ts +96 -0
  83. package/src/lib/runtime/telemetry-agent-runner.ts +139 -0
  84. package/src/lib/runtime/types.ts +49 -0
  85. package/src/lib/runtime/utils.ts +87 -0
  86. package/src/lib/streaming.ts +202 -0
  87. package/src/lib/telemetry-client.ts +64 -0
  88. package/src/service-adapters/anthropic/anthropic-adapter.ts +452 -0
  89. package/src/service-adapters/anthropic/utils.ts +152 -0
  90. package/src/service-adapters/bedrock/bedrock-adapter.ts +73 -0
  91. package/src/service-adapters/conversion.ts +67 -0
  92. package/src/service-adapters/empty/empty-adapter.ts +38 -0
  93. package/src/service-adapters/events.ts +294 -0
  94. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +84 -0
  95. package/src/service-adapters/google/google-genai-adapter.test.ts +104 -0
  96. package/src/service-adapters/google/google-genai-adapter.ts +88 -0
  97. package/src/service-adapters/groq/groq-adapter.ts +203 -0
  98. package/src/service-adapters/index.ts +18 -0
  99. package/src/service-adapters/langchain/langchain-adapter.ts +111 -0
  100. package/src/service-adapters/langchain/langserve.ts +88 -0
  101. package/src/service-adapters/langchain/types.ts +14 -0
  102. package/src/service-adapters/langchain/utils.ts +313 -0
  103. package/src/service-adapters/openai/openai-adapter.ts +283 -0
  104. package/src/service-adapters/openai/openai-assistant-adapter.ts +344 -0
  105. package/src/service-adapters/openai/utils.ts +199 -0
  106. package/src/service-adapters/service-adapter.ts +41 -0
  107. package/src/service-adapters/shared/error-utils.ts +61 -0
  108. package/src/service-adapters/shared/index.ts +1 -0
  109. package/src/service-adapters/unify/unify-adapter.ts +151 -0
  110. package/src/utils/failed-response-status-reasons.ts +70 -0
  111. package/src/utils/index.ts +1 -0
  112. package/src/v2/index.ts +3 -0
  113. package/tests/global.d.ts +13 -0
  114. package/tests/service-adapters/anthropic/allowlist-approach.test.ts +226 -0
  115. package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +389 -0
  116. package/tests/service-adapters/openai/allowlist-approach.test.ts +238 -0
  117. package/tests/service-adapters/openai/openai-adapter.test.ts +301 -0
  118. package/tests/setup.jest.ts +21 -0
  119. package/tests/tsconfig.json +10 -0
  120. package/tsconfig.json +13 -0
  121. package/tsup.config.ts +20 -0
  122. package/typedoc.json +4 -0
@@ -0,0 +1,254 @@
1
+ import { Action, Parameter } from "@copilotkit/shared";
2
+
3
+ /**
4
+ * Represents a tool provided by an MCP server.
5
+ */
6
+ export interface MCPTool {
7
+ description?: string;
8
+ /** Schema defining parameters, mirroring the MCP structure. */
9
+ schema?: {
10
+ parameters?: {
11
+ properties?: Record<string, any>;
12
+ required?: string[];
13
+ jsonSchema?: Record<string, any>;
14
+ };
15
+ };
16
+ /** The function to call to execute the tool on the MCP server. */
17
+ execute(params: any): Promise<any>;
18
+ }
19
+
20
+ /**
21
+ * Defines the contract for *any* MCP client implementation the user might provide.
22
+ */
23
+ export interface MCPClient {
24
+ /** A method that returns a map of tool names to MCPTool objects available from the connected MCP server. */
25
+ tools(): Promise<Record<string, MCPTool>>;
26
+ /** An optional method for cleanup if the underlying client requires explicit disconnection. */
27
+ close?(): Promise<void>;
28
+ }
29
+
30
+ /**
31
+ * Configuration for connecting to an MCP endpoint.
32
+ */
33
+ export interface MCPEndpointConfig {
34
+ endpoint: string;
35
+ apiKey?: string;
36
+ }
37
+
38
+ /**
39
+ * Extracts CopilotKit-compatible parameters from an MCP tool schema.
40
+ * @param toolOrSchema The schema object from an MCPTool or the full MCPTool object.
41
+ * @returns An array of Parameter objects.
42
+ */
43
+ export function extractParametersFromSchema(
44
+ toolOrSchema?: MCPTool | MCPTool["schema"],
45
+ ): Parameter[] {
46
+ const parameters: Parameter[] = [];
47
+
48
+ // Handle either full tool object or just schema
49
+ const schema =
50
+ "schema" in (toolOrSchema || {})
51
+ ? (toolOrSchema as MCPTool).schema
52
+ : (toolOrSchema as MCPTool["schema"]);
53
+
54
+ const toolParameters = schema?.parameters?.jsonSchema || schema?.parameters;
55
+ const properties = toolParameters?.properties;
56
+ const requiredParams = new Set(toolParameters?.required || []);
57
+
58
+ if (!properties) {
59
+ return parameters;
60
+ }
61
+
62
+ for (const paramName in properties) {
63
+ if (Object.prototype.hasOwnProperty.call(properties, paramName)) {
64
+ const paramDef = properties[paramName];
65
+
66
+ // Enhanced type extraction with support for complex types
67
+ let type = paramDef.type || "string";
68
+ let description = paramDef.description || "";
69
+
70
+ // Handle arrays with items
71
+ if (type === "array" && paramDef.items) {
72
+ const itemType = paramDef.items.type || "object";
73
+ if (itemType === "object" && paramDef.items.properties) {
74
+ // For arrays of objects, describe the structure
75
+ const itemProperties = Object.keys(paramDef.items.properties).join(", ");
76
+ description =
77
+ description +
78
+ (description ? " " : "") +
79
+ `Array of objects with properties: ${itemProperties}`;
80
+ } else {
81
+ // For arrays of primitives
82
+ type = `array<${itemType}>`;
83
+ }
84
+ }
85
+
86
+ // Handle enums
87
+ if (paramDef.enum && Array.isArray(paramDef.enum)) {
88
+ const enumValues = paramDef.enum.join(" | ");
89
+ description = description + (description ? " " : "") + `Allowed values: ${enumValues}`;
90
+ }
91
+
92
+ // Handle objects with properties
93
+ if (type === "object" && paramDef.properties) {
94
+ const objectProperties = Object.keys(paramDef.properties).join(", ");
95
+ description =
96
+ description + (description ? " " : "") + `Object with properties: ${objectProperties}`;
97
+ }
98
+
99
+ parameters.push({
100
+ name: paramName,
101
+ type: type,
102
+ description: description,
103
+ required: requiredParams.has(paramName),
104
+ });
105
+ }
106
+ }
107
+
108
+ return parameters;
109
+ }
110
+
111
+ /**
112
+ * Converts a map of MCPTools into an array of CopilotKit Actions.
113
+ * @param mcpTools A record mapping tool names to MCPTool objects.
114
+ * @param mcpEndpoint The endpoint URL from which these tools were fetched.
115
+ * @returns An array of Action<any> objects.
116
+ */
117
+ export function convertMCPToolsToActions(
118
+ mcpTools: Record<string, MCPTool>,
119
+ mcpEndpoint: string,
120
+ ): Action<any>[] {
121
+ const actions: Action<any>[] = [];
122
+
123
+ for (const [toolName, tool] of Object.entries(mcpTools)) {
124
+ const parameters = extractParametersFromSchema(tool);
125
+
126
+ const handler = async (params: any): Promise<any> => {
127
+ try {
128
+ const result = await tool.execute(params);
129
+ // Ensure the result is a string or stringify it, as required by many LLMs.
130
+ // This might need adjustment depending on how different LLMs handle tool results.
131
+ return typeof result === "string" ? result : JSON.stringify(result);
132
+ } catch (error) {
133
+ console.error(
134
+ `Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`,
135
+ error,
136
+ );
137
+ // Re-throw or format the error for the LLM
138
+ throw new Error(
139
+ `Execution failed for MCP tool '${toolName}': ${
140
+ error instanceof Error ? error.message : String(error)
141
+ }`,
142
+ );
143
+ }
144
+ };
145
+
146
+ actions.push({
147
+ name: toolName,
148
+ description: tool.description || `MCP tool: ${toolName} (from ${mcpEndpoint})`,
149
+ parameters: parameters,
150
+ handler: handler,
151
+ // Add metadata for easier identification/debugging
152
+ _isMCPTool: true,
153
+ _mcpEndpoint: mcpEndpoint,
154
+ } as Action<any> & { _isMCPTool: boolean; _mcpEndpoint: string }); // Type assertion for metadata
155
+ }
156
+
157
+ return actions;
158
+ }
159
+
160
+ /**
161
+ * Generate better instructions for using MCP tools
162
+ * This is used to enhance the system prompt with tool documentation
163
+ */
164
+ export function generateMcpToolInstructions(toolsMap: Record<string, MCPTool>): string {
165
+ if (!toolsMap || Object.keys(toolsMap).length === 0) {
166
+ return "";
167
+ }
168
+
169
+ const toolEntries = Object.entries(toolsMap);
170
+
171
+ // Generate documentation for each tool
172
+ const toolsDoc = toolEntries
173
+ .map(([name, tool]) => {
174
+ // Extract schema information if available
175
+ let paramsDoc = " No parameters required";
176
+
177
+ try {
178
+ if (tool.schema && typeof tool.schema === "object") {
179
+ const schema = tool.schema as any;
180
+
181
+ // Extract parameters from JSON Schema - check both schema.parameters.properties and schema.properties
182
+ const toolParameters = schema.parameters?.jsonSchema || schema.parameters;
183
+ const properties = toolParameters?.properties || schema.properties;
184
+ const requiredParams = toolParameters?.required || schema.required || [];
185
+
186
+ if (properties) {
187
+ // Build parameter documentation from properties with enhanced type information
188
+ const paramsList = Object.entries(properties).map(([paramName, propSchema]) => {
189
+ const propDetails = propSchema as any;
190
+ const requiredMark = requiredParams.includes(paramName) ? "*" : "";
191
+ let typeInfo = propDetails.type || "any";
192
+ let description = propDetails.description ? ` - ${propDetails.description}` : "";
193
+
194
+ // Enhanced type display for complex schemas
195
+ if (typeInfo === "array" && propDetails.items) {
196
+ const itemType = propDetails.items.type || "object";
197
+ if (itemType === "object" && propDetails.items.properties) {
198
+ const itemProps = Object.keys(propDetails.items.properties).join(", ");
199
+ typeInfo = `array<object>`;
200
+ description =
201
+ description +
202
+ (description ? " " : " - ") +
203
+ `Array of objects with properties: ${itemProps}`;
204
+ } else {
205
+ typeInfo = `array<${itemType}>`;
206
+ }
207
+ }
208
+
209
+ // Handle enums
210
+ if (propDetails.enum && Array.isArray(propDetails.enum)) {
211
+ const enumValues = propDetails.enum.join(" | ");
212
+ description =
213
+ description + (description ? " " : " - ") + `Allowed values: ${enumValues}`;
214
+ }
215
+
216
+ // Handle objects
217
+ if (typeInfo === "object" && propDetails.properties) {
218
+ const objectProps = Object.keys(propDetails.properties).join(", ");
219
+ description =
220
+ description +
221
+ (description ? " " : " - ") +
222
+ `Object with properties: ${objectProps}`;
223
+ }
224
+
225
+ return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;
226
+ });
227
+
228
+ if (paramsList.length > 0) {
229
+ paramsDoc = paramsList.join("\n");
230
+ }
231
+ }
232
+ }
233
+ } catch (e) {
234
+ console.error(`Error parsing schema for tool ${name}:`, e);
235
+ }
236
+
237
+ return `- ${name}: ${tool.description || ""}
238
+ ${paramsDoc}`;
239
+ })
240
+ .join("\n\n");
241
+
242
+ return `You have access to the following external tools provided by Model Context Protocol (MCP) servers:
243
+
244
+ ${toolsDoc}
245
+
246
+ When using these tools:
247
+ 1. Only provide valid parameters according to their type requirements
248
+ 2. Required parameters are marked with *
249
+ 3. For array parameters, provide data in the correct array format
250
+ 4. For object parameters, include all required nested properties
251
+ 5. For enum parameters, use only the allowed values listed
252
+ 6. Format API calls correctly with the expected parameter structure
253
+ 7. Always check tool responses to determine your next action`;
254
+ }
@@ -0,0 +1,96 @@
1
+ import { Logger } from "pino";
2
+
3
+ // Retry configuration for network requests
4
+ export const RETRY_CONFIG = {
5
+ maxRetries: 3,
6
+ baseDelayMs: 1000,
7
+ maxDelayMs: 5000,
8
+ // HTTP status codes that should be retried
9
+ retryableStatusCodes: [502, 503, 504, 408, 429],
10
+ // Network error patterns that should be retried
11
+ retryableErrorMessages: [
12
+ "fetch failed",
13
+ "network error",
14
+ "connection timeout",
15
+ "ECONNREFUSED",
16
+ "ETIMEDOUT",
17
+ "ENOTFOUND",
18
+ "ECONNRESET",
19
+ ],
20
+ };
21
+
22
+ // Helper function to check if an error/response is retryable
23
+ export function isRetryableError(error: any, response?: Response): boolean {
24
+ // Check HTTP response status
25
+ if (response && RETRY_CONFIG.retryableStatusCodes.includes(response.status)) {
26
+ return true;
27
+ }
28
+
29
+ // Check error codes (for connection errors like ECONNREFUSED)
30
+ const errorCode = error?.cause?.code || error?.code;
31
+ if (errorCode && RETRY_CONFIG.retryableErrorMessages.includes(errorCode)) {
32
+ return true;
33
+ }
34
+
35
+ // Check error messages
36
+ const errorMessage = error?.message?.toLowerCase() || "";
37
+ return RETRY_CONFIG.retryableErrorMessages.some((msg) => errorMessage.includes(msg));
38
+ }
39
+
40
+ // Helper function to sleep for a given duration
41
+ export function sleep(ms: number): Promise<void> {
42
+ return new Promise((resolve) => setTimeout(resolve, ms));
43
+ }
44
+
45
+ // Calculate exponential backoff delay
46
+ export function calculateDelay(attempt: number): number {
47
+ const delay = RETRY_CONFIG.baseDelayMs * Math.pow(2, attempt);
48
+ return Math.min(delay, RETRY_CONFIG.maxDelayMs);
49
+ }
50
+
51
+ // Retry wrapper for fetch requests
52
+ export async function fetchWithRetry(
53
+ url: string,
54
+ options: RequestInit,
55
+ logger?: Logger,
56
+ ): Promise<Response> {
57
+ let lastError: any;
58
+
59
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
60
+ try {
61
+ const response = await fetch(url, options);
62
+
63
+ // If response is retryable, treat as error and retry
64
+ if (isRetryableError(null, response) && attempt < RETRY_CONFIG.maxRetries) {
65
+ const delay = calculateDelay(attempt);
66
+ logger?.warn(
67
+ `Request to ${url} failed with status ${response.status}. ` +
68
+ `Retrying attempt ${attempt + 1}/${RETRY_CONFIG.maxRetries + 1} in ${delay}ms.`,
69
+ );
70
+ await sleep(delay);
71
+ continue;
72
+ }
73
+
74
+ return response; // Success or non-retryable error
75
+ } catch (error) {
76
+ lastError = error;
77
+
78
+ // Check if this is a retryable network error
79
+ if (isRetryableError(error) && attempt < RETRY_CONFIG.maxRetries) {
80
+ const delay = calculateDelay(attempt);
81
+ logger?.warn(
82
+ `Request to ${url} failed with network error. ` +
83
+ `Retrying attempt ${attempt + 1}/${RETRY_CONFIG.maxRetries + 1} in ${delay}ms. Error: ${error?.message || String(error)}`,
84
+ );
85
+ await sleep(delay);
86
+ continue;
87
+ }
88
+
89
+ // Not retryable or max retries exceeded
90
+ break;
91
+ }
92
+ }
93
+
94
+ // Re-throw the last error after retries exhausted
95
+ throw lastError;
96
+ }
@@ -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
+ }