@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) Atai Barkai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # CopilotKit - SDK JS
2
+
3
+
4
+ <img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />
5
+
6
+ <br>
7
+ <div align="center" style="display:flex;justify-content:center;gap:16px;height:20px;margin: 0;">
8
+ <a href="https://www.npmjs.com/package/@copilotkit/react-core" target="_blank">
9
+ <img src="https://img.shields.io/npm/v/%40copilotkit%2Fsdk-js?logo=npm&logoColor=%23FFFFFF&label=Version&color=%236963ff" alt="NPM">
10
+ </a>
11
+ <a href="https://github.com/copilotkit/copilotkit/blob/main/LICENSE" target="_blank">
12
+ <img src="https://img.shields.io/github/license/copilotkit/copilotkit?color=%236963ff&label=License" alt="MIT">
13
+ </a>
14
+ <a href="https://discord.gg/6dffbvGU3D" target="_blank">
15
+ <img src="https://img.shields.io/discord/1122926057641742418?logo=discord&logoColor=%23FFFFFF&label=Discord&color=%236963ff" alt="Discord">
16
+ </a>
17
+ </div>
18
+ <br/>
19
+ <div align="center">
20
+ <a href="https://www.producthunt.com/posts/copilotkit" target="_blank">
21
+ <img src="https://api.producthunt.com/widgets/embed-image/v1/top-post-badge.svg?post_id=428778&theme=light&period=daily">
22
+ </a>
23
+ </div>
24
+
25
+ ## ✨ Why CopilotKit?
26
+
27
+ - Minutes to integrate - Get started quickly with our CLI
28
+ - Framework agnostic - Works with React, Next.js, AGUI and more
29
+ - Production-ready UI - Use customizable components or build with headless UI
30
+ - Built-in security - Prompt injection protection
31
+ - Open source - Full transparency and community-driven
32
+
33
+ <img src="https://github.com/user-attachments/assets/6cb425f8-ffcb-49d2-9bbb-87cab5995b78" alt="class-support-ecosystem" style="border-radius: 12px; border: 2px solid #d6d4fa;">
34
+
35
+ ## 🧑‍💻 Real life use cases
36
+
37
+ <span>Deploy deeply-integrated AI assistants & agents that work alongside your users inside your applications.</span>
38
+
39
+ <img src="https://github.com/user-attachments/assets/3b810240-e9f8-43ae-acec-31a58095e223" alt="headless-ui" style="border-radius: 12px; border: 2px solid #d6d4fa;">
40
+
41
+ ## 🏆 Featured Examples
42
+
43
+ <p align="center">
44
+ <a href="https://www.copilotkit.ai/examples/form-filling-copilot">
45
+ <img src="https://github.com/user-attachments/assets/874da84a-67ff-47fa-a6b4-cbc3c65eb704" width="300" style="border-radius: 16px;" />
46
+ </a>
47
+ <a href="https://www.copilotkit.ai/examples/state-machine-copilot">
48
+ <img src="https://github.com/user-attachments/assets/0b5e45b3-2704-4678-82dc-2f3e1c58e2dd" width="300" style="border-radius: 16px;" />
49
+ </a>
50
+ <a href="https://www.copilotkit.ai/examples/chat-with-your-data">
51
+ <img src="https://github.com/user-attachments/assets/0fed66be-a4c2-4093-8eab-75c0b27a62f6" width="300" style="border-radius: 16px;" />
52
+ </a>
53
+ </p>
54
+
55
+ ## Documentation
56
+
57
+ To get started with CopilotKit, please check out the [documentation](https://docs.copilotkit.ai).
@@ -0,0 +1,434 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/langgraph/types.ts
5
+ import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
6
+ var CopilotKitPropertiesAnnotation = Annotation.Root({
7
+ actions: Annotation,
8
+ context: Annotation,
9
+ interceptedToolCalls: Annotation,
10
+ originalAIMessageId: Annotation
11
+ });
12
+ var CopilotKitStateAnnotation = Annotation.Root({
13
+ copilotkit: Annotation,
14
+ ...MessagesAnnotation.spec
15
+ });
16
+
17
+ // src/langgraph/utils.ts
18
+ import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
19
+ import { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from "@copilotkit/shared";
20
+ import { interrupt } from "@langchain/langgraph";
21
+ import { DynamicStructuredTool } from "@langchain/core/tools";
22
+ import { AIMessage } from "@langchain/core/messages";
23
+ function copilotkitCustomizeConfig(baseConfig, options) {
24
+ if (baseConfig && typeof baseConfig !== "object") {
25
+ throw new CopilotKitMisuseError({
26
+ message: "baseConfig must be an object or null/undefined"
27
+ });
28
+ }
29
+ if (options && typeof options !== "object") {
30
+ throw new CopilotKitMisuseError({
31
+ message: "options must be an object when provided"
32
+ });
33
+ }
34
+ if (options == null ? void 0 : options.emitIntermediateState) {
35
+ if (!Array.isArray(options.emitIntermediateState)) {
36
+ throw new CopilotKitMisuseError({
37
+ message: "emitIntermediateState must be an array when provided"
38
+ });
39
+ }
40
+ options.emitIntermediateState.forEach((state, index) => {
41
+ if (!state || typeof state !== "object") {
42
+ throw new CopilotKitMisuseError({
43
+ message: `emitIntermediateState[${index}] must be an object`
44
+ });
45
+ }
46
+ if (!state.stateKey || typeof state.stateKey !== "string") {
47
+ throw new CopilotKitMisuseError({
48
+ message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`
49
+ });
50
+ }
51
+ if (!state.tool || typeof state.tool !== "string") {
52
+ throw new CopilotKitMisuseError({
53
+ message: `emitIntermediateState[${index}] must have a valid 'tool' string property`
54
+ });
55
+ }
56
+ if (state.toolArgument && typeof state.toolArgument !== "string") {
57
+ throw new CopilotKitMisuseError({
58
+ message: `emitIntermediateState[${index}].toolArgument must be a string when provided`
59
+ });
60
+ }
61
+ });
62
+ }
63
+ try {
64
+ const metadata = (baseConfig == null ? void 0 : baseConfig.metadata) || {};
65
+ if (options == null ? void 0 : options.emitAll) {
66
+ metadata["copilotkit:emit-tool-calls"] = true;
67
+ metadata["copilotkit:emit-messages"] = true;
68
+ } else {
69
+ if ((options == null ? void 0 : options.emitToolCalls) !== void 0) {
70
+ metadata["copilotkit:emit-tool-calls"] = options.emitToolCalls;
71
+ }
72
+ if ((options == null ? void 0 : options.emitMessages) !== void 0) {
73
+ metadata["copilotkit:emit-messages"] = options.emitMessages;
74
+ }
75
+ }
76
+ if (options == null ? void 0 : options.emitIntermediateState) {
77
+ const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({
78
+ tool: state.tool,
79
+ tool_argument: state.toolArgument,
80
+ state_key: state.stateKey
81
+ }));
82
+ metadata["copilotkit:emit-intermediate-state"] = snakeCaseIntermediateState;
83
+ }
84
+ baseConfig = baseConfig || {};
85
+ return {
86
+ ...baseConfig,
87
+ metadata
88
+ };
89
+ } catch (error) {
90
+ throw new CopilotKitMisuseError({
91
+ message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`
92
+ });
93
+ }
94
+ }
95
+ __name(copilotkitCustomizeConfig, "copilotkitCustomizeConfig");
96
+ async function copilotkitExit(config) {
97
+ if (!config) {
98
+ throw new CopilotKitMisuseError({
99
+ message: "LangGraph configuration is required for copilotkitExit"
100
+ });
101
+ }
102
+ try {
103
+ await dispatchCustomEvent("copilotkit_exit", {}, config);
104
+ } catch (error) {
105
+ throw new CopilotKitMisuseError({
106
+ message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`
107
+ });
108
+ }
109
+ }
110
+ __name(copilotkitExit, "copilotkitExit");
111
+ async function copilotkitEmitState(config, state) {
112
+ if (!config) {
113
+ throw new CopilotKitMisuseError({
114
+ message: "LangGraph configuration is required for copilotkitEmitState"
115
+ });
116
+ }
117
+ if (state === void 0) {
118
+ throw new CopilotKitMisuseError({
119
+ message: "State is required for copilotkitEmitState"
120
+ });
121
+ }
122
+ try {
123
+ await dispatchCustomEvent("copilotkit_manually_emit_intermediate_state", state, config);
124
+ } catch (error) {
125
+ throw new CopilotKitMisuseError({
126
+ message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`
127
+ });
128
+ }
129
+ }
130
+ __name(copilotkitEmitState, "copilotkitEmitState");
131
+ async function copilotkitEmitMessage(config, message) {
132
+ if (!config) {
133
+ throw new CopilotKitMisuseError({
134
+ message: "LangGraph configuration is required for copilotkitEmitMessage"
135
+ });
136
+ }
137
+ if (!message || typeof message !== "string") {
138
+ throw new CopilotKitMisuseError({
139
+ message: "Message must be a non-empty string for copilotkitEmitMessage"
140
+ });
141
+ }
142
+ try {
143
+ await dispatchCustomEvent("copilotkit_manually_emit_message", {
144
+ message,
145
+ message_id: randomId(),
146
+ role: "assistant"
147
+ }, config);
148
+ } catch (error) {
149
+ throw new CopilotKitMisuseError({
150
+ message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`
151
+ });
152
+ }
153
+ }
154
+ __name(copilotkitEmitMessage, "copilotkitEmitMessage");
155
+ async function copilotkitEmitToolCall(config, name, args) {
156
+ if (!config) {
157
+ throw new CopilotKitMisuseError({
158
+ message: "LangGraph configuration is required for copilotkitEmitToolCall"
159
+ });
160
+ }
161
+ if (!name || typeof name !== "string") {
162
+ throw new CopilotKitMisuseError({
163
+ message: "Tool name must be a non-empty string for copilotkitEmitToolCall"
164
+ });
165
+ }
166
+ if (args === void 0) {
167
+ throw new CopilotKitMisuseError({
168
+ message: "Tool arguments are required for copilotkitEmitToolCall"
169
+ });
170
+ }
171
+ try {
172
+ await dispatchCustomEvent("copilotkit_manually_emit_tool_call", {
173
+ name,
174
+ args,
175
+ id: randomId()
176
+ }, config);
177
+ } catch (error) {
178
+ throw new CopilotKitMisuseError({
179
+ message: `Failed to emit tool call '${name}': ${error instanceof Error ? error.message : String(error)}`
180
+ });
181
+ }
182
+ }
183
+ __name(copilotkitEmitToolCall, "copilotkitEmitToolCall");
184
+ function convertActionToDynamicStructuredTool(actionInput) {
185
+ if (!actionInput) {
186
+ throw new CopilotKitMisuseError({
187
+ message: "Action input is required but was not provided"
188
+ });
189
+ }
190
+ if (!actionInput.name || typeof actionInput.name !== "string") {
191
+ throw new CopilotKitMisuseError({
192
+ message: "Action must have a valid 'name' property of type string"
193
+ });
194
+ }
195
+ if (actionInput.description == void 0 || actionInput.description == null || typeof actionInput.description !== "string") {
196
+ throw new CopilotKitMisuseError({
197
+ message: `Action '${actionInput.name}' must have a valid 'description' property of type string`
198
+ });
199
+ }
200
+ if (!actionInput.parameters) {
201
+ throw new CopilotKitMisuseError({
202
+ message: `Action '${actionInput.name}' must have a 'parameters' property`
203
+ });
204
+ }
205
+ try {
206
+ return new DynamicStructuredTool({
207
+ name: actionInput.name,
208
+ description: actionInput.description,
209
+ schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),
210
+ func: async () => {
211
+ return "";
212
+ }
213
+ });
214
+ } catch (error) {
215
+ throw new CopilotKitMisuseError({
216
+ message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`
217
+ });
218
+ }
219
+ }
220
+ __name(convertActionToDynamicStructuredTool, "convertActionToDynamicStructuredTool");
221
+ function convertActionsToDynamicStructuredTools(actions) {
222
+ if (!Array.isArray(actions)) {
223
+ throw new CopilotKitMisuseError({
224
+ message: "Actions must be an array"
225
+ });
226
+ }
227
+ return actions.map((action, index) => {
228
+ try {
229
+ return convertActionToDynamicStructuredTool(action.type === "function" ? action.function : action);
230
+ } catch (error) {
231
+ throw new CopilotKitMisuseError({
232
+ message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`
233
+ });
234
+ }
235
+ });
236
+ }
237
+ __name(convertActionsToDynamicStructuredTools, "convertActionsToDynamicStructuredTools");
238
+ function copilotKitInterrupt({ message, action, args }) {
239
+ if (!message && !action) {
240
+ throw new CopilotKitMisuseError({
241
+ message: "Either message or action (and optional arguments) must be provided for copilotKitInterrupt"
242
+ });
243
+ }
244
+ if (action && typeof action !== "string") {
245
+ throw new CopilotKitMisuseError({
246
+ message: "Action must be a string when provided to copilotKitInterrupt"
247
+ });
248
+ }
249
+ if (message && typeof message !== "string") {
250
+ throw new CopilotKitMisuseError({
251
+ message: "Message must be a string when provided to copilotKitInterrupt"
252
+ });
253
+ }
254
+ if (args && typeof args !== "object") {
255
+ throw new CopilotKitMisuseError({
256
+ message: "Args must be an object when provided to copilotKitInterrupt"
257
+ });
258
+ }
259
+ let interruptValues = null;
260
+ let interruptMessage = null;
261
+ let answer = null;
262
+ try {
263
+ if (message) {
264
+ interruptValues = message;
265
+ interruptMessage = new AIMessage({
266
+ content: message,
267
+ id: randomId()
268
+ });
269
+ } else {
270
+ const toolId = randomId();
271
+ interruptMessage = new AIMessage({
272
+ content: "",
273
+ tool_calls: [
274
+ {
275
+ id: toolId,
276
+ name: action,
277
+ args: args ?? {}
278
+ }
279
+ ]
280
+ });
281
+ interruptValues = {
282
+ action,
283
+ args: args ?? {}
284
+ };
285
+ }
286
+ const response = interrupt({
287
+ __copilotkit_interrupt_value__: interruptValues,
288
+ __copilotkit_messages__: [
289
+ interruptMessage
290
+ ]
291
+ });
292
+ answer = response[response.length - 1].content;
293
+ return {
294
+ answer,
295
+ messages: response
296
+ };
297
+ } catch (error) {
298
+ throw new CopilotKitMisuseError({
299
+ message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`
300
+ });
301
+ }
302
+ }
303
+ __name(copilotKitInterrupt, "copilotKitInterrupt");
304
+
305
+ // src/langgraph/middleware.ts
306
+ import { createMiddleware, AIMessage as AIMessage2 } from "langchain";
307
+ import * as z from "zod";
308
+ var copilotKitStateSchema = z.object({
309
+ copilotkit: z.object({
310
+ actions: z.array(z.any()),
311
+ context: z.any().optional(),
312
+ interceptedToolCalls: z.array(z.any()).optional(),
313
+ originalAIMessageId: z.string().optional()
314
+ }).optional()
315
+ });
316
+ var middlewareInput = {
317
+ name: "CopilotKitMiddleware",
318
+ stateSchema: copilotKitStateSchema,
319
+ // Inject frontend tools before model call
320
+ wrapModelCall: async (request, handler) => {
321
+ var _a;
322
+ const frontendTools = ((_a = request.state["copilotkit"]) == null ? void 0 : _a.actions) ?? [];
323
+ if (frontendTools.length === 0) {
324
+ return handler(request);
325
+ }
326
+ const existingTools = request.tools || [];
327
+ const mergedTools = [
328
+ ...existingTools,
329
+ ...frontendTools
330
+ ];
331
+ return handler({
332
+ ...request,
333
+ tools: mergedTools
334
+ });
335
+ },
336
+ // Restore frontend tool calls to AIMessage before agent exits
337
+ afterAgent: (state) => {
338
+ var _a, _b;
339
+ const interceptedToolCalls = (_a = state["copilotkit"]) == null ? void 0 : _a.interceptedToolCalls;
340
+ const originalMessageId = (_b = state["copilotkit"]) == null ? void 0 : _b.originalAIMessageId;
341
+ if (!(interceptedToolCalls == null ? void 0 : interceptedToolCalls.length) || !originalMessageId) {
342
+ return;
343
+ }
344
+ let messageFound = false;
345
+ const updatedMessages = state.messages.map((msg) => {
346
+ if (AIMessage2.isInstance(msg) && msg.id === originalMessageId) {
347
+ messageFound = true;
348
+ const existingToolCalls = msg.tool_calls || [];
349
+ return new AIMessage2({
350
+ content: msg.content,
351
+ tool_calls: [
352
+ ...existingToolCalls,
353
+ ...interceptedToolCalls
354
+ ],
355
+ id: msg.id
356
+ });
357
+ }
358
+ return msg;
359
+ });
360
+ if (!messageFound) {
361
+ console.warn(`CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`);
362
+ return;
363
+ }
364
+ return {
365
+ messages: updatedMessages,
366
+ copilotkit: {
367
+ ...state["copilotkit"] ?? {},
368
+ interceptedToolCalls: void 0,
369
+ originalAIMessageId: void 0
370
+ }
371
+ };
372
+ },
373
+ // Intercept frontend tool calls after model returns, before ToolNode executes
374
+ afterModel: (state) => {
375
+ var _a, _b;
376
+ const frontendTools = ((_a = state["copilotkit"]) == null ? void 0 : _a.actions) ?? [];
377
+ if (frontendTools.length === 0)
378
+ return;
379
+ const frontendToolNames = new Set(frontendTools.map((t) => {
380
+ var _a2;
381
+ return ((_a2 = t.function) == null ? void 0 : _a2.name) || t.name;
382
+ }));
383
+ const lastMessage = state.messages[state.messages.length - 1];
384
+ if (!AIMessage2.isInstance(lastMessage) || !((_b = lastMessage.tool_calls) == null ? void 0 : _b.length)) {
385
+ return;
386
+ }
387
+ const backendToolCalls = [];
388
+ const frontendToolCalls = [];
389
+ for (const call of lastMessage.tool_calls) {
390
+ if (frontendToolNames.has(call.name)) {
391
+ frontendToolCalls.push(call);
392
+ } else {
393
+ backendToolCalls.push(call);
394
+ }
395
+ }
396
+ if (frontendToolCalls.length === 0)
397
+ return;
398
+ const updatedAIMessage = new AIMessage2({
399
+ content: lastMessage.content,
400
+ tool_calls: backendToolCalls,
401
+ id: lastMessage.id
402
+ });
403
+ return {
404
+ messages: [
405
+ ...state.messages.slice(0, -1),
406
+ updatedAIMessage
407
+ ],
408
+ copilotkit: {
409
+ ...state["copilotkit"] ?? {},
410
+ interceptedToolCalls: frontendToolCalls,
411
+ originalAIMessageId: lastMessage.id
412
+ }
413
+ };
414
+ }
415
+ };
416
+ var createCopilotKitMiddleware = /* @__PURE__ */ __name(() => {
417
+ return createMiddleware(middlewareInput);
418
+ }, "createCopilotKitMiddleware");
419
+ var copilotkitMiddleware = createCopilotKitMiddleware();
420
+
421
+ export {
422
+ CopilotKitPropertiesAnnotation,
423
+ CopilotKitStateAnnotation,
424
+ copilotkitCustomizeConfig,
425
+ copilotkitExit,
426
+ copilotkitEmitState,
427
+ copilotkitEmitMessage,
428
+ copilotkitEmitToolCall,
429
+ convertActionToDynamicStructuredTool,
430
+ convertActionsToDynamicStructuredTools,
431
+ copilotKitInterrupt,
432
+ copilotkitMiddleware
433
+ };
434
+ //# sourceMappingURL=chunk-5AVAJKYU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/langgraph/types.ts","../src/langgraph/utils.ts","../src/langgraph/middleware.ts"],"sourcesContent":["import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n\nexport const CopilotKitPropertiesAnnotation = Annotation.Root({\n actions: Annotation<any[]>,\n context: Annotation<{ description: string; value: string }[]>,\n interceptedToolCalls: Annotation<any[]>,\n originalAIMessageId: Annotation<string>,\n});\n\nexport const CopilotKitStateAnnotation = Annotation.Root({\n copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,\n ...MessagesAnnotation.spec,\n});\n\nexport interface IntermediateStateConfig {\n stateKey: string;\n tool: string;\n toolArgument?: string;\n}\n\nexport interface OptionsConfig {\n emitToolCalls?: boolean | string | string[];\n emitMessages?: boolean;\n emitAll?: boolean;\n emitIntermediateState?: IntermediateStateConfig[];\n}\n\nexport type CopilotKitState = typeof CopilotKitStateAnnotation.State;\nexport type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;\n","import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\nimport { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from \"@copilotkit/shared\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { OptionsConfig } from \"./types\";\n\n/**\n * Customize the LangGraph configuration for use in CopilotKit.\n *\n * To the CopilotKit SDK, run:\n *\n * ```bash\n * npm install @copilotkit/sdk-js\n * ```\n *\n * ### Examples\n *\n * Disable emitting messages and tool calls:\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitMessages=false,\n * emitToolCalls=false\n * )\n * ```\n *\n * To emit a tool call as streaming LangGraph state, pass the destination key in state,\n * the tool name and optionally the tool argument. (If you don't pass the argument name,\n * all arguments are emitted under the state key.)\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitIntermediateState=[\n * {\n * \"stateKey\": \"steps\",\n * \"tool\": \"SearchTool\",\n * \"toolArgument\": \"steps\",\n * },\n * ],\n * )\n * ```\n */\nexport function copilotkitCustomizeConfig(\n /**\n * The LangChain/LangGraph configuration to customize.\n */\n baseConfig: RunnableConfig,\n /**\n * Configuration options:\n * - `emitMessages: boolean?`\n * Configure how messages are emitted. By default, all messages are emitted. Pass false to\n * disable emitting messages.\n * - `emitToolCalls: boolean | string | string[]?`\n * Configure how tool calls are emitted. By default, all tool calls are emitted. Pass false to\n * disable emitting tool calls. Pass a string or list of strings to emit only specific tool calls.\n * - `emitIntermediateState: IntermediateStateConfig[]?`\n * Lets you emit tool calls as streaming LangGraph state.\n */\n options?: OptionsConfig,\n): RunnableConfig {\n if (baseConfig && typeof baseConfig !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"baseConfig must be an object or null/undefined\",\n });\n }\n\n if (options && typeof options !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"options must be an object when provided\",\n });\n }\n\n // Validate emitIntermediateState structure\n if (options?.emitIntermediateState) {\n if (!Array.isArray(options.emitIntermediateState)) {\n throw new CopilotKitMisuseError({\n message: \"emitIntermediateState must be an array when provided\",\n });\n }\n\n options.emitIntermediateState.forEach((state, index) => {\n if (!state || typeof state !== \"object\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must be an object`,\n });\n }\n\n if (!state.stateKey || typeof state.stateKey !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`,\n });\n }\n\n if (!state.tool || typeof state.tool !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'tool' string property`,\n });\n }\n\n if (state.toolArgument && typeof state.toolArgument !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}].toolArgument must be a string when provided`,\n });\n }\n });\n }\n\n try {\n const metadata = baseConfig?.metadata || {};\n\n if (options?.emitAll) {\n metadata[\"copilotkit:emit-tool-calls\"] = true;\n metadata[\"copilotkit:emit-messages\"] = true;\n } else {\n if (options?.emitToolCalls !== undefined) {\n metadata[\"copilotkit:emit-tool-calls\"] = options.emitToolCalls;\n }\n if (options?.emitMessages !== undefined) {\n metadata[\"copilotkit:emit-messages\"] = options.emitMessages;\n }\n }\n\n if (options?.emitIntermediateState) {\n const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }));\n\n metadata[\"copilotkit:emit-intermediate-state\"] = snakeCaseIntermediateState;\n }\n\n baseConfig = baseConfig || {};\n\n return {\n ...baseConfig,\n metadata: metadata,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Exits the current agent after the run completes. Calling copilotkit_exit() will\n * not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after\n * the run completes.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitExit } from \"@copilotkit/sdk-js\";\n *\n * async function myNode(state: Any):\n * await copilotkitExit(config)\n * return state\n * ```\n */\nexport async function copilotkitExit(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitExit\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_exit\", {}, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Emits intermediate state to CopilotKit. Useful if you have a longer running node and you want to\n * update the user with the current state of the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitState } from \"@copilotkit/sdk-js\";\n *\n * for (let i = 0; i < 10; i++) {\n * await someLongRunningOperation(i);\n * await copilotkitEmitState(config, { progress: i });\n * }\n * ```\n */\nexport async function copilotkitEmitState(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The state to emit.\n */\n state: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitState\",\n });\n }\n\n if (state === undefined) {\n throw new CopilotKitMisuseError({\n message: \"State is required for copilotkitEmitState\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_manually_emit_intermediate_state\", state, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a message to CopilotKit. Useful in longer running nodes to update the user.\n * Important: You still need to return the messages from the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitMessage } from \"@copilotkit/sdk-js\";\n *\n * const message = \"Step 1 of 10 complete\";\n * await copilotkitEmitMessage(config, message);\n *\n * // Return the message from the node\n * return {\n * \"messages\": [AIMessage(content=message)]\n * }\n * ```\n */\nexport async function copilotkitEmitMessage(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The message to emit.\n */\n message: string,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitMessage\",\n });\n }\n\n if (!message || typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a non-empty string for copilotkitEmitMessage\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_message\",\n { message, message_id: randomId(), role: \"assistant\" },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a tool call to CopilotKit.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitToolCall } from \"@copilotkit/sdk-js\";\n *\n * await copilotkitEmitToolCall(config, name=\"SearchTool\", args={\"steps\": 10})\n * ```\n */\nexport async function copilotkitEmitToolCall(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The name of the tool to emit.\n */\n name: string,\n /**\n * The arguments to emit.\n */\n args: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitToolCall\",\n });\n }\n\n if (!name || typeof name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Tool name must be a non-empty string for copilotkitEmitToolCall\",\n });\n }\n\n if (args === undefined) {\n throw new CopilotKitMisuseError({\n message: \"Tool arguments are required for copilotkitEmitToolCall\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_tool_call\",\n { name, args, id: randomId() },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit tool call '${name}': ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n\nexport function convertActionToDynamicStructuredTool(actionInput: any): DynamicStructuredTool<any> {\n if (!actionInput) {\n throw new CopilotKitMisuseError({\n message: \"Action input is required but was not provided\",\n });\n }\n\n if (!actionInput.name || typeof actionInput.name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must have a valid 'name' property of type string\",\n });\n }\n\n if (\n actionInput.description == undefined ||\n actionInput.description == null ||\n typeof actionInput.description !== \"string\"\n ) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,\n });\n }\n\n if (!actionInput.parameters) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a 'parameters' property`,\n });\n }\n\n try {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),\n func: async () => {\n return \"\";\n },\n });\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Use this function to convert a list of actions you get from state\n * to a list of dynamic structured tools.\n *\n * ### Examples\n *\n * ```typescript\n * import { convertActionsToDynamicStructuredTools } from \"@copilotkit/sdk-js\";\n *\n * const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);\n * ```\n */\nexport function convertActionsToDynamicStructuredTools(\n /**\n * The list of actions to convert.\n */\n actions: any[],\n): DynamicStructuredTool<any>[] {\n if (!Array.isArray(actions)) {\n throw new CopilotKitMisuseError({\n message: \"Actions must be an array\",\n });\n }\n\n return actions.map((action, index) => {\n try {\n return convertActionToDynamicStructuredTool(\n action.type === \"function\" ? action.function : action,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n });\n}\n\nexport function copilotKitInterrupt({\n message,\n action,\n args,\n}: {\n message?: string;\n action?: string;\n args?: Record<string, any>;\n}) {\n if (!message && !action) {\n throw new CopilotKitMisuseError({\n message:\n \"Either message or action (and optional arguments) must be provided for copilotKitInterrupt\",\n });\n }\n\n if (action && typeof action !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (message && typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (args && typeof args !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"Args must be an object when provided to copilotKitInterrupt\",\n });\n }\n\n let interruptValues = null;\n let interruptMessage = null;\n let answer = null;\n\n try {\n if (message) {\n interruptValues = message;\n interruptMessage = new AIMessage({ content: message, id: randomId() });\n } else {\n const toolId = randomId();\n interruptMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolId, name: action, args: args ?? {} }],\n });\n interruptValues = {\n action,\n args: args ?? {},\n };\n }\n\n const response = interrupt({\n __copilotkit_interrupt_value__: interruptValues,\n __copilotkit_messages__: [interruptMessage],\n });\n answer = response[response.length - 1].content;\n\n return {\n answer,\n messages: response,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n","import { createMiddleware, AIMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport * as z from \"zod\";\n\n/**\n * CopilotKit Middleware for LangGraph agents.\n *\n * Enables:\n * - Dynamic frontend tools from state.tools\n * - Context provided from CopilotKit useCopilotReadable\n *\n * Works with any agent (prebuilt or custom).\n *\n * @example\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { copilotkitMiddleware } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const agent = createAgent({\n * model: \"gpt-4o\",\n * tools: [backendTool],\n * middleware: [copilotkitMiddleware],\n * });\n * ```\n */\nconst copilotKitStateSchema = z.object({\n copilotkit: z\n .object({\n actions: z.array(z.any()),\n context: z.any().optional(),\n interceptedToolCalls: z.array(z.any()).optional(),\n originalAIMessageId: z.string().optional(),\n })\n .optional(),\n});\n\n\nconst middlewareInput = {\n name: \"CopilotKitMiddleware\",\n\n stateSchema: copilotKitStateSchema as unknown as InteropZodObject,\n\n // Inject frontend tools before model call\n wrapModelCall: async (request, handler) => {\n const frontendTools = request.state[\"copilotkit\"]?.actions ?? [];\n\n if (frontendTools.length === 0) {\n return handler(request);\n }\n\n const existingTools = request.tools || [];\n const mergedTools = [...existingTools, ...frontendTools];\n\n return handler({\n ...request,\n tools: mergedTools,\n });\n },\n\n // Restore frontend tool calls to AIMessage before agent exits\n afterAgent: (state) => {\n const interceptedToolCalls = state[\"copilotkit\"]?.interceptedToolCalls;\n const originalMessageId = state[\"copilotkit\"]?.originalAIMessageId;\n\n if (!interceptedToolCalls?.length || !originalMessageId) {\n return;\n }\n\n let messageFound = false;\n const updatedMessages = state.messages.map((msg: any) => {\n if (AIMessage.isInstance(msg) && msg.id === originalMessageId) {\n messageFound = true;\n const existingToolCalls = msg.tool_calls || [];\n return new AIMessage({\n content: msg.content,\n tool_calls: [...existingToolCalls, ...interceptedToolCalls],\n id: msg.id,\n });\n }\n return msg;\n });\n\n // Only clear intercepted state if we successfully restored the tool calls\n if (!messageFound) {\n console.warn(\n `CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`,\n );\n return;\n }\n\n return {\n messages: updatedMessages,\n copilotkit: {\n ...(state[\"copilotkit\"] ?? {}),\n interceptedToolCalls: undefined,\n originalAIMessageId: undefined,\n },\n };\n },\n\n // Intercept frontend tool calls after model returns, before ToolNode executes\n afterModel: (state) => {\n const frontendTools = state[\"copilotkit\"]?.actions ?? [];\n if (frontendTools.length === 0) return;\n\n const frontendToolNames = new Set(frontendTools.map((t: any) => t.function?.name || t.name));\n\n const lastMessage = state.messages[state.messages.length - 1];\n if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls?.length) {\n return;\n }\n\n const backendToolCalls: any[] = [];\n const frontendToolCalls: any[] = [];\n\n for (const call of lastMessage.tool_calls) {\n if (frontendToolNames.has(call.name)) {\n frontendToolCalls.push(call);\n } else {\n backendToolCalls.push(call);\n }\n }\n\n if (frontendToolCalls.length === 0) return;\n\n const updatedAIMessage = new AIMessage({\n content: lastMessage.content,\n tool_calls: backendToolCalls,\n id: lastMessage.id,\n });\n\n return {\n messages: [...state.messages.slice(0, -1), updatedAIMessage],\n copilotkit: {\n ...(state[\"copilotkit\"] ?? {}),\n interceptedToolCalls: frontendToolCalls,\n originalAIMessageId: lastMessage.id,\n },\n };\n },\n} as any;\nconst createCopilotKitMiddleware = () => {\n return createMiddleware(middlewareInput);\n};\n\nexport const copilotkitMiddleware = createCopilotKitMiddleware();\n"],"mappings":";;;;AAAA,SAASA,YAAYC,0BAA0B;AAExC,IAAMC,iCAAiCF,WAAWG,KAAK;EAC5DC,SAASJ;EACTK,SAASL;EACTM,sBAAsBN;EACtBO,qBAAqBP;AACvB,CAAA;AAEO,IAAMQ,4BAA4BR,WAAWG,KAAK;EACvDM,YAAYT;EACZ,GAAGC,mBAAmBS;AACxB,CAAA;;;ACXA,SAASC,2BAA2B;AACpC,SAASC,8BAA8BC,UAAUC,6BAA6B;AAC9E,SAASC,iBAAiB;AAC1B,SAASC,6BAA6B;AACtC,SAASC,iBAAiB;AA6CnB,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,sBAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAAOA,YAAY,UAAU;AAC1C,UAAM,IAAIC,sBAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAGA,MAAIF,mCAASG,uBAAuB;AAClC,QAAI,CAACC,MAAMC,QAAQL,QAAQG,qBAAqB,GAAG;AACjD,YAAM,IAAIF,sBAAsB;QAC9BC,SAAS;MACX,CAAA;IACF;AAEAF,YAAQG,sBAAsBG,QAAQ,CAACC,OAAOC,UAAAA;AAC5C,UAAI,CAACD,SAAS,OAAOA,UAAU,UAAU;AACvC,cAAM,IAAIN,sBAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CAAA;MACF;AAEA,UAAI,CAACD,MAAME,YAAY,OAAOF,MAAME,aAAa,UAAU;AACzD,cAAM,IAAIR,sBAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CAAA;MACF;AAEA,UAAI,CAACD,MAAMG,QAAQ,OAAOH,MAAMG,SAAS,UAAU;AACjD,cAAM,IAAIT,sBAAsB;UAC9BC,SAAS,yBAAyBM;QACp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MACrBD,YAAYY;MACZd,IAAIa,YAAYb;IAClB,CAAA;AAEA,WAAO;MACLL,UAAU;WAAIT,MAAMS,SAASyB,MAAM,GAAG,EAAC;QAAID;;MAC3CjD,YAAY;QACV,GAAIgB,MAAM,YAAA,KAAiB,CAAC;QAC5BV,sBAAsBuC;QACtBtC,qBAAqBoC,YAAYb;MACnC;IACF;EACF;AACF;AACA,IAAMqB,6BAA6B,6BAAA;AACjC,SAAOC,iBAAiB3C,eAAAA;AAC1B,GAFmC;AAI5B,IAAM4C,uBAAuBF,2BAAAA;","names":["Annotation","MessagesAnnotation","CopilotKitPropertiesAnnotation","Root","actions","context","interceptedToolCalls","originalAIMessageId","CopilotKitStateAnnotation","copilotkit","spec","dispatchCustomEvent","convertJsonSchemaToZodSchema","randomId","CopilotKitMisuseError","interrupt","DynamicStructuredTool","AIMessage","copilotkitCustomizeConfig","baseConfig","options","CopilotKitMisuseError","message","emitIntermediateState","Array","isArray","forEach","state","index","stateKey","tool","toolArgument","metadata","emitAll","emitToolCalls","undefined","emitMessages","snakeCaseIntermediateState","map","tool_argument","state_key","error","Error","String","copilotkitExit","config","dispatchCustomEvent","copilotkitEmitState","copilotkitEmitMessage","message_id","randomId","role","copilotkitEmitToolCall","name","args","id","convertActionToDynamicStructuredTool","actionInput","description","parameters","DynamicStructuredTool","schema","convertJsonSchemaToZodSchema","func","convertActionsToDynamicStructuredTools","actions","action","type","function","copilotKitInterrupt","interruptValues","interruptMessage","answer","AIMessage","content","toolId","tool_calls","response","interrupt","__copilotkit_interrupt_value__","__copilotkit_messages__","length","messages","createMiddleware","AIMessage","z","copilotKitStateSchema","object","copilotkit","actions","array","any","context","optional","interceptedToolCalls","originalAIMessageId","string","middlewareInput","name","stateSchema","wrapModelCall","request","handler","frontendTools","state","length","existingTools","tools","mergedTools","afterAgent","originalMessageId","messageFound","updatedMessages","messages","map","msg","AIMessage","isInstance","id","existingToolCalls","tool_calls","content","console","warn","undefined","afterModel","frontendToolNames","Set","t","_a","function","lastMessage","backendToolCalls","frontendToolCalls","call","has","push","updatedAIMessage","slice","createCopilotKitMiddleware","createMiddleware","copilotkitMiddleware"]}
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}