@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/dist/langgraph.js CHANGED
@@ -1,6 +1,8 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
2
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
4
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
7
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
8
  var __export = (target, all) => {
@@ -15,9 +17,17 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
- // src/langgraph.ts
30
+ // src/langgraph/index.ts
21
31
  var langgraph_exports = {};
22
32
  __export(langgraph_exports, {
23
33
  CopilotKitPropertiesAnnotation: () => CopilotKitPropertiesAnnotation,
@@ -29,22 +39,30 @@ __export(langgraph_exports, {
29
39
  copilotkitEmitMessage: () => copilotkitEmitMessage,
30
40
  copilotkitEmitState: () => copilotkitEmitState,
31
41
  copilotkitEmitToolCall: () => copilotkitEmitToolCall,
32
- copilotkitExit: () => copilotkitExit
42
+ copilotkitExit: () => copilotkitExit,
43
+ copilotkitMiddleware: () => copilotkitMiddleware
33
44
  });
34
45
  module.exports = __toCommonJS(langgraph_exports);
35
- var import_dispatch = require("@langchain/core/callbacks/dispatch");
36
- var import_shared = require("@copilotkit/shared");
46
+
47
+ // src/langgraph/types.ts
37
48
  var import_langgraph = require("@langchain/langgraph");
38
- var import_tools = require("@langchain/core/tools");
39
- var import_messages = require("@langchain/core/messages");
40
49
  var CopilotKitPropertiesAnnotation = import_langgraph.Annotation.Root({
41
50
  actions: import_langgraph.Annotation,
42
- context: import_langgraph.Annotation
51
+ context: import_langgraph.Annotation,
52
+ interceptedToolCalls: import_langgraph.Annotation,
53
+ originalAIMessageId: import_langgraph.Annotation
43
54
  });
44
55
  var CopilotKitStateAnnotation = import_langgraph.Annotation.Root({
45
56
  copilotkit: import_langgraph.Annotation,
46
57
  ...import_langgraph.MessagesAnnotation.spec
47
58
  });
59
+
60
+ // src/langgraph/utils.ts
61
+ var import_dispatch = require("@langchain/core/callbacks/dispatch");
62
+ var import_shared = require("@copilotkit/shared");
63
+ var import_langgraph2 = require("@langchain/langgraph");
64
+ var import_tools = require("@langchain/core/tools");
65
+ var import_messages = require("@langchain/core/messages");
48
66
  function copilotkitCustomizeConfig(baseConfig, options) {
49
67
  if (baseConfig && typeof baseConfig !== "object") {
50
68
  throw new import_shared.CopilotKitMisuseError({
@@ -308,7 +326,7 @@ function copilotKitInterrupt({ message, action, args }) {
308
326
  args: args ?? {}
309
327
  };
310
328
  }
311
- const response = (0, import_langgraph.interrupt)({
329
+ const response = (0, import_langgraph2.interrupt)({
312
330
  __copilotkit_interrupt_value__: interruptValues,
313
331
  __copilotkit_messages__: [
314
332
  interruptMessage
@@ -326,6 +344,122 @@ function copilotKitInterrupt({ message, action, args }) {
326
344
  }
327
345
  }
328
346
  __name(copilotKitInterrupt, "copilotKitInterrupt");
347
+
348
+ // src/langgraph/middleware.ts
349
+ var import_langchain = require("langchain");
350
+ var z = __toESM(require("zod"));
351
+ var copilotKitStateSchema = z.object({
352
+ copilotkit: z.object({
353
+ actions: z.array(z.any()),
354
+ context: z.any().optional(),
355
+ interceptedToolCalls: z.array(z.any()).optional(),
356
+ originalAIMessageId: z.string().optional()
357
+ }).optional()
358
+ });
359
+ var middlewareInput = {
360
+ name: "CopilotKitMiddleware",
361
+ stateSchema: copilotKitStateSchema,
362
+ // Inject frontend tools before model call
363
+ wrapModelCall: async (request, handler) => {
364
+ var _a;
365
+ const frontendTools = ((_a = request.state["copilotkit"]) == null ? void 0 : _a.actions) ?? [];
366
+ if (frontendTools.length === 0) {
367
+ return handler(request);
368
+ }
369
+ const existingTools = request.tools || [];
370
+ const mergedTools = [
371
+ ...existingTools,
372
+ ...frontendTools
373
+ ];
374
+ return handler({
375
+ ...request,
376
+ tools: mergedTools
377
+ });
378
+ },
379
+ // Restore frontend tool calls to AIMessage before agent exits
380
+ afterAgent: (state) => {
381
+ var _a, _b;
382
+ const interceptedToolCalls = (_a = state["copilotkit"]) == null ? void 0 : _a.interceptedToolCalls;
383
+ const originalMessageId = (_b = state["copilotkit"]) == null ? void 0 : _b.originalAIMessageId;
384
+ if (!(interceptedToolCalls == null ? void 0 : interceptedToolCalls.length) || !originalMessageId) {
385
+ return;
386
+ }
387
+ let messageFound = false;
388
+ const updatedMessages = state.messages.map((msg) => {
389
+ if (import_langchain.AIMessage.isInstance(msg) && msg.id === originalMessageId) {
390
+ messageFound = true;
391
+ const existingToolCalls = msg.tool_calls || [];
392
+ return new import_langchain.AIMessage({
393
+ content: msg.content,
394
+ tool_calls: [
395
+ ...existingToolCalls,
396
+ ...interceptedToolCalls
397
+ ],
398
+ id: msg.id
399
+ });
400
+ }
401
+ return msg;
402
+ });
403
+ if (!messageFound) {
404
+ console.warn(`CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`);
405
+ return;
406
+ }
407
+ return {
408
+ messages: updatedMessages,
409
+ copilotkit: {
410
+ ...state["copilotkit"] ?? {},
411
+ interceptedToolCalls: void 0,
412
+ originalAIMessageId: void 0
413
+ }
414
+ };
415
+ },
416
+ // Intercept frontend tool calls after model returns, before ToolNode executes
417
+ afterModel: (state) => {
418
+ var _a, _b;
419
+ const frontendTools = ((_a = state["copilotkit"]) == null ? void 0 : _a.actions) ?? [];
420
+ if (frontendTools.length === 0)
421
+ return;
422
+ const frontendToolNames = new Set(frontendTools.map((t) => {
423
+ var _a2;
424
+ return ((_a2 = t.function) == null ? void 0 : _a2.name) || t.name;
425
+ }));
426
+ const lastMessage = state.messages[state.messages.length - 1];
427
+ if (!import_langchain.AIMessage.isInstance(lastMessage) || !((_b = lastMessage.tool_calls) == null ? void 0 : _b.length)) {
428
+ return;
429
+ }
430
+ const backendToolCalls = [];
431
+ const frontendToolCalls = [];
432
+ for (const call of lastMessage.tool_calls) {
433
+ if (frontendToolNames.has(call.name)) {
434
+ frontendToolCalls.push(call);
435
+ } else {
436
+ backendToolCalls.push(call);
437
+ }
438
+ }
439
+ if (frontendToolCalls.length === 0)
440
+ return;
441
+ const updatedAIMessage = new import_langchain.AIMessage({
442
+ content: lastMessage.content,
443
+ tool_calls: backendToolCalls,
444
+ id: lastMessage.id
445
+ });
446
+ return {
447
+ messages: [
448
+ ...state.messages.slice(0, -1),
449
+ updatedAIMessage
450
+ ],
451
+ copilotkit: {
452
+ ...state["copilotkit"] ?? {},
453
+ interceptedToolCalls: frontendToolCalls,
454
+ originalAIMessageId: lastMessage.id
455
+ }
456
+ };
457
+ }
458
+ };
459
+ var createCopilotKitMiddleware = /* @__PURE__ */ __name(() => {
460
+ return (0, import_langchain.createMiddleware)(middlewareInput);
461
+ }, "createCopilotKitMiddleware");
462
+ var copilotkitMiddleware = createCopilotKitMiddleware();
329
463
  // Annotate the CommonJS export names for ESM import in node:
330
464
  0 && (module.exports = {
331
465
  CopilotKitPropertiesAnnotation,
@@ -337,6 +471,7 @@ __name(copilotKitInterrupt, "copilotKitInterrupt");
337
471
  copilotkitEmitMessage,
338
472
  copilotkitEmitState,
339
473
  copilotkitEmitToolCall,
340
- copilotkitExit
474
+ copilotkitExit,
475
+ copilotkitMiddleware
341
476
  });
342
477
  //# sourceMappingURL=langgraph.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/langgraph.ts"],"sourcesContent":["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}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+BAA+BmB,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;IAC1F,CAAA;EACF;AACF;AArEgB2B;","names":["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","copilotKitInterrupt","interruptValues","interruptMessage","answer","AIMessage","content","toolId","tool_calls","response","interrupt","__copilotkit_interrupt_value__","__copilotkit_messages__","length","messages"]}
1
+ {"version":3,"sources":["../src/langgraph/index.ts","../src/langgraph/types.ts","../src/langgraph/utils.ts","../src/langgraph/middleware.ts"],"sourcesContent":["export * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./middleware\";\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","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;;;;;;;;;;;;;;;;;ACAA,uBAA+C;AAExC,IAAMA,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,C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AAZW,mBAAwB1B,SAAQ;AACzE;IACF;AAEA,UAAM2B,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,2BAAU;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,aAAOC,mCAAiB3C,eAAAA;AAC1B,GAFmC;AAI5B,IAAM4C,uBAAuBF,2BAAAA;","names":["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","copilotKitInterrupt","interruptValues","interruptMessage","answer","AIMessage","content","toolId","tool_calls","response","interrupt","__copilotkit_interrupt_value__","__copilotkit_messages__","length","messages","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"]}
@@ -8,8 +8,9 @@ import {
8
8
  copilotkitEmitMessage,
9
9
  copilotkitEmitState,
10
10
  copilotkitEmitToolCall,
11
- copilotkitExit
12
- } from "./chunk-RPSUO5FS.mjs";
11
+ copilotkitExit,
12
+ copilotkitMiddleware
13
+ } from "./chunk-5AVAJKYU.mjs";
13
14
  export {
14
15
  CopilotKitPropertiesAnnotation,
15
16
  CopilotKitStateAnnotation,
@@ -20,6 +21,7 @@ export {
20
21
  copilotkitEmitMessage,
21
22
  copilotkitEmitState,
22
23
  copilotkitEmitToolCall,
23
- copilotkitExit
24
+ copilotkitExit,
25
+ copilotkitMiddleware
24
26
  };
25
27
  //# sourceMappingURL=langgraph.mjs.map
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "publishConfig": {
10
10
  "access": "public"
11
11
  },
12
- "version": "1.50.1",
12
+ "version": "1.51.0-next.1",
13
13
  "sideEffects": false,
14
14
  "main": "./dist/index.js",
15
15
  "module": "./dist/index.mjs",
@@ -33,7 +33,8 @@
33
33
  "types": "./dist/index.d.ts",
34
34
  "license": "MIT",
35
35
  "devDependencies": {
36
- "@langchain/langgraph": "^0.4.5",
36
+ "@langchain/core": "^1.1.8",
37
+ "@langchain/langgraph": "^1.0.7",
37
38
  "@swc/core": "1.5.28",
38
39
  "@types/express": "^4.17.21",
39
40
  "@types/jest": "^29.5.4",
@@ -41,24 +42,24 @@
41
42
  "@whatwg-node/server": "^0.9.34",
42
43
  "eslint": "^8.56.0",
43
44
  "jest": "^29.6.4",
45
+ "langchain": "^1.2.3",
44
46
  "nodemon": "^3.1.3",
45
47
  "ts-jest": "^29.1.1",
46
48
  "ts-node": "^10.9.2",
47
49
  "tsup": "^6.7.0",
48
50
  "typescript": "^5.2.3",
51
+ "@copilotkit/shared": "1.51.0-next.1",
49
52
  "eslint-config-custom": "1.4.6",
50
53
  "tsconfig": "1.4.6"
51
54
  },
52
- "dependencies": {
53
- "@copilotkit/shared": "1.50.1"
54
- },
55
55
  "peerDependencies": {
56
56
  "@langchain/community": "^0.0.53",
57
57
  "@langchain/core": ">=0.4.0 <2.0.0",
58
58
  "@langchain/langgraph": ">=0.4.0 <2.0.0",
59
- "langchain": "^0.3.3",
59
+ "langchain": ">=1.0.0",
60
60
  "typescript": "^5.2.3",
61
- "zod": "^3.23.3 || ^3.24.0 || ^3.25.0"
61
+ "zod": "^3.23.3 || ^3.24.0 || ^3.25.0",
62
+ "@copilotkit/shared": "1.51.0-next.1"
62
63
  },
63
64
  "keywords": [
64
65
  "copilotkit",
@@ -0,0 +1,3 @@
1
+ export * from "./types";
2
+ export * from "./utils";
3
+ export * from "./middleware";
@@ -0,0 +1,146 @@
1
+ import { createMiddleware, AIMessage } from "langchain";
2
+ import type { InteropZodObject } from "@langchain/core/utils/types";
3
+ import * as z from "zod";
4
+
5
+ /**
6
+ * CopilotKit Middleware for LangGraph agents.
7
+ *
8
+ * Enables:
9
+ * - Dynamic frontend tools from state.tools
10
+ * - Context provided from CopilotKit useCopilotReadable
11
+ *
12
+ * Works with any agent (prebuilt or custom).
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { createAgent } from "langchain";
17
+ * import { copilotkitMiddleware } from "@copilotkit/sdk-js/langgraph";
18
+ *
19
+ * const agent = createAgent({
20
+ * model: "gpt-4o",
21
+ * tools: [backendTool],
22
+ * middleware: [copilotkitMiddleware],
23
+ * });
24
+ * ```
25
+ */
26
+ const copilotKitStateSchema = z.object({
27
+ copilotkit: z
28
+ .object({
29
+ actions: z.array(z.any()),
30
+ context: z.any().optional(),
31
+ interceptedToolCalls: z.array(z.any()).optional(),
32
+ originalAIMessageId: z.string().optional(),
33
+ })
34
+ .optional(),
35
+ });
36
+
37
+
38
+ const middlewareInput = {
39
+ name: "CopilotKitMiddleware",
40
+
41
+ stateSchema: copilotKitStateSchema as unknown as InteropZodObject,
42
+
43
+ // Inject frontend tools before model call
44
+ wrapModelCall: async (request, handler) => {
45
+ const frontendTools = request.state["copilotkit"]?.actions ?? [];
46
+
47
+ if (frontendTools.length === 0) {
48
+ return handler(request);
49
+ }
50
+
51
+ const existingTools = request.tools || [];
52
+ const mergedTools = [...existingTools, ...frontendTools];
53
+
54
+ return handler({
55
+ ...request,
56
+ tools: mergedTools,
57
+ });
58
+ },
59
+
60
+ // Restore frontend tool calls to AIMessage before agent exits
61
+ afterAgent: (state) => {
62
+ const interceptedToolCalls = state["copilotkit"]?.interceptedToolCalls;
63
+ const originalMessageId = state["copilotkit"]?.originalAIMessageId;
64
+
65
+ if (!interceptedToolCalls?.length || !originalMessageId) {
66
+ return;
67
+ }
68
+
69
+ let messageFound = false;
70
+ const updatedMessages = state.messages.map((msg: any) => {
71
+ if (AIMessage.isInstance(msg) && msg.id === originalMessageId) {
72
+ messageFound = true;
73
+ const existingToolCalls = msg.tool_calls || [];
74
+ return new AIMessage({
75
+ content: msg.content,
76
+ tool_calls: [...existingToolCalls, ...interceptedToolCalls],
77
+ id: msg.id,
78
+ });
79
+ }
80
+ return msg;
81
+ });
82
+
83
+ // Only clear intercepted state if we successfully restored the tool calls
84
+ if (!messageFound) {
85
+ console.warn(
86
+ `CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`,
87
+ );
88
+ return;
89
+ }
90
+
91
+ return {
92
+ messages: updatedMessages,
93
+ copilotkit: {
94
+ ...(state["copilotkit"] ?? {}),
95
+ interceptedToolCalls: undefined,
96
+ originalAIMessageId: undefined,
97
+ },
98
+ };
99
+ },
100
+
101
+ // Intercept frontend tool calls after model returns, before ToolNode executes
102
+ afterModel: (state) => {
103
+ const frontendTools = state["copilotkit"]?.actions ?? [];
104
+ if (frontendTools.length === 0) return;
105
+
106
+ const frontendToolNames = new Set(frontendTools.map((t: any) => t.function?.name || t.name));
107
+
108
+ const lastMessage = state.messages[state.messages.length - 1];
109
+ if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls?.length) {
110
+ return;
111
+ }
112
+
113
+ const backendToolCalls: any[] = [];
114
+ const frontendToolCalls: any[] = [];
115
+
116
+ for (const call of lastMessage.tool_calls) {
117
+ if (frontendToolNames.has(call.name)) {
118
+ frontendToolCalls.push(call);
119
+ } else {
120
+ backendToolCalls.push(call);
121
+ }
122
+ }
123
+
124
+ if (frontendToolCalls.length === 0) return;
125
+
126
+ const updatedAIMessage = new AIMessage({
127
+ content: lastMessage.content,
128
+ tool_calls: backendToolCalls,
129
+ id: lastMessage.id,
130
+ });
131
+
132
+ return {
133
+ messages: [...state.messages.slice(0, -1), updatedAIMessage],
134
+ copilotkit: {
135
+ ...(state["copilotkit"] ?? {}),
136
+ interceptedToolCalls: frontendToolCalls,
137
+ originalAIMessageId: lastMessage.id,
138
+ },
139
+ };
140
+ },
141
+ } as any;
142
+ const createCopilotKitMiddleware = () => {
143
+ return createMiddleware(middlewareInput);
144
+ };
145
+
146
+ export const copilotkitMiddleware = createCopilotKitMiddleware();
@@ -0,0 +1,29 @@
1
+ import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
2
+
3
+ export const CopilotKitPropertiesAnnotation = Annotation.Root({
4
+ actions: Annotation<any[]>,
5
+ context: Annotation<{ description: string; value: string }[]>,
6
+ interceptedToolCalls: Annotation<any[]>,
7
+ originalAIMessageId: Annotation<string>,
8
+ });
9
+
10
+ export const CopilotKitStateAnnotation = Annotation.Root({
11
+ copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,
12
+ ...MessagesAnnotation.spec,
13
+ });
14
+
15
+ export interface IntermediateStateConfig {
16
+ stateKey: string;
17
+ tool: string;
18
+ toolArgument?: string;
19
+ }
20
+
21
+ export interface OptionsConfig {
22
+ emitToolCalls?: boolean | string | string[];
23
+ emitMessages?: boolean;
24
+ emitAll?: boolean;
25
+ emitIntermediateState?: IntermediateStateConfig[];
26
+ }
27
+
28
+ export type CopilotKitState = typeof CopilotKitStateAnnotation.State;
29
+ export type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;
@@ -1,35 +1,10 @@
1
1
  import { RunnableConfig } from "@langchain/core/runnables";
2
2
  import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
3
3
  import { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from "@copilotkit/shared";
4
- import { Annotation, MessagesAnnotation, interrupt } from "@langchain/langgraph";
4
+ import { interrupt } from "@langchain/langgraph";
5
5
  import { DynamicStructuredTool } from "@langchain/core/tools";
6
6
  import { AIMessage } from "@langchain/core/messages";
7
-
8
- interface IntermediateStateConfig {
9
- stateKey: string;
10
- tool: string;
11
- toolArgument?: string;
12
- }
13
-
14
- interface OptionsConfig {
15
- emitToolCalls?: boolean | string | string[];
16
- emitMessages?: boolean;
17
- emitAll?: boolean;
18
- emitIntermediateState?: IntermediateStateConfig[];
19
- }
20
-
21
- export const CopilotKitPropertiesAnnotation = Annotation.Root({
22
- actions: Annotation<any[]>,
23
- context: Annotation<{ description: string; value: string }[]>,
24
- });
25
-
26
- export const CopilotKitStateAnnotation = Annotation.Root({
27
- copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,
28
- ...MessagesAnnotation.spec,
29
- });
30
-
31
- export type CopilotKitState = typeof CopilotKitStateAnnotation.State;
32
- export type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;
7
+ import { OptionsConfig } from "./types";
33
8
 
34
9
  /**
35
10
  * Customize the LangGraph configuration for use in CopilotKit.
package/tsup.config.ts CHANGED
@@ -5,11 +5,11 @@ export default defineConfig((options: Options) => ({
5
5
  entry: {
6
6
  index: "src/index.ts",
7
7
  langchain: "src/langchain.ts",
8
- langgraph: "src/langgraph.ts",
8
+ langgraph: "src/langgraph/index.ts",
9
9
  },
10
10
  format: ["esm", "cjs"],
11
11
  dts: {
12
- entry: ["src/index.ts", "src/langchain.ts", "src/langgraph.ts"],
12
+ entry: ["src/index.ts", "src/langchain.ts", "src/langgraph/index.ts"],
13
13
  },
14
14
  minify: false,
15
15
  external: [],