@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.
- package/.eslintrc.js +7 -0
- package/CHANGELOG.md +2905 -0
- package/LICENSE +21 -0
- package/README.md +76 -0
- package/__snapshots__/schema/schema.graphql +371 -0
- package/dist/index.d.ts +1495 -0
- package/dist/index.js +5644 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +5601 -0
- package/dist/index.mjs.map +1 -0
- package/dist/langgraph.d.ts +284 -0
- package/dist/langgraph.js +211 -0
- package/dist/langgraph.js.map +1 -0
- package/dist/langgraph.mjs +206 -0
- package/dist/langgraph.mjs.map +1 -0
- package/dist/v2/index.d.ts +2 -0
- package/dist/v2/index.js +22 -0
- package/dist/v2/index.js.map +1 -0
- package/dist/v2/index.mjs +5 -0
- package/dist/v2/index.mjs.map +1 -0
- package/jest.config.js +10 -0
- package/package.json +143 -0
- package/scripts/generate-gql-schema.ts +13 -0
- package/src/agents/langgraph/event-source.ts +329 -0
- package/src/agents/langgraph/events.ts +377 -0
- package/src/graphql/inputs/action.input.ts +16 -0
- package/src/graphql/inputs/agent-session.input.ts +13 -0
- package/src/graphql/inputs/agent-state.input.ts +13 -0
- package/src/graphql/inputs/cloud-guardrails.input.ts +16 -0
- package/src/graphql/inputs/cloud.input.ts +8 -0
- package/src/graphql/inputs/context-property.input.ts +10 -0
- package/src/graphql/inputs/copilot-context.input.ts +10 -0
- package/src/graphql/inputs/custom-property.input.ts +15 -0
- package/src/graphql/inputs/extensions.input.ts +21 -0
- package/src/graphql/inputs/forwarded-parameters.input.ts +22 -0
- package/src/graphql/inputs/frontend.input.ts +14 -0
- package/src/graphql/inputs/generate-copilot-response.input.ts +59 -0
- package/src/graphql/inputs/load-agent-state.input.ts +10 -0
- package/src/graphql/inputs/message.input.ts +110 -0
- package/src/graphql/inputs/meta-event.input.ts +18 -0
- package/src/graphql/message-conversion/agui-to-gql.test.ts +1263 -0
- package/src/graphql/message-conversion/agui-to-gql.ts +333 -0
- package/src/graphql/message-conversion/gql-to-agui.test.ts +1580 -0
- package/src/graphql/message-conversion/gql-to-agui.ts +278 -0
- package/src/graphql/message-conversion/index.ts +2 -0
- package/src/graphql/message-conversion/roundtrip-conversion.test.ts +526 -0
- package/src/graphql/resolvers/copilot.resolver.ts +708 -0
- package/src/graphql/resolvers/state.resolver.ts +27 -0
- package/src/graphql/types/agents-response.type.ts +19 -0
- package/src/graphql/types/base/index.ts +10 -0
- package/src/graphql/types/converted/index.ts +176 -0
- package/src/graphql/types/copilot-response.type.ts +138 -0
- package/src/graphql/types/enums.ts +38 -0
- package/src/graphql/types/extensions-response.type.ts +23 -0
- package/src/graphql/types/guardrails-result.type.ts +20 -0
- package/src/graphql/types/load-agent-state-response.type.ts +17 -0
- package/src/graphql/types/message-status.type.ts +42 -0
- package/src/graphql/types/meta-events.type.ts +71 -0
- package/src/graphql/types/response-status.type.ts +66 -0
- package/src/index.ts +4 -0
- package/src/langgraph.ts +1 -0
- package/src/lib/cloud/index.ts +4 -0
- package/src/lib/error-messages.ts +200 -0
- package/src/lib/index.ts +52 -0
- package/src/lib/integrations/index.ts +6 -0
- package/src/lib/integrations/nest/index.ts +14 -0
- package/src/lib/integrations/nextjs/app-router.ts +38 -0
- package/src/lib/integrations/nextjs/pages-router.ts +39 -0
- package/src/lib/integrations/node-express/index.ts +14 -0
- package/src/lib/integrations/node-http/index.ts +143 -0
- package/src/lib/integrations/node-http/request-handler.ts +111 -0
- package/src/lib/integrations/shared.ts +161 -0
- package/src/lib/logger.ts +28 -0
- package/src/lib/observability.ts +160 -0
- package/src/lib/runtime/__tests__/copilot-runtime-error.test.ts +169 -0
- package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +464 -0
- package/src/lib/runtime/agent-integrations/langgraph/agent.ts +209 -0
- package/src/lib/runtime/agent-integrations/langgraph/consts.ts +34 -0
- package/src/lib/runtime/agent-integrations/langgraph/index.ts +2 -0
- package/src/lib/runtime/copilot-runtime.ts +710 -0
- package/src/lib/runtime/mcp-tools-utils.ts +254 -0
- package/src/lib/runtime/retry-utils.ts +96 -0
- package/src/lib/runtime/telemetry-agent-runner.ts +139 -0
- package/src/lib/runtime/types.ts +49 -0
- package/src/lib/runtime/utils.ts +87 -0
- package/src/lib/streaming.ts +202 -0
- package/src/lib/telemetry-client.ts +64 -0
- package/src/service-adapters/anthropic/anthropic-adapter.ts +452 -0
- package/src/service-adapters/anthropic/utils.ts +152 -0
- package/src/service-adapters/bedrock/bedrock-adapter.ts +73 -0
- package/src/service-adapters/conversion.ts +67 -0
- package/src/service-adapters/empty/empty-adapter.ts +38 -0
- package/src/service-adapters/events.ts +294 -0
- package/src/service-adapters/experimental/ollama/ollama-adapter.ts +84 -0
- package/src/service-adapters/google/google-genai-adapter.test.ts +104 -0
- package/src/service-adapters/google/google-genai-adapter.ts +88 -0
- package/src/service-adapters/groq/groq-adapter.ts +203 -0
- package/src/service-adapters/index.ts +18 -0
- package/src/service-adapters/langchain/langchain-adapter.ts +111 -0
- package/src/service-adapters/langchain/langserve.ts +88 -0
- package/src/service-adapters/langchain/types.ts +14 -0
- package/src/service-adapters/langchain/utils.ts +313 -0
- package/src/service-adapters/openai/openai-adapter.ts +283 -0
- package/src/service-adapters/openai/openai-assistant-adapter.ts +344 -0
- package/src/service-adapters/openai/utils.ts +199 -0
- package/src/service-adapters/service-adapter.ts +41 -0
- package/src/service-adapters/shared/error-utils.ts +61 -0
- package/src/service-adapters/shared/index.ts +1 -0
- package/src/service-adapters/unify/unify-adapter.ts +151 -0
- package/src/utils/failed-response-status-reasons.ts +70 -0
- package/src/utils/index.ts +1 -0
- package/src/v2/index.ts +3 -0
- package/tests/global.d.ts +13 -0
- package/tests/service-adapters/anthropic/allowlist-approach.test.ts +226 -0
- package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +389 -0
- package/tests/service-adapters/openai/allowlist-approach.test.ts +238 -0
- package/tests/service-adapters/openai/openai-adapter.test.ts +301 -0
- package/tests/setup.jest.ts +21 -0
- package/tests/tsconfig.json +10 -0
- package/tsconfig.json +13 -0
- package/tsup.config.ts +20 -0
- package/typedoc.json +4 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error message configuration - Single source of truth for all error messages
|
|
3
|
+
*
|
|
4
|
+
* This centralized configuration system provides:
|
|
5
|
+
*
|
|
6
|
+
* 🎯 **Benefits:**
|
|
7
|
+
* - Single source of truth for all error messages
|
|
8
|
+
* - Easy content management without touching code
|
|
9
|
+
* - Consistent error messaging across the application
|
|
10
|
+
* - Ready for internationalization (i18n)
|
|
11
|
+
* - Type-safe configuration with TypeScript
|
|
12
|
+
* - Categorized errors for better handling
|
|
13
|
+
*
|
|
14
|
+
* 📝 **How to use:**
|
|
15
|
+
* 1. Add new error patterns to `errorPatterns` object
|
|
16
|
+
* 2. Use {context} placeholder for dynamic context injection
|
|
17
|
+
* 3. Specify category, severity, and actionable flags
|
|
18
|
+
* 4. Add fallback messages for error categories
|
|
19
|
+
*
|
|
20
|
+
* 🔧 **How to maintain:**
|
|
21
|
+
* - Content teams can update messages here without touching logic
|
|
22
|
+
* - Developers add new error patterns as needed
|
|
23
|
+
* - Use categories to group similar errors
|
|
24
|
+
* - Mark errors as actionable if users can fix them
|
|
25
|
+
*
|
|
26
|
+
* 🌍 **Future i18n support:**
|
|
27
|
+
* - Replace `message` string with `messages: { en: "...", es: "..." }`
|
|
28
|
+
* - Add locale parameter to helper functions
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* // Adding a new error pattern:
|
|
33
|
+
* "CUSTOM_ERROR": {
|
|
34
|
+
* message: "Custom error occurred in {context}. Please try again.",
|
|
35
|
+
* category: "unknown",
|
|
36
|
+
* severity: "error",
|
|
37
|
+
* actionable: true
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
export interface ErrorPatternConfig {
|
|
43
|
+
message: string;
|
|
44
|
+
category: "network" | "connection" | "authentication" | "validation" | "unknown";
|
|
45
|
+
severity: "error" | "warning" | "info";
|
|
46
|
+
actionable: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ErrorConfig {
|
|
50
|
+
errorPatterns: Record<string, ErrorPatternConfig>;
|
|
51
|
+
fallbacks: Record<string, string>;
|
|
52
|
+
contextTemplates: Record<string, string>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const errorConfig: ErrorConfig = {
|
|
56
|
+
errorPatterns: {
|
|
57
|
+
ECONNREFUSED: {
|
|
58
|
+
message:
|
|
59
|
+
"Connection refused - the agent service is not running or not accessible at the specified address. Please check that your agent is started and listening on the correct port.",
|
|
60
|
+
category: "network",
|
|
61
|
+
severity: "error",
|
|
62
|
+
actionable: true,
|
|
63
|
+
},
|
|
64
|
+
ENOTFOUND: {
|
|
65
|
+
message:
|
|
66
|
+
"Host not found - the agent service URL appears to be incorrect or the service is not accessible. Please verify the agent endpoint URL.",
|
|
67
|
+
category: "network",
|
|
68
|
+
severity: "error",
|
|
69
|
+
actionable: true,
|
|
70
|
+
},
|
|
71
|
+
ETIMEDOUT: {
|
|
72
|
+
message:
|
|
73
|
+
"Connection timeout - the agent service is taking too long to respond. This could indicate network issues or an overloaded agent service.",
|
|
74
|
+
category: "network",
|
|
75
|
+
severity: "warning",
|
|
76
|
+
actionable: true,
|
|
77
|
+
},
|
|
78
|
+
terminated: {
|
|
79
|
+
message:
|
|
80
|
+
"Agent {context} was unexpectedly terminated. This often indicates an error in the agent service (e.g., authentication failures, missing environment variables, or agent crashes). Check the agent logs for the root cause.",
|
|
81
|
+
category: "connection",
|
|
82
|
+
severity: "error",
|
|
83
|
+
actionable: true,
|
|
84
|
+
},
|
|
85
|
+
UND_ERR_SOCKET: {
|
|
86
|
+
message:
|
|
87
|
+
"Socket connection was closed unexpectedly. This typically indicates the agent service encountered an error and shut down the connection. Check the agent logs for the underlying cause.",
|
|
88
|
+
category: "connection",
|
|
89
|
+
severity: "error",
|
|
90
|
+
actionable: true,
|
|
91
|
+
},
|
|
92
|
+
other_side_closed: {
|
|
93
|
+
message:
|
|
94
|
+
"The agent service closed the connection unexpectedly. This usually indicates an error in the agent service. Check the agent logs for more details.",
|
|
95
|
+
category: "connection",
|
|
96
|
+
severity: "error",
|
|
97
|
+
actionable: true,
|
|
98
|
+
},
|
|
99
|
+
fetch_failed: {
|
|
100
|
+
message:
|
|
101
|
+
"Failed to connect to the agent service. Please verify the agent is running and the endpoint URL is correct.",
|
|
102
|
+
category: "network",
|
|
103
|
+
severity: "error",
|
|
104
|
+
actionable: true,
|
|
105
|
+
},
|
|
106
|
+
// Authentication patterns
|
|
107
|
+
"401": {
|
|
108
|
+
message:
|
|
109
|
+
"Authentication failed. Please check your API keys and ensure they are correctly configured.",
|
|
110
|
+
category: "authentication",
|
|
111
|
+
severity: "error",
|
|
112
|
+
actionable: true,
|
|
113
|
+
},
|
|
114
|
+
"api key": {
|
|
115
|
+
message:
|
|
116
|
+
"API key error detected. Please verify your API key is correct and has the necessary permissions.",
|
|
117
|
+
category: "authentication",
|
|
118
|
+
severity: "error",
|
|
119
|
+
actionable: true,
|
|
120
|
+
},
|
|
121
|
+
unauthorized: {
|
|
122
|
+
message: "Unauthorized access. Please check your authentication credentials.",
|
|
123
|
+
category: "authentication",
|
|
124
|
+
severity: "error",
|
|
125
|
+
actionable: true,
|
|
126
|
+
},
|
|
127
|
+
// Python-specific error patterns
|
|
128
|
+
AuthenticationError: {
|
|
129
|
+
message:
|
|
130
|
+
"OpenAI authentication failed. Please check your OPENAI_API_KEY environment variable or API key configuration.",
|
|
131
|
+
category: "authentication",
|
|
132
|
+
severity: "error",
|
|
133
|
+
actionable: true,
|
|
134
|
+
},
|
|
135
|
+
"Incorrect API key provided": {
|
|
136
|
+
message:
|
|
137
|
+
"OpenAI API key is invalid. Please verify your OPENAI_API_KEY is correct and active.",
|
|
138
|
+
category: "authentication",
|
|
139
|
+
severity: "error",
|
|
140
|
+
actionable: true,
|
|
141
|
+
},
|
|
142
|
+
RateLimitError: {
|
|
143
|
+
message:
|
|
144
|
+
"OpenAI rate limit exceeded. Please wait a moment and try again, or check your OpenAI usage limits.",
|
|
145
|
+
category: "network",
|
|
146
|
+
severity: "warning",
|
|
147
|
+
actionable: true,
|
|
148
|
+
},
|
|
149
|
+
InvalidRequestError: {
|
|
150
|
+
message:
|
|
151
|
+
"Invalid request to OpenAI API. Please check your request parameters and model configuration.",
|
|
152
|
+
category: "validation",
|
|
153
|
+
severity: "error",
|
|
154
|
+
actionable: true,
|
|
155
|
+
},
|
|
156
|
+
PermissionDeniedError: {
|
|
157
|
+
message:
|
|
158
|
+
"Permission denied for OpenAI API. Please check your API key permissions and billing status.",
|
|
159
|
+
category: "authentication",
|
|
160
|
+
severity: "error",
|
|
161
|
+
actionable: true,
|
|
162
|
+
},
|
|
163
|
+
NotFoundError: {
|
|
164
|
+
message: "OpenAI resource not found. Please check your model name and availability.",
|
|
165
|
+
category: "validation",
|
|
166
|
+
severity: "error",
|
|
167
|
+
actionable: true,
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
fallbacks: {
|
|
171
|
+
network:
|
|
172
|
+
"A network error occurred while connecting to the agent service. Please check your connection and ensure the agent service is running.",
|
|
173
|
+
connection:
|
|
174
|
+
"The connection to the agent service was lost unexpectedly. This may indicate an issue with the agent service.",
|
|
175
|
+
authentication: "Authentication failed. Please check your API keys and credentials.",
|
|
176
|
+
validation: "Invalid input or configuration. Please check your parameters and try again.",
|
|
177
|
+
unknown: "An unexpected error occurred. Please check the logs for more details.",
|
|
178
|
+
default: "An unexpected error occurred. Please check the logs for more details.",
|
|
179
|
+
},
|
|
180
|
+
contextTemplates: {
|
|
181
|
+
connection: "connection",
|
|
182
|
+
event_streaming_connection: "event streaming connection",
|
|
183
|
+
agent_streaming_connection: "agent streaming connection",
|
|
184
|
+
langgraph_agent_connection: "LangGraph agent connection",
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Helper function to get error pattern configuration by key
|
|
190
|
+
*/
|
|
191
|
+
export function getErrorPattern(key: string): ErrorPatternConfig | undefined {
|
|
192
|
+
return errorConfig.errorPatterns[key];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Helper function to get fallback message by category
|
|
197
|
+
*/
|
|
198
|
+
export function getFallbackMessage(category: string): string {
|
|
199
|
+
return errorConfig.fallbacks[category] || errorConfig.fallbacks.default;
|
|
200
|
+
}
|
package/src/lib/index.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export * from "../service-adapters/openai/openai-adapter";
|
|
2
|
+
export * from "../service-adapters/langchain/langchain-adapter";
|
|
3
|
+
export * from "../service-adapters/google/google-genai-adapter";
|
|
4
|
+
export * from "../service-adapters/openai/openai-assistant-adapter";
|
|
5
|
+
export * from "../service-adapters/unify/unify-adapter";
|
|
6
|
+
export * from "../service-adapters/groq/groq-adapter";
|
|
7
|
+
export * from "./integrations";
|
|
8
|
+
export * from "./logger";
|
|
9
|
+
export * from "./runtime/copilot-runtime";
|
|
10
|
+
export * from "./runtime/mcp-tools-utils";
|
|
11
|
+
export * from "./runtime/telemetry-agent-runner";
|
|
12
|
+
|
|
13
|
+
// The below re-exports "dummy" classes and types, to get a deprecation warning redirecting the users to import these from the correct, new route
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @deprecated LangGraphAgent import from `@copilotkit/runtime` is deprecated. Please import it from `@copilotkit/runtime/langgraph` instead
|
|
17
|
+
*/
|
|
18
|
+
export class LangGraphAgent {
|
|
19
|
+
constructor() {
|
|
20
|
+
throw new Error(
|
|
21
|
+
"LangGraphAgent import from @copilotkit/runtime is deprecated. Please import it from @copilotkit/runtime/langgraph instead",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @deprecated LangGraphHttpAgent import from `@copilotkit/runtime` is deprecated. Please import it from `@copilotkit/runtime/langgraph` instead
|
|
28
|
+
*/
|
|
29
|
+
export class LangGraphHttpAgent {
|
|
30
|
+
constructor() {
|
|
31
|
+
throw new Error(
|
|
32
|
+
"LangGraphHttpAgent import from @copilotkit/runtime is deprecated. Please import it from @copilotkit/runtime/langgraph instead",
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @deprecated TextMessageEvents import from `@copilotkit/runtime` is deprecated. Please import it from `@copilotkit/runtime/langgraph` instead
|
|
39
|
+
*/
|
|
40
|
+
export type TextMessageEvents = any;
|
|
41
|
+
/**
|
|
42
|
+
* @deprecated ToolCallEvents import from `@copilotkit/runtime` is deprecated. Please import it from `@copilotkit/runtime/langgraph` instead
|
|
43
|
+
*/
|
|
44
|
+
export type ToolCallEvents = any;
|
|
45
|
+
/**
|
|
46
|
+
* @deprecated CustomEventNames import from `@copilotkit/runtime` is deprecated. Please import it from `@copilotkit/runtime/langgraph` instead
|
|
47
|
+
*/
|
|
48
|
+
export type CustomEventNames = any;
|
|
49
|
+
/**
|
|
50
|
+
* @deprecated PredictStateTool import from `@copilotkit/runtime` is deprecated. Please import it from `@copilotkit/runtime/langgraph` instead
|
|
51
|
+
*/
|
|
52
|
+
export type PredictStateTool = any;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CreateCopilotRuntimeServerOptions } from "../shared";
|
|
2
|
+
import { copilotRuntimeNodeHttpEndpoint } from "../node-http";
|
|
3
|
+
import telemetry, { getRuntimeInstanceTelemetryInfo } from "../../telemetry-client";
|
|
4
|
+
|
|
5
|
+
export function copilotRuntimeNestEndpoint(options: CreateCopilotRuntimeServerOptions) {
|
|
6
|
+
telemetry.setGlobalProperties({
|
|
7
|
+
runtime: {
|
|
8
|
+
framework: "nest",
|
|
9
|
+
},
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
telemetry.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
|
|
13
|
+
return copilotRuntimeNodeHttpEndpoint(options);
|
|
14
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createCopilotEndpointSingleRoute } from "@copilotkitnext/runtime";
|
|
2
|
+
import { CreateCopilotRuntimeServerOptions, getCommonConfig } from "../shared";
|
|
3
|
+
import telemetry, { getRuntimeInstanceTelemetryInfo } from "../../telemetry-client";
|
|
4
|
+
import { handle } from "hono/vercel";
|
|
5
|
+
|
|
6
|
+
export function copilotRuntimeNextJSAppRouterEndpoint(options: CreateCopilotRuntimeServerOptions) {
|
|
7
|
+
const commonConfig = getCommonConfig(options);
|
|
8
|
+
|
|
9
|
+
telemetry.setGlobalProperties({
|
|
10
|
+
runtime: {
|
|
11
|
+
framework: "nextjs-app-router",
|
|
12
|
+
},
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
if (options.properties?._copilotkit) {
|
|
16
|
+
telemetry.setGlobalProperties({
|
|
17
|
+
_copilotkit: options.properties._copilotkit,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
telemetry.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
|
|
22
|
+
|
|
23
|
+
const logger = commonConfig.logging;
|
|
24
|
+
logger.debug("Creating NextJS App Router endpoint");
|
|
25
|
+
|
|
26
|
+
const serviceAdapter = options.serviceAdapter;
|
|
27
|
+
if (serviceAdapter) {
|
|
28
|
+
options.runtime.handleServiceAdapter(serviceAdapter);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const copilotRoute = createCopilotEndpointSingleRoute({
|
|
32
|
+
runtime: options.runtime.instance,
|
|
33
|
+
basePath: options.baseUrl ?? options.endpoint,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const handleRequest = handle(copilotRoute as any);
|
|
37
|
+
return { handleRequest };
|
|
38
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { CreateCopilotRuntimeServerOptions, getCommonConfig } from "../shared";
|
|
2
|
+
import telemetry, { getRuntimeInstanceTelemetryInfo } from "../../telemetry-client";
|
|
3
|
+
import { copilotRuntimeNodeHttpEndpoint } from "../node-http";
|
|
4
|
+
|
|
5
|
+
export const config = {
|
|
6
|
+
api: {
|
|
7
|
+
bodyParser: false,
|
|
8
|
+
},
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// This import is needed to fix the type error
|
|
12
|
+
// Fix is currently in TypeScript 5.5 beta, waiting for stable version
|
|
13
|
+
// https://github.com/microsoft/TypeScript/issues/42873#issuecomment-2066874644
|
|
14
|
+
export type {} from "@whatwg-node/server";
|
|
15
|
+
|
|
16
|
+
export function copilotRuntimeNextJSPagesRouterEndpoint(
|
|
17
|
+
options: CreateCopilotRuntimeServerOptions,
|
|
18
|
+
) {
|
|
19
|
+
const commonConfig = getCommonConfig(options);
|
|
20
|
+
|
|
21
|
+
telemetry.setGlobalProperties({
|
|
22
|
+
runtime: {
|
|
23
|
+
framework: "nextjs-pages-router",
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
if (options.properties?._copilotkit) {
|
|
28
|
+
telemetry.setGlobalProperties({
|
|
29
|
+
_copilotkit: options.properties._copilotkit,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
telemetry.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
|
|
34
|
+
|
|
35
|
+
const logger = commonConfig.logging;
|
|
36
|
+
logger.debug("Creating NextJS Pages Router endpoint");
|
|
37
|
+
|
|
38
|
+
return copilotRuntimeNodeHttpEndpoint(options);
|
|
39
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CreateCopilotRuntimeServerOptions } from "../shared";
|
|
2
|
+
import { copilotRuntimeNodeHttpEndpoint } from "../node-http";
|
|
3
|
+
import telemetry, { getRuntimeInstanceTelemetryInfo } from "../../telemetry-client";
|
|
4
|
+
|
|
5
|
+
export function copilotRuntimeNodeExpressEndpoint(options: CreateCopilotRuntimeServerOptions) {
|
|
6
|
+
telemetry.setGlobalProperties({
|
|
7
|
+
runtime: {
|
|
8
|
+
framework: "node-express",
|
|
9
|
+
},
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
telemetry.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
|
|
13
|
+
return copilotRuntimeNodeHttpEndpoint(options);
|
|
14
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { CreateCopilotRuntimeServerOptions, getCommonConfig } from "../shared";
|
|
2
|
+
import telemetry, { getRuntimeInstanceTelemetryInfo } from "../../telemetry-client";
|
|
3
|
+
import { createCopilotEndpointSingleRoute } from "@copilotkitnext/runtime";
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
5
|
+
import {
|
|
6
|
+
getFullUrl,
|
|
7
|
+
IncomingWithBody,
|
|
8
|
+
isDisturbedOrLockedError,
|
|
9
|
+
isStreamConsumed,
|
|
10
|
+
nodeStreamToReadableStream,
|
|
11
|
+
readableStreamToNodeStream,
|
|
12
|
+
synthesizeBodyFromParsedBody,
|
|
13
|
+
toHeaders,
|
|
14
|
+
} from "./request-handler";
|
|
15
|
+
|
|
16
|
+
export function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {
|
|
17
|
+
const commonConfig = getCommonConfig(options);
|
|
18
|
+
|
|
19
|
+
telemetry.setGlobalProperties({
|
|
20
|
+
runtime: {
|
|
21
|
+
framework: "node-http",
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
if (options.properties?._copilotkit) {
|
|
26
|
+
telemetry.setGlobalProperties({
|
|
27
|
+
_copilotkit: options.properties._copilotkit,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
telemetry.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
|
|
32
|
+
|
|
33
|
+
const logger = commonConfig.logging;
|
|
34
|
+
logger.debug("Creating Node HTTP endpoint");
|
|
35
|
+
|
|
36
|
+
const serviceAdapter = options.serviceAdapter;
|
|
37
|
+
if (serviceAdapter) {
|
|
38
|
+
options.runtime.handleServiceAdapter(serviceAdapter);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const honoApp = createCopilotEndpointSingleRoute({
|
|
42
|
+
runtime: options.runtime.instance,
|
|
43
|
+
basePath: options.baseUrl ?? options.endpoint,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const handle = async function handler(req: IncomingWithBody, res: ServerResponse) {
|
|
47
|
+
const url = getFullUrl(req);
|
|
48
|
+
const hasBody = req.method !== "GET" && req.method !== "HEAD";
|
|
49
|
+
|
|
50
|
+
const baseHeaders = toHeaders(req.headers);
|
|
51
|
+
const parsedBody = req.body;
|
|
52
|
+
|
|
53
|
+
const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;
|
|
54
|
+
const canStream = hasBody && !streamConsumed;
|
|
55
|
+
|
|
56
|
+
let requestBody: BodyInit | null | undefined = undefined;
|
|
57
|
+
let useDuplex = false;
|
|
58
|
+
|
|
59
|
+
if (hasBody && canStream) {
|
|
60
|
+
requestBody = nodeStreamToReadableStream(req);
|
|
61
|
+
useDuplex = true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (hasBody && streamConsumed) {
|
|
65
|
+
if (parsedBody !== undefined) {
|
|
66
|
+
const synthesized = synthesizeBodyFromParsedBody(parsedBody, baseHeaders);
|
|
67
|
+
requestBody = synthesized.body ?? undefined;
|
|
68
|
+
baseHeaders.delete("content-length");
|
|
69
|
+
|
|
70
|
+
if (synthesized.contentType) {
|
|
71
|
+
baseHeaders.set("content-type", synthesized.contentType);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
logger.debug("Request stream already consumed; using parsed req.body to rebuild request.");
|
|
75
|
+
} else {
|
|
76
|
+
logger.warn("Request stream consumed with no available body; sending empty payload.");
|
|
77
|
+
requestBody = undefined;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const buildRequest = (body: BodyInit | null | undefined, headers: Headers, duplex: boolean) =>
|
|
82
|
+
new Request(url, {
|
|
83
|
+
method: req.method,
|
|
84
|
+
headers,
|
|
85
|
+
body,
|
|
86
|
+
duplex: duplex ? "half" : undefined,
|
|
87
|
+
} as RequestInit);
|
|
88
|
+
|
|
89
|
+
let response: Response;
|
|
90
|
+
try {
|
|
91
|
+
response = await honoApp.fetch(buildRequest(requestBody, baseHeaders, useDuplex));
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (isDisturbedOrLockedError(error) && hasBody) {
|
|
94
|
+
logger.warn(
|
|
95
|
+
"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.",
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
const fallbackHeaders = new Headers(baseHeaders);
|
|
99
|
+
let fallbackBody: BodyInit | null | undefined;
|
|
100
|
+
|
|
101
|
+
if (parsedBody !== undefined) {
|
|
102
|
+
const synthesized = synthesizeBodyFromParsedBody(parsedBody, fallbackHeaders);
|
|
103
|
+
fallbackBody = synthesized.body ?? undefined;
|
|
104
|
+
fallbackHeaders.delete("content-length");
|
|
105
|
+
|
|
106
|
+
if (synthesized.contentType) {
|
|
107
|
+
fallbackHeaders.set("content-type", synthesized.contentType);
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
fallbackBody = undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
response = await honoApp.fetch(buildRequest(fallbackBody, fallbackHeaders, false));
|
|
114
|
+
} else {
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
res.statusCode = response.status;
|
|
120
|
+
response.headers.forEach((value, key) => {
|
|
121
|
+
res.setHeader(key, value);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
if (response.body) {
|
|
125
|
+
readableStreamToNodeStream(response.body).pipe(res);
|
|
126
|
+
} else {
|
|
127
|
+
res.end();
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
return function (
|
|
132
|
+
reqOrRequest: IncomingMessage | Request,
|
|
133
|
+
res?: ServerResponse,
|
|
134
|
+
): Promise<void> | Promise<Response> | Response {
|
|
135
|
+
if (reqOrRequest instanceof Request) {
|
|
136
|
+
return honoApp.fetch(reqOrRequest as Request);
|
|
137
|
+
}
|
|
138
|
+
if (!res) {
|
|
139
|
+
throw new TypeError("ServerResponse is required for Node HTTP requests");
|
|
140
|
+
}
|
|
141
|
+
return handle(reqOrRequest as IncomingMessage, res);
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { IncomingMessage } from "http";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
|
+
|
|
4
|
+
export type IncomingWithBody = IncomingMessage & { body?: unknown; complete?: boolean };
|
|
5
|
+
|
|
6
|
+
export function readableStreamToNodeStream(webStream: ReadableStream): Readable {
|
|
7
|
+
const reader = webStream.getReader();
|
|
8
|
+
|
|
9
|
+
return new Readable({
|
|
10
|
+
async read() {
|
|
11
|
+
try {
|
|
12
|
+
const { done, value } = await reader.read();
|
|
13
|
+
if (done) {
|
|
14
|
+
this.push(null);
|
|
15
|
+
} else {
|
|
16
|
+
this.push(Buffer.from(value));
|
|
17
|
+
}
|
|
18
|
+
} catch (err) {
|
|
19
|
+
this.destroy(err as Error);
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function nodeStreamToReadableStream(nodeStream: Readable): ReadableStream<Uint8Array> {
|
|
26
|
+
return new ReadableStream({
|
|
27
|
+
start(controller) {
|
|
28
|
+
nodeStream.on("data", (chunk) => {
|
|
29
|
+
controller.enqueue(chunk instanceof Buffer ? new Uint8Array(chunk) : chunk);
|
|
30
|
+
});
|
|
31
|
+
nodeStream.on("end", () => {
|
|
32
|
+
controller.close();
|
|
33
|
+
});
|
|
34
|
+
nodeStream.on("error", (err) => {
|
|
35
|
+
controller.error(err);
|
|
36
|
+
});
|
|
37
|
+
},
|
|
38
|
+
cancel() {
|
|
39
|
+
nodeStream.destroy();
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function getFullUrl(req: IncomingMessage): string {
|
|
45
|
+
// Use req.url (path relative to mount point) for Hono routing to work correctly.
|
|
46
|
+
// Express sets req.url to the path after the mount point (e.g., "/" when mounted at "/copilotkit").
|
|
47
|
+
// Pure Node HTTP sets req.url to the full path.
|
|
48
|
+
const path = req.url || "/";
|
|
49
|
+
const host =
|
|
50
|
+
(req.headers["x-forwarded-host"] as string) || (req.headers.host as string) || "localhost";
|
|
51
|
+
const proto =
|
|
52
|
+
(req.headers["x-forwarded-proto"] as string) ||
|
|
53
|
+
((req.socket as any).encrypted ? "https" : "http");
|
|
54
|
+
|
|
55
|
+
return `${proto}://${host}${path}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function toHeaders(rawHeaders: IncomingMessage["headers"]): Headers {
|
|
59
|
+
const headers = new Headers();
|
|
60
|
+
|
|
61
|
+
for (const [key, value] of Object.entries(rawHeaders)) {
|
|
62
|
+
if (value === undefined) continue;
|
|
63
|
+
|
|
64
|
+
if (Array.isArray(value)) {
|
|
65
|
+
value.forEach((entry) => headers.append(key, entry));
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
headers.append(key, value);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return headers;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function isStreamConsumed(req: IncomingWithBody): boolean {
|
|
76
|
+
const readableState = (req as any)._readableState;
|
|
77
|
+
|
|
78
|
+
return Boolean(
|
|
79
|
+
req.readableEnded || req.complete || readableState?.ended || readableState?.endEmitted,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function synthesizeBodyFromParsedBody(
|
|
84
|
+
parsedBody: unknown,
|
|
85
|
+
headers: Headers,
|
|
86
|
+
): { body: BodyInit | null; contentType?: string } {
|
|
87
|
+
if (parsedBody === null || parsedBody === undefined) {
|
|
88
|
+
return { body: null };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (parsedBody instanceof Buffer || parsedBody instanceof Uint8Array) {
|
|
92
|
+
return { body: parsedBody };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (typeof parsedBody === "string") {
|
|
96
|
+
return { body: parsedBody, contentType: headers.get("content-type") ?? "text/plain" };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
body: JSON.stringify(parsedBody),
|
|
101
|
+
contentType: "application/json",
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function isDisturbedOrLockedError(error: unknown): boolean {
|
|
106
|
+
return (
|
|
107
|
+
error instanceof TypeError &&
|
|
108
|
+
typeof error.message === "string" &&
|
|
109
|
+
(error.message.includes("disturbed") || error.message.includes("locked"))
|
|
110
|
+
);
|
|
111
|
+
}
|