@copilotkit/sdk-js 1.50.1 → 1.51.0-next.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @copilotkit/sdk-js
2
2
 
3
+ ## 1.51.0-next.1
4
+
5
+ ### Minor Changes
6
+
7
+ - ce14f8b: create copilotkit langgraph middleware
8
+
9
+ ### Patch Changes
10
+
11
+ - @copilotkit/shared@1.51.0-next.1
12
+
13
+ ## 1.50.2-next.0
14
+
15
+ ### Patch Changes
16
+
17
+ - @copilotkit/shared@1.50.2-next.0
18
+
3
19
  ## 1.50.1
4
20
 
5
21
  ### Patch Changes
@@ -1890,7 +1906,6 @@
1890
1906
  - e16d95e: New prerelease
1891
1907
  - 1721cbd: Add convertActionsToDynamicStructuredTools to sdk-js
1892
1908
  - CopilotKit Core:
1893
-
1894
1909
  - Improved error messages and overall logs
1895
1910
  - `useCopilotAction.renderAndAwait` renamed to `.renderAndAwaitForResponse` (backwards compatible, will be deprecated in the future)
1896
1911
  - Improved scrolling behavior. It is now possible to scroll up during LLM response generation
@@ -1898,7 +1913,6 @@
1898
1913
  - Updated interfaces for better developer ergonomics
1899
1914
 
1900
1915
  CoAgents:
1901
-
1902
1916
  - Renamed `remoteActions` to `remoteEndpoints` (backwards compatible, will be deprecated in the future)
1903
1917
  - Support for LangGraph Platform in Remote Endpoints
1904
1918
  - LangGraph JS Support for CoAgents (locally via `langgraph dev`, `langgraph up` or deployed to LangGraph Platform)
@@ -1906,7 +1920,6 @@
1906
1920
  - Enhanced state management and message handling
1907
1921
 
1908
1922
  CopilotKid Back-end SDK:
1909
-
1910
1923
  - Released a whole-new `@copilotkit/sdk-js` for building agents with LangGraph JS Support
1911
1924
 
1912
1925
  - 8d0144f: bump
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.
@@ -1,20 +1,25 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
3
 
4
- // src/langgraph.ts
5
- import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
6
- import { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from "@copilotkit/shared";
7
- import { Annotation, MessagesAnnotation, interrupt } from "@langchain/langgraph";
8
- import { DynamicStructuredTool } from "@langchain/core/tools";
9
- import { AIMessage } from "@langchain/core/messages";
4
+ // src/langgraph/types.ts
5
+ import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
10
6
  var CopilotKitPropertiesAnnotation = Annotation.Root({
11
7
  actions: Annotation,
12
- context: Annotation
8
+ context: Annotation,
9
+ interceptedToolCalls: Annotation,
10
+ originalAIMessageId: Annotation
13
11
  });
14
12
  var CopilotKitStateAnnotation = Annotation.Root({
15
13
  copilotkit: Annotation,
16
14
  ...MessagesAnnotation.spec
17
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";
18
23
  function copilotkitCustomizeConfig(baseConfig, options) {
19
24
  if (baseConfig && typeof baseConfig !== "object") {
20
25
  throw new CopilotKitMisuseError({
@@ -297,6 +302,122 @@ function copilotKitInterrupt({ message, action, args }) {
297
302
  }
298
303
  __name(copilotKitInterrupt, "copilotKitInterrupt");
299
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
+
300
421
  export {
301
422
  CopilotKitPropertiesAnnotation,
302
423
  CopilotKitStateAnnotation,
@@ -307,6 +428,7 @@ export {
307
428
  copilotkitEmitToolCall,
308
429
  convertActionToDynamicStructuredTool,
309
430
  convertActionsToDynamicStructuredTools,
310
- copilotKitInterrupt
431
+ copilotKitInterrupt,
432
+ copilotkitMiddleware
311
433
  };
312
- //# sourceMappingURL=chunk-RPSUO5FS.mjs.map
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,U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AM2B,mBAA0B,CAAA;AAChC,UAAMC,oBAA2B,CAAA;AAEjC,eAAWC,QAAQH,YAAYX,YAAY;AACzC,UAAIM,kBAAkBS,IAAID,KAAKpC,IAAI,GAAG;AACpCmC,0BAAkBG,KAAKF,IAAAA;MACzB,OAAO;AACLF,yBAAiBI,KAAKF,IAAAA;MACxB;IACF;AAEA,QAAID,kBAAkB5B,WAAW;AAAG;AAEpC,UAAMgC,mBAAmB,IAAIrB,WAAU;MACrCK,SAASU,YAAYV;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"]}
@@ -1,19 +1,9 @@
1
+ import * as langchain from 'langchain';
1
2
  import * as _langchain_core_messages from '@langchain/core/messages';
2
3
  import * as _langchain_langgraph from '@langchain/langgraph';
3
4
  import { RunnableConfig } from '@langchain/core/runnables';
4
5
  import { DynamicStructuredTool } from '@langchain/core/tools';
5
6
 
6
- interface IntermediateStateConfig {
7
- stateKey: string;
8
- tool: string;
9
- toolArgument?: string;
10
- }
11
- interface OptionsConfig {
12
- emitToolCalls?: boolean | string | string[];
13
- emitMessages?: boolean;
14
- emitAll?: boolean;
15
- emitIntermediateState?: IntermediateStateConfig[];
16
- }
17
7
  declare const CopilotKitPropertiesAnnotation: _langchain_langgraph.AnnotationRoot<{
18
8
  actions: {
19
9
  (): _langchain_langgraph.LastValue<any[]>;
@@ -40,9 +30,19 @@ declare const CopilotKitPropertiesAnnotation: _langchain_langgraph.AnnotationRoo
40
30
  }[]>;
41
31
  Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
42
32
  };
33
+ interceptedToolCalls: {
34
+ (): _langchain_langgraph.LastValue<any[]>;
35
+ (annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
36
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
37
+ };
38
+ originalAIMessageId: {
39
+ (): _langchain_langgraph.LastValue<string>;
40
+ (annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
41
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
42
+ };
43
43
  }>;
44
44
  declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
45
- messages: _langchain_langgraph.BinaryOperatorAggregate<_langchain_core_messages.BaseMessage[], _langchain_langgraph.Messages>;
45
+ messages: _langchain_langgraph.BinaryOperatorAggregate<langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>[], _langchain_langgraph.Messages>;
46
46
  copilotkit: {
47
47
  (): _langchain_langgraph.LastValue<_langchain_langgraph.StateType<{
48
48
  actions: {
@@ -70,6 +70,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
70
70
  }[]>;
71
71
  Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
72
72
  };
73
+ interceptedToolCalls: {
74
+ (): _langchain_langgraph.LastValue<any[]>;
75
+ (annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
76
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
77
+ };
78
+ originalAIMessageId: {
79
+ (): _langchain_langgraph.LastValue<string>;
80
+ (annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
81
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
82
+ };
73
83
  }>>;
74
84
  (annotation: _langchain_langgraph.SingleReducer<_langchain_langgraph.StateType<{
75
85
  actions: {
@@ -97,6 +107,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
97
107
  }[]>;
98
108
  Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
99
109
  };
110
+ interceptedToolCalls: {
111
+ (): _langchain_langgraph.LastValue<any[]>;
112
+ (annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
113
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
114
+ };
115
+ originalAIMessageId: {
116
+ (): _langchain_langgraph.LastValue<string>;
117
+ (annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
118
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
119
+ };
100
120
  }>, _langchain_langgraph.StateType<{
101
121
  actions: {
102
122
  (): _langchain_langgraph.LastValue<any[]>;
@@ -123,6 +143,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
123
143
  }[]>;
124
144
  Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
125
145
  };
146
+ interceptedToolCalls: {
147
+ (): _langchain_langgraph.LastValue<any[]>;
148
+ (annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
149
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
150
+ };
151
+ originalAIMessageId: {
152
+ (): _langchain_langgraph.LastValue<string>;
153
+ (annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
154
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
155
+ };
126
156
  }>>): _langchain_langgraph.BinaryOperatorAggregate<_langchain_langgraph.StateType<{
127
157
  actions: {
128
158
  (): _langchain_langgraph.LastValue<any[]>;
@@ -149,6 +179,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
149
179
  }[]>;
150
180
  Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
151
181
  };
182
+ interceptedToolCalls: {
183
+ (): _langchain_langgraph.LastValue<any[]>;
184
+ (annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
185
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
186
+ };
187
+ originalAIMessageId: {
188
+ (): _langchain_langgraph.LastValue<string>;
189
+ (annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
190
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
191
+ };
152
192
  }>, _langchain_langgraph.StateType<{
153
193
  actions: {
154
194
  (): _langchain_langgraph.LastValue<any[]>;
@@ -175,12 +215,34 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
175
215
  }[]>;
176
216
  Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
177
217
  };
218
+ interceptedToolCalls: {
219
+ (): _langchain_langgraph.LastValue<any[]>;
220
+ (annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
221
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
222
+ };
223
+ originalAIMessageId: {
224
+ (): _langchain_langgraph.LastValue<string>;
225
+ (annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
226
+ Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
227
+ };
178
228
  }>>;
179
229
  Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
180
230
  };
181
231
  }>;
232
+ interface IntermediateStateConfig {
233
+ stateKey: string;
234
+ tool: string;
235
+ toolArgument?: string;
236
+ }
237
+ interface OptionsConfig {
238
+ emitToolCalls?: boolean | string | string[];
239
+ emitMessages?: boolean;
240
+ emitAll?: boolean;
241
+ emitIntermediateState?: IntermediateStateConfig[];
242
+ }
182
243
  type CopilotKitState = typeof CopilotKitStateAnnotation.State;
183
244
  type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;
245
+
184
246
  /**
185
247
  * Customize the LangGraph configuration for use in CopilotKit.
186
248
  *
@@ -362,4 +424,4 @@ declare function copilotKitInterrupt({ message, action, args, }: {
362
424
  messages: any;
363
425
  };
364
426
 
365
- export { CopilotKitProperties, CopilotKitPropertiesAnnotation, CopilotKitState, CopilotKitStateAnnotation, convertActionToDynamicStructuredTool, convertActionsToDynamicStructuredTools, copilotKitInterrupt, copilotkitCustomizeConfig, copilotkitEmitMessage, copilotkitEmitState, copilotkitEmitToolCall, copilotkitExit };
427
+ export { CopilotKitPropertiesAnnotation as C, IntermediateStateConfig as I, OptionsConfig as O, CopilotKitStateAnnotation as a, CopilotKitState as b, CopilotKitProperties as c, copilotkitCustomizeConfig as d, copilotkitExit as e, copilotkitEmitState as f, copilotkitEmitMessage as g, copilotkitEmitToolCall as h, convertActionToDynamicStructuredTool as i, convertActionsToDynamicStructuredTools as j, copilotKitInterrupt as k };
@@ -1,4 +1,5 @@
1
- export { CopilotKitProperties, CopilotKitPropertiesAnnotation, CopilotKitState, CopilotKitStateAnnotation, convertActionToDynamicStructuredTool, convertActionsToDynamicStructuredTools, copilotkitCustomizeConfig as copilotKitCustomizeConfig, copilotkitEmitMessage as copilotKitEmitMessage, copilotkitEmitState as copilotKitEmitState, copilotkitEmitToolCall as copilotKitEmitToolCall, copilotkitExit as copilotKitExit } from './langgraph.js';
1
+ export { c as CopilotKitProperties, C as CopilotKitPropertiesAnnotation, b as CopilotKitState, a as CopilotKitStateAnnotation, i as convertActionToDynamicStructuredTool, j as convertActionsToDynamicStructuredTools, d as copilotKitCustomizeConfig, g as copilotKitEmitMessage, f as copilotKitEmitState, h as copilotKitEmitToolCall, e as copilotKitExit } from './langchain-db7cb6cb.js';
2
+ import 'langchain';
2
3
  import '@langchain/core/messages';
3
4
  import '@langchain/langgraph';
4
5
  import '@langchain/core/runnables';
package/dist/langchain.js CHANGED
@@ -32,20 +32,25 @@ __export(langchain_exports, {
32
32
  });
33
33
  module.exports = __toCommonJS(langchain_exports);
34
34
 
35
- // src/langgraph.ts
36
- var import_dispatch = require("@langchain/core/callbacks/dispatch");
37
- var import_shared = require("@copilotkit/shared");
35
+ // src/langgraph/types.ts
38
36
  var import_langgraph = require("@langchain/langgraph");
39
- var import_tools = require("@langchain/core/tools");
40
- var import_messages = require("@langchain/core/messages");
41
37
  var CopilotKitPropertiesAnnotation = import_langgraph.Annotation.Root({
42
38
  actions: import_langgraph.Annotation,
43
- context: import_langgraph.Annotation
39
+ context: import_langgraph.Annotation,
40
+ interceptedToolCalls: import_langgraph.Annotation,
41
+ originalAIMessageId: import_langgraph.Annotation
44
42
  });
45
43
  var CopilotKitStateAnnotation = import_langgraph.Annotation.Root({
46
44
  copilotkit: import_langgraph.Annotation,
47
45
  ...import_langgraph.MessagesAnnotation.spec
48
46
  });
47
+
48
+ // src/langgraph/utils.ts
49
+ var import_dispatch = require("@langchain/core/callbacks/dispatch");
50
+ var import_shared = require("@copilotkit/shared");
51
+ var import_langgraph2 = require("@langchain/langgraph");
52
+ var import_tools = require("@langchain/core/tools");
53
+ var import_messages = require("@langchain/core/messages");
49
54
  function copilotkitCustomizeConfig(baseConfig, options) {
50
55
  if (baseConfig && typeof baseConfig !== "object") {
51
56
  throw new import_shared.CopilotKitMisuseError({
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/langchain.ts","../src/langgraph.ts"],"sourcesContent":["console.warn(\n \"Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.\",\n);\n\nexport {\n CopilotKitPropertiesAnnotation,\n CopilotKitStateAnnotation,\n type CopilotKitState,\n type CopilotKitProperties,\n copilotkitCustomizeConfig as copilotKitCustomizeConfig,\n copilotkitExit as copilotKitExit,\n copilotkitEmitState as copilotKitEmitState,\n copilotkitEmitMessage as copilotKitEmitMessage,\n copilotkitEmitToolCall as copilotKitEmitToolCall,\n convertActionToDynamicStructuredTool,\n convertActionsToDynamicStructuredTools,\n} from \"./langgraph\";\n","import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\nimport { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from \"@copilotkit/shared\";\nimport { Annotation, MessagesAnnotation, interrupt } from \"@langchain/langgraph\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\ninterface IntermediateStateConfig {\n stateKey: string;\n tool: string;\n toolArgument?: string;\n}\n\ninterface OptionsConfig {\n emitToolCalls?: boolean | string | string[];\n emitMessages?: boolean;\n emitAll?: boolean;\n emitIntermediateState?: IntermediateStateConfig[];\n}\n\nexport const CopilotKitPropertiesAnnotation = Annotation.Root({\n actions: Annotation<any[]>,\n context: Annotation<{ description: string; value: string }[]>,\n});\n\nexport const CopilotKitStateAnnotation = Annotation.Root({\n copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,\n ...MessagesAnnotation.spec,\n});\n\nexport type CopilotKitState = typeof CopilotKitStateAnnotation.State;\nexport type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAAA;;;;;;;;;;;;;;;ACCA,sBAAoC;AACpC,oBAA8E;AAC9E,uBAA0D;AAC1D,mBAAsC;AACtC,sBAA0B;AAenB,IAAMC,iCAAiCC,4BAAWC,KAAK;EAC5DC,SAASF;EACTG,SAASH;AACX,CAAA;AAEO,IAAMI,4BAA4BJ,4BAAWC,KAAK;EACvDI,YAAYL;EACZ,GAAGM,oCAAmBC;AACxB,CAAA;AA+CO,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAAOA,YAAY,UAAU;AAC1C,UAAM,IAAIC,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAGA,MAAIF,mCAASG,uBAAuB;AAClC,QAAI,CAACC,MAAMC,QAAQL,QAAQG,qBAAqB,GAAG;AACjD,YAAM,IAAIF,oCAAsB;QAC9BC,SAAS;MACX,CAAA;IACF;AAEAF,YAAQG,sBAAsBG,QAAQ,CAACC,OAAOC,UAAAA;AAC5C,UAAI,CAACD,SAAS,OAAOA,UAAU,UAAU;AACvC,cAAM,IAAIN,oCAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CAAA;MACF;AAEA,UAAI,CAACD,MAAME,YAAY,OAAOF,MAAME,aAAa,UAAU;AACzD,cAAM,IAAIR,oC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;EACF;AACF;AA3CgBe;AAwDT,SAASQ,uCAIdpD,SAAc;AAEd,MAAI,CAACY,MAAMC,QAAQb,OAAAA,GAAU;AAC3B,UAAM,IAAIS,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,SAAOV,QAAQ0B,IAAI,CAAC2B,QAAQrC,UAAAA;AAC1B,QAAI;AACF,aAAO4B,qCACLS,OAAOC,SAAS,aAAaD,OAAOE,WAAWF,MAAAA;IAEnD,SAASxB,OAAP;AACA,YAAM,IAAIpB,oCAAsB;QAC9BC,SAAS,qCAAqCM,UAAUa,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;MAC1G,CAAA;IACF;EACF,CAAA;AACF;AAvBgBuB;;;ADrahBI,QAAQC,KACN,mJAAA;","names":["console","CopilotKitPropertiesAnnotation","Annotation","Root","actions","context","CopilotKitStateAnnotation","copilotkit","MessagesAnnotation","spec","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","action","type","function","console","warn"]}
1
+ {"version":3,"sources":["../src/langchain.ts","../src/langgraph/types.ts","../src/langgraph/utils.ts"],"sourcesContent":["console.warn(\n \"Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.\",\n);\n\nexport {\n CopilotKitPropertiesAnnotation,\n CopilotKitStateAnnotation,\n type CopilotKitState,\n type CopilotKitProperties,\n copilotkitCustomizeConfig as copilotKitCustomizeConfig,\n copilotkitExit as copilotKitExit,\n copilotkitEmitState as copilotKitEmitState,\n copilotkitEmitMessage as copilotKitEmitMessage,\n copilotkitEmitToolCall as copilotKitEmitToolCall,\n convertActionToDynamicStructuredTool,\n convertActionsToDynamicStructuredTools,\n} from \"./langgraph\";\n","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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAAA;;;;;;;;;;;;;;;ACAA,uBAA+C;AAExC,IAAMC,iCAAiCC,4BAAWC,KAAK;EAC5DC,SAASF;EACTG,SAASH;EACTI,sBAAsBJ;EACtBK,qBAAqBL;AACvB,CAAA;AAEO,IAAMM,4BAA4BN,4BAAWC,KAAK;EACvDM,YAAYP;EACZ,GAAGQ,oCAAmBC;AACxB,CAAA;;;ACXA,sBAAoC;AACpC,oBAA8E;AAC9E,IAAAC,oBAA0B;AAC1B,mBAAsC;AACtC,sBAA0B;AA6CnB,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAAOA,YAAY,UAAU;AAC1C,UAAM,IAAIC,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAGA,MAAIF,mCAASG,uBAAuB;AAClC,QAAI,CAACC,MAAMC,QAAQL,QAAQG,qBAAqB,GAAG;AACjD,YAAM,IAAIF,oCAAsB;QAC9BC,SAAS;MACX,CAAA;IACF;AAEAF,YAAQG,sBAAsBG,QAAQ,CAACC,OAAOC,UAAAA;AAC5C,UAAI,CAACD,SAAS,OAAOA,UAAU,UAAU;AACvC,cAAM,IAAIN,oCAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CAAA;MACF;AAEA,UAAI,CAACD,MAAME,YAAY,OAAOF,MAAME,aAAa,UAAU;AACzD,cAAM,IAAIR,oCAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CAAA;MACF;AAEA,UAAI,CAACD,MAAMG,QAAQ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AAQwC,OAAAA,GAAU;AAC3B,UAAM,IAAI5C,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,SAAO2C,QAAQ3B,IAAI,CAAC4B,QAAQtC,UAAAA;AAC1B,QAAI;AACF,aAAO4B,qCACLU,OAAOC,SAAS,aAAaD,OAAOE,WAAWF,MAAAA;IAEnD,SAASzB,OAAP;AACA,YAAM,IAAIpB,oCAAsB;QAC9BC,SAAS,qCAAqCM,UAAUa,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;MAC1G,CAAA;IACF;EACF,CAAA;AACF;AAvBgBuB;;;AF5YhBK,QAAQC,KACN,mJAAA;","names":["console","CopilotKitPropertiesAnnotation","Annotation","Root","actions","context","interceptedToolCalls","originalAIMessageId","CopilotKitStateAnnotation","copilotkit","MessagesAnnotation","spec","import_langgraph","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","console","warn"]}
@@ -8,7 +8,7 @@ import {
8
8
  copilotkitEmitState,
9
9
  copilotkitEmitToolCall,
10
10
  copilotkitExit
11
- } from "./chunk-RPSUO5FS.mjs";
11
+ } from "./chunk-5AVAJKYU.mjs";
12
12
 
13
13
  // src/langchain.ts
14
14
  console.warn("Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.");
@@ -0,0 +1,10 @@
1
+ export { c as CopilotKitProperties, C as CopilotKitPropertiesAnnotation, b as CopilotKitState, a as CopilotKitStateAnnotation, I as IntermediateStateConfig, O as OptionsConfig, i as convertActionToDynamicStructuredTool, j as convertActionsToDynamicStructuredTools, k as copilotKitInterrupt, d as copilotkitCustomizeConfig, g as copilotkitEmitMessage, f as copilotkitEmitState, h as copilotkitEmitToolCall, e as copilotkitExit } from '../langchain-db7cb6cb.js';
2
+ import * as langchain from 'langchain';
3
+ import * as _langchain_core_tools from '@langchain/core/tools';
4
+ import '@langchain/core/messages';
5
+ import '@langchain/langgraph';
6
+ import '@langchain/core/runnables';
7
+
8
+ declare const copilotkitMiddleware: langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[]>;
9
+
10
+ export { copilotkitMiddleware };