@copilotkit/sdk-js 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.
@@ -0,0 +1,207 @@
1
+ import { CopilotKitMisuseError } from "@copilotkit/shared";
2
+ import {
3
+ copilotKitInterrupt,
4
+ convertActionToDynamicStructuredTool,
5
+ convertActionsToDynamicStructuredTools,
6
+ copilotkitCustomizeConfig,
7
+ copilotkitEmitMessage,
8
+ copilotkitEmitState,
9
+ copilotkitEmitToolCall,
10
+ copilotkitExit,
11
+ } from "../langgraph";
12
+
13
+ describe("SDK-JS Error Handling", () => {
14
+ describe("copilotKitInterrupt", () => {
15
+ it("should throw CopilotKitMisuseError when neither message nor action provided", () => {
16
+ expect(() => {
17
+ copilotKitInterrupt({});
18
+ }).toThrow(CopilotKitMisuseError);
19
+
20
+ expect(() => {
21
+ copilotKitInterrupt({});
22
+ }).toThrow(
23
+ "Either message or action (and optional arguments) must be provided for copilotKitInterrupt",
24
+ );
25
+ });
26
+
27
+ it("should throw CopilotKitMisuseError when action is not a string", () => {
28
+ expect(() => {
29
+ copilotKitInterrupt({ action: 123 as any });
30
+ }).toThrow(CopilotKitMisuseError);
31
+
32
+ expect(() => {
33
+ copilotKitInterrupt({ action: 123 as any });
34
+ }).toThrow("Action must be a string when provided to copilotKitInterrupt");
35
+ });
36
+
37
+ it("should throw CopilotKitMisuseError when message is not a string", () => {
38
+ expect(() => {
39
+ copilotKitInterrupt({ message: 123 as any });
40
+ }).toThrow(CopilotKitMisuseError);
41
+
42
+ expect(() => {
43
+ copilotKitInterrupt({ message: 123 as any });
44
+ }).toThrow("Message must be a string when provided to copilotKitInterrupt");
45
+ });
46
+
47
+ it("should throw CopilotKitMisuseError when args is not an object", () => {
48
+ expect(() => {
49
+ copilotKitInterrupt({ action: "test", args: "invalid" as any });
50
+ }).toThrow(CopilotKitMisuseError);
51
+
52
+ expect(() => {
53
+ copilotKitInterrupt({ action: "test", args: "invalid" as any });
54
+ }).toThrow("Args must be an object when provided to copilotKitInterrupt");
55
+ });
56
+ });
57
+
58
+ describe("convertActionToDynamicStructuredTool", () => {
59
+ it("should throw CopilotKitMisuseError when actionInput is null/undefined", () => {
60
+ expect(() => {
61
+ convertActionToDynamicStructuredTool(null);
62
+ }).toThrow(CopilotKitMisuseError);
63
+
64
+ expect(() => {
65
+ convertActionToDynamicStructuredTool(null);
66
+ }).toThrow("Action input is required but was not provided");
67
+ });
68
+
69
+ it("should throw CopilotKitMisuseError when name is missing", () => {
70
+ expect(() => {
71
+ convertActionToDynamicStructuredTool({ description: "test" });
72
+ }).toThrow(CopilotKitMisuseError);
73
+
74
+ expect(() => {
75
+ convertActionToDynamicStructuredTool({ description: "test" });
76
+ }).toThrow("Action must have a valid 'name' property of type string");
77
+ });
78
+
79
+ it("should throw CopilotKitMisuseError when description is missing", () => {
80
+ expect(() => {
81
+ convertActionToDynamicStructuredTool({ name: "test" });
82
+ }).toThrow(CopilotKitMisuseError);
83
+
84
+ expect(() => {
85
+ convertActionToDynamicStructuredTool({ name: "test" });
86
+ }).toThrow("Action 'test' must have a valid 'description' property of type string");
87
+ });
88
+
89
+ it("should throw CopilotKitMisuseError when parameters is missing", () => {
90
+ expect(() => {
91
+ convertActionToDynamicStructuredTool({ name: "test", description: "test desc" });
92
+ }).toThrow(CopilotKitMisuseError);
93
+
94
+ expect(() => {
95
+ convertActionToDynamicStructuredTool({ name: "test", description: "test desc" });
96
+ }).toThrow("Action 'test' must have a 'parameters' property");
97
+ });
98
+ });
99
+
100
+ describe("convertActionsToDynamicStructuredTools", () => {
101
+ it("should throw CopilotKitMisuseError when actions is not an array", () => {
102
+ expect(() => {
103
+ convertActionsToDynamicStructuredTools("not an array" as any);
104
+ }).toThrow(CopilotKitMisuseError);
105
+
106
+ expect(() => {
107
+ convertActionsToDynamicStructuredTools("not an array" as any);
108
+ }).toThrow("Actions must be an array");
109
+ });
110
+ });
111
+
112
+ describe("copilotkitCustomizeConfig", () => {
113
+ it("should throw CopilotKitMisuseError when baseConfig is not an object", () => {
114
+ expect(() => {
115
+ copilotkitCustomizeConfig("invalid" as any);
116
+ }).toThrow(CopilotKitMisuseError);
117
+
118
+ expect(() => {
119
+ copilotkitCustomizeConfig("invalid" as any);
120
+ }).toThrow("baseConfig must be an object or null/undefined");
121
+ });
122
+
123
+ it("should throw CopilotKitMisuseError when options is not an object", () => {
124
+ expect(() => {
125
+ copilotkitCustomizeConfig({}, "invalid" as any);
126
+ }).toThrow(CopilotKitMisuseError);
127
+
128
+ expect(() => {
129
+ copilotkitCustomizeConfig({}, "invalid" as any);
130
+ }).toThrow("options must be an object when provided");
131
+ });
132
+
133
+ it("should throw CopilotKitMisuseError when emitIntermediateState is not an array", () => {
134
+ expect(() => {
135
+ copilotkitCustomizeConfig({}, { emitIntermediateState: "invalid" as any });
136
+ }).toThrow(CopilotKitMisuseError);
137
+
138
+ expect(() => {
139
+ copilotkitCustomizeConfig({}, { emitIntermediateState: "invalid" as any });
140
+ }).toThrow("emitIntermediateState must be an array when provided");
141
+ });
142
+
143
+ it("should throw CopilotKitMisuseError when emitIntermediateState item is invalid", () => {
144
+ expect(() => {
145
+ copilotkitCustomizeConfig({}, { emitIntermediateState: [{ invalidKey: "value" }] as any });
146
+ }).toThrow(CopilotKitMisuseError);
147
+
148
+ expect(() => {
149
+ copilotkitCustomizeConfig({}, { emitIntermediateState: [{ invalidKey: "value" }] as any });
150
+ }).toThrow("emitIntermediateState[0] must have a valid 'stateKey' string property");
151
+ });
152
+ });
153
+
154
+ describe("emit functions", () => {
155
+ const mockConfig = { metadata: {} };
156
+
157
+ it("should throw CopilotKitMisuseError when config is missing for copilotkitExit", async () => {
158
+ await expect(copilotkitExit(null as any)).rejects.toThrow(CopilotKitMisuseError);
159
+ await expect(copilotkitExit(null as any)).rejects.toThrow(
160
+ "LangGraph configuration is required for copilotkitExit",
161
+ );
162
+ });
163
+
164
+ it("should throw CopilotKitMisuseError when config is missing for copilotkitEmitState", async () => {
165
+ await expect(copilotkitEmitState(null as any, {})).rejects.toThrow(CopilotKitMisuseError);
166
+ await expect(copilotkitEmitState(null as any, {})).rejects.toThrow(
167
+ "LangGraph configuration is required for copilotkitEmitState",
168
+ );
169
+ });
170
+
171
+ it("should throw CopilotKitMisuseError when state is undefined for copilotkitEmitState", async () => {
172
+ await expect(copilotkitEmitState(mockConfig, undefined)).rejects.toThrow(
173
+ CopilotKitMisuseError,
174
+ );
175
+ await expect(copilotkitEmitState(mockConfig, undefined)).rejects.toThrow(
176
+ "State is required for copilotkitEmitState",
177
+ );
178
+ });
179
+
180
+ it("should throw CopilotKitMisuseError when message is invalid for copilotkitEmitMessage", async () => {
181
+ await expect(copilotkitEmitMessage(mockConfig, "" as any)).rejects.toThrow(
182
+ CopilotKitMisuseError,
183
+ );
184
+ await expect(copilotkitEmitMessage(mockConfig, "" as any)).rejects.toThrow(
185
+ "Message must be a non-empty string for copilotkitEmitMessage",
186
+ );
187
+ });
188
+
189
+ it("should throw CopilotKitMisuseError when tool name is invalid for copilotkitEmitToolCall", async () => {
190
+ await expect(copilotkitEmitToolCall(mockConfig, "", {})).rejects.toThrow(
191
+ CopilotKitMisuseError,
192
+ );
193
+ await expect(copilotkitEmitToolCall(mockConfig, "", {})).rejects.toThrow(
194
+ "Tool name must be a non-empty string for copilotkitEmitToolCall",
195
+ );
196
+ });
197
+
198
+ it("should throw CopilotKitMisuseError when args is undefined for copilotkitEmitToolCall", async () => {
199
+ await expect(copilotkitEmitToolCall(mockConfig, "testTool", undefined)).rejects.toThrow(
200
+ CopilotKitMisuseError,
201
+ );
202
+ await expect(copilotkitEmitToolCall(mockConfig, "testTool", undefined)).rejects.toThrow(
203
+ "Tool arguments are required for copilotkitEmitToolCall",
204
+ );
205
+ });
206
+ });
207
+ });
package/src/index.ts ADDED
File without changes
@@ -0,0 +1,17 @@
1
+ console.warn(
2
+ "Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.",
3
+ );
4
+
5
+ export {
6
+ CopilotKitPropertiesAnnotation,
7
+ CopilotKitStateAnnotation,
8
+ type CopilotKitState,
9
+ type CopilotKitProperties,
10
+ copilotkitCustomizeConfig as copilotKitCustomizeConfig,
11
+ copilotkitExit as copilotKitExit,
12
+ copilotkitEmitState as copilotKitEmitState,
13
+ copilotkitEmitMessage as copilotKitEmitMessage,
14
+ copilotkitEmitToolCall as copilotKitEmitToolCall,
15
+ convertActionToDynamicStructuredTool,
16
+ convertActionsToDynamicStructuredTools,
17
+ } from "./langgraph";
@@ -0,0 +1,3 @@
1
+ export * from "./types";
2
+ export * from "./utils";
3
+ export * from "./middleware";
@@ -0,0 +1,146 @@
1
+ import { createMiddleware, AIMessage } from "langchain";
2
+ import type { InteropZodObject } from "@langchain/core/utils/types";
3
+ import * as z from "zod";
4
+
5
+ /**
6
+ * CopilotKit Middleware for LangGraph agents.
7
+ *
8
+ * Enables:
9
+ * - Dynamic frontend tools from state.tools
10
+ * - Context provided from CopilotKit useCopilotReadable
11
+ *
12
+ * Works with any agent (prebuilt or custom).
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { createAgent } from "langchain";
17
+ * import { copilotkitMiddleware } from "@copilotkit/sdk-js/langgraph";
18
+ *
19
+ * const agent = createAgent({
20
+ * model: "gpt-4o",
21
+ * tools: [backendTool],
22
+ * middleware: [copilotkitMiddleware],
23
+ * });
24
+ * ```
25
+ */
26
+ const copilotKitStateSchema = z.object({
27
+ copilotkit: z
28
+ .object({
29
+ actions: z.array(z.any()),
30
+ context: z.any().optional(),
31
+ interceptedToolCalls: z.array(z.any()).optional(),
32
+ originalAIMessageId: z.string().optional(),
33
+ })
34
+ .optional(),
35
+ });
36
+
37
+
38
+ const middlewareInput = {
39
+ name: "CopilotKitMiddleware",
40
+
41
+ stateSchema: copilotKitStateSchema as unknown as InteropZodObject,
42
+
43
+ // Inject frontend tools before model call
44
+ wrapModelCall: async (request, handler) => {
45
+ const frontendTools = request.state["copilotkit"]?.actions ?? [];
46
+
47
+ if (frontendTools.length === 0) {
48
+ return handler(request);
49
+ }
50
+
51
+ const existingTools = request.tools || [];
52
+ const mergedTools = [...existingTools, ...frontendTools];
53
+
54
+ return handler({
55
+ ...request,
56
+ tools: mergedTools,
57
+ });
58
+ },
59
+
60
+ // Restore frontend tool calls to AIMessage before agent exits
61
+ afterAgent: (state) => {
62
+ const interceptedToolCalls = state["copilotkit"]?.interceptedToolCalls;
63
+ const originalMessageId = state["copilotkit"]?.originalAIMessageId;
64
+
65
+ if (!interceptedToolCalls?.length || !originalMessageId) {
66
+ return;
67
+ }
68
+
69
+ let messageFound = false;
70
+ const updatedMessages = state.messages.map((msg: any) => {
71
+ if (AIMessage.isInstance(msg) && msg.id === originalMessageId) {
72
+ messageFound = true;
73
+ const existingToolCalls = msg.tool_calls || [];
74
+ return new AIMessage({
75
+ content: msg.content,
76
+ tool_calls: [...existingToolCalls, ...interceptedToolCalls],
77
+ id: msg.id,
78
+ });
79
+ }
80
+ return msg;
81
+ });
82
+
83
+ // Only clear intercepted state if we successfully restored the tool calls
84
+ if (!messageFound) {
85
+ console.warn(
86
+ `CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`,
87
+ );
88
+ return;
89
+ }
90
+
91
+ return {
92
+ messages: updatedMessages,
93
+ copilotkit: {
94
+ ...(state["copilotkit"] ?? {}),
95
+ interceptedToolCalls: undefined,
96
+ originalAIMessageId: undefined,
97
+ },
98
+ };
99
+ },
100
+
101
+ // Intercept frontend tool calls after model returns, before ToolNode executes
102
+ afterModel: (state) => {
103
+ const frontendTools = state["copilotkit"]?.actions ?? [];
104
+ if (frontendTools.length === 0) return;
105
+
106
+ const frontendToolNames = new Set(frontendTools.map((t: any) => t.function?.name || t.name));
107
+
108
+ const lastMessage = state.messages[state.messages.length - 1];
109
+ if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls?.length) {
110
+ return;
111
+ }
112
+
113
+ const backendToolCalls: any[] = [];
114
+ const frontendToolCalls: any[] = [];
115
+
116
+ for (const call of lastMessage.tool_calls) {
117
+ if (frontendToolNames.has(call.name)) {
118
+ frontendToolCalls.push(call);
119
+ } else {
120
+ backendToolCalls.push(call);
121
+ }
122
+ }
123
+
124
+ if (frontendToolCalls.length === 0) return;
125
+
126
+ const updatedAIMessage = new AIMessage({
127
+ content: lastMessage.content,
128
+ tool_calls: backendToolCalls,
129
+ id: lastMessage.id,
130
+ });
131
+
132
+ return {
133
+ messages: [...state.messages.slice(0, -1), updatedAIMessage],
134
+ copilotkit: {
135
+ ...(state["copilotkit"] ?? {}),
136
+ interceptedToolCalls: frontendToolCalls,
137
+ originalAIMessageId: lastMessage.id,
138
+ },
139
+ };
140
+ },
141
+ } as any;
142
+ const createCopilotKitMiddleware = () => {
143
+ return createMiddleware(middlewareInput);
144
+ };
145
+
146
+ export const copilotkitMiddleware = createCopilotKitMiddleware();
@@ -0,0 +1,29 @@
1
+ import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
2
+
3
+ export const CopilotKitPropertiesAnnotation = Annotation.Root({
4
+ actions: Annotation<any[]>,
5
+ context: Annotation<{ description: string; value: string }[]>,
6
+ interceptedToolCalls: Annotation<any[]>,
7
+ originalAIMessageId: Annotation<string>,
8
+ });
9
+
10
+ export const CopilotKitStateAnnotation = Annotation.Root({
11
+ copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,
12
+ ...MessagesAnnotation.spec,
13
+ });
14
+
15
+ export interface IntermediateStateConfig {
16
+ stateKey: string;
17
+ tool: string;
18
+ toolArgument?: string;
19
+ }
20
+
21
+ export interface OptionsConfig {
22
+ emitToolCalls?: boolean | string | string[];
23
+ emitMessages?: boolean;
24
+ emitAll?: boolean;
25
+ emitIntermediateState?: IntermediateStateConfig[];
26
+ }
27
+
28
+ export type CopilotKitState = typeof CopilotKitStateAnnotation.State;
29
+ export type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;