@copilotkit/sdk-js 1.51.4-next.1 → 1.51.4-next.3

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,18 @@
1
1
  # @copilotkit/sdk-js
2
2
 
3
+ ## 1.51.4-next.3
4
+
5
+ ### Patch Changes
6
+
7
+ - @copilotkit/shared@1.51.4-next.3
8
+
9
+ ## 1.51.4-next.2
10
+
11
+ ### Patch Changes
12
+
13
+ - c07362d: feat: add app context readables to prebuilt LG agent middleware
14
+ - @copilotkit/shared@1.51.4-next.2
15
+
3
16
  ## 1.51.4-next.1
4
17
 
5
18
  ### Patch Changes
@@ -303,8 +303,78 @@ function copilotKitInterrupt({ message, action, args }) {
303
303
  __name(copilotKitInterrupt, "copilotKitInterrupt");
304
304
 
305
305
  // src/langgraph/middleware.ts
306
- import { createMiddleware, AIMessage as AIMessage2 } from "langchain";
306
+ import { createMiddleware, AIMessage as AIMessage2, SystemMessage } from "langchain";
307
307
  import * as z from "zod";
308
+ var createAppContextBeforeAgent = /* @__PURE__ */ __name((state, runtime) => {
309
+ var _a, _b, _c;
310
+ const messages = state.messages;
311
+ if (!messages || messages.length === 0) {
312
+ return;
313
+ }
314
+ const appContext = ((_a = state["copilotkit"]) == null ? void 0 : _a.context) ?? (runtime == null ? void 0 : runtime.context);
315
+ const isEmptyContext = !appContext || typeof appContext === "string" && appContext.trim() === "" || typeof appContext === "object" && Object.keys(appContext).length === 0;
316
+ if (isEmptyContext) {
317
+ return;
318
+ }
319
+ const contextContent = typeof appContext === "string" ? appContext : JSON.stringify(appContext, null, 2);
320
+ const contextMessageContent = `App Context:
321
+ ${contextContent}`;
322
+ const contextMessagePrefix = "App Context:\n";
323
+ const getContentString = /* @__PURE__ */ __name((msg) => {
324
+ var _a2;
325
+ if (typeof msg.content === "string")
326
+ return msg.content;
327
+ if (Array.isArray(msg.content) && ((_a2 = msg.content[0]) == null ? void 0 : _a2.text))
328
+ return msg.content[0].text;
329
+ return null;
330
+ }, "getContentString");
331
+ let firstSystemIndex = -1;
332
+ for (let i = 0; i < messages.length; i++) {
333
+ const msg = messages[i];
334
+ const type = (_b = msg._getType) == null ? void 0 : _b.call(msg);
335
+ if (type === "system" || type === "developer") {
336
+ const content = getContentString(msg);
337
+ if (content == null ? void 0 : content.startsWith(contextMessagePrefix)) {
338
+ continue;
339
+ }
340
+ firstSystemIndex = i;
341
+ break;
342
+ }
343
+ }
344
+ let existingContextIndex = -1;
345
+ for (let i = 0; i < messages.length; i++) {
346
+ const msg = messages[i];
347
+ const type = (_c = msg._getType) == null ? void 0 : _c.call(msg);
348
+ if (type === "system" || type === "developer") {
349
+ const content = getContentString(msg);
350
+ if (content == null ? void 0 : content.startsWith(contextMessagePrefix)) {
351
+ existingContextIndex = i;
352
+ break;
353
+ }
354
+ }
355
+ }
356
+ const contextMessage = new SystemMessage({
357
+ content: contextMessageContent
358
+ });
359
+ let updatedMessages;
360
+ if (existingContextIndex !== -1) {
361
+ updatedMessages = [
362
+ ...messages
363
+ ];
364
+ updatedMessages[existingContextIndex] = contextMessage;
365
+ } else {
366
+ const insertIndex = firstSystemIndex !== -1 ? firstSystemIndex + 1 : 0;
367
+ updatedMessages = [
368
+ ...messages.slice(0, insertIndex),
369
+ contextMessage,
370
+ ...messages.slice(insertIndex)
371
+ ];
372
+ }
373
+ return {
374
+ ...state,
375
+ messages: updatedMessages
376
+ };
377
+ }, "createAppContextBeforeAgent");
308
378
  var copilotKitStateSchema = z.object({
309
379
  copilotkit: z.object({
310
380
  actions: z.array(z.any()),
@@ -333,6 +403,7 @@ var middlewareInput = {
333
403
  tools: mergedTools
334
404
  });
335
405
  },
406
+ beforeAgent: createAppContextBeforeAgent,
336
407
  // Restore frontend tool calls to AIMessage before agent exits
337
408
  afterAgent: (state) => {
338
409
  var _a, _b;
@@ -431,4 +502,4 @@ export {
431
502
  copilotKitInterrupt,
432
503
  copilotkitMiddleware
433
504
  };
434
- //# sourceMappingURL=chunk-5AVAJKYU.mjs.map
505
+ //# sourceMappingURL=chunk-VDFMYX6O.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, SystemMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport * as z from \"zod\";\n\nconst createAppContextBeforeAgent = (state, runtime) => {\n const messages = state.messages;\n\n if (!messages || messages.length === 0) {\n return;\n }\n\n // Get app context from runtime\n const appContext = state[\"copilotkit\"]?.context ?? runtime?.context;\n\n // Check if appContext is missing or empty\n const isEmptyContext =\n !appContext ||\n (typeof appContext === \"string\" && appContext.trim() === \"\") ||\n (typeof appContext === \"object\" && Object.keys(appContext).length === 0);\n\n if (isEmptyContext) {\n return;\n }\n\n // Create the context content\n const contextContent =\n typeof appContext === \"string\" ? appContext : JSON.stringify(appContext, null, 2);\n const contextMessageContent = `App Context:\\n${contextContent}`;\n const contextMessagePrefix = \"App Context:\\n\";\n\n // Helper to get message content as string\n const getContentString = (msg: any): string | null => {\n if (typeof msg.content === \"string\") return msg.content;\n if (Array.isArray(msg.content) && msg.content[0]?.text) return msg.content[0].text;\n return null;\n };\n\n // Find the first system/developer message (not our context message) to determine\n // where to insert our context message (right after it)\n let firstSystemIndex = -1;\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const type = msg._getType?.();\n if (type === \"system\" || type === \"developer\") {\n const content = getContentString(msg);\n // Skip if this is our own context message\n if (content?.startsWith(contextMessagePrefix)) {\n continue;\n }\n firstSystemIndex = i;\n break;\n }\n }\n\n // Check if our context message already exists\n let existingContextIndex = -1;\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const type = msg._getType?.();\n if (type === \"system\" || type === \"developer\") {\n const content = getContentString(msg);\n if (content?.startsWith(contextMessagePrefix)) {\n existingContextIndex = i;\n break;\n }\n }\n }\n\n // Create the context message\n const contextMessage = new SystemMessage({ content: contextMessageContent });\n\n let updatedMessages;\n\n if (existingContextIndex !== -1) {\n // Replace existing context message\n updatedMessages = [...messages];\n updatedMessages[existingContextIndex] = contextMessage;\n } else {\n // Insert after the first system message, or at position 0 if no system message\n const insertIndex = firstSystemIndex !== -1 ? firstSystemIndex + 1 : 0;\n updatedMessages = [\n ...messages.slice(0, insertIndex),\n contextMessage,\n ...messages.slice(insertIndex),\n ];\n }\n\n return {\n ...state,\n messages: updatedMessages,\n };\n};\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\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 beforeAgent: createAppContextBeforeAgent,\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,0BAA0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,MAAME,SAASF,MAAME,SAASC,SAAS,CAAA;AAC3D,QAAI,CAACuD,WAAUC,WAAWY,WAAAA,KAAgB,GAACA,iBAAYT,eAAZS,mBAAwBpE,SAAQ;AACzE;IACF;AAEA,UAAMqE,mBAA0B,CAAA;AAChC,UAAMC,oBAA2B,CAAA;AAEjC,eAAWC,QAAQH,YAAYT,YAAY;AACzC,UAAIK,kBAAkBQ,IAAID,KAAK9B,IAAI,GAAG;AACpC6B,0BAAkBG,KAAKF,IAAAA;MACzB,OAAO;AACLF,yBAAiBI,KAAKF,IAAAA;MACxB;IACF;AAEA,QAAID,kBAAkBtE,WAAW;AAAG;AAEpC,UAAM0E,mBAAmB,IAAInB,WAAU;MACrCxC,SAASqD,YAAYrD;MACrB4C,YAAYU;MACZZ,IAAIW,YAAYX;IAClB,CAAA;AAEA,WAAO;MACL1D,UAAU;WAAIF,MAAME,SAAS8B,MAAM,GAAG,EAAC;QAAI6C;;MAC3C1C,YAAY;QACV,GAAInC,MAAM,YAAA,KAAiB,CAAC;QAC5BwC,sBAAsBiC;QACtBhC,qBAAqB8B,YAAYX;MACnC;IACF;EACF;AACF;AACA,IAAMkB,6BAA6B,6BAAA;AACjC,SAAOC,iBAAiBpC,eAAAA;AAC1B,GAFmC;AAI5B,IAAMqC,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","SystemMessage","z","createAppContextBeforeAgent","state","runtime","messages","length","appContext","context","isEmptyContext","trim","Object","keys","contextContent","JSON","stringify","contextMessageContent","contextMessagePrefix","getContentString","msg","_a","content","Array","isArray","text","firstSystemIndex","i","type","_getType","startsWith","existingContextIndex","contextMessage","SystemMessage","updatedMessages","insertIndex","slice","copilotKitStateSchema","object","copilotkit","actions","array","any","optional","interceptedToolCalls","originalAIMessageId","string","middlewareInput","name","stateSchema","wrapModelCall","request","handler","frontendTools","existingTools","tools","mergedTools","beforeAgent","afterAgent","originalMessageId","messageFound","map","AIMessage","isInstance","id","existingToolCalls","tool_calls","console","warn","undefined","afterModel","frontendToolNames","Set","t","function","lastMessage","backendToolCalls","frontendToolCalls","call","has","push","updatedAIMessage","createCopilotKitMiddleware","createMiddleware","copilotkitMiddleware"]}
@@ -8,7 +8,7 @@ import {
8
8
  copilotkitEmitState,
9
9
  copilotkitEmitToolCall,
10
10
  copilotkitExit
11
- } from "./chunk-5AVAJKYU.mjs";
11
+ } from "./chunk-VDFMYX6O.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.");
package/dist/langgraph.js CHANGED
@@ -348,6 +348,76 @@ __name(copilotKitInterrupt, "copilotKitInterrupt");
348
348
  // src/langgraph/middleware.ts
349
349
  var import_langchain = require("langchain");
350
350
  var z = __toESM(require("zod"));
351
+ var createAppContextBeforeAgent = /* @__PURE__ */ __name((state, runtime) => {
352
+ var _a, _b, _c;
353
+ const messages = state.messages;
354
+ if (!messages || messages.length === 0) {
355
+ return;
356
+ }
357
+ const appContext = ((_a = state["copilotkit"]) == null ? void 0 : _a.context) ?? (runtime == null ? void 0 : runtime.context);
358
+ const isEmptyContext = !appContext || typeof appContext === "string" && appContext.trim() === "" || typeof appContext === "object" && Object.keys(appContext).length === 0;
359
+ if (isEmptyContext) {
360
+ return;
361
+ }
362
+ const contextContent = typeof appContext === "string" ? appContext : JSON.stringify(appContext, null, 2);
363
+ const contextMessageContent = `App Context:
364
+ ${contextContent}`;
365
+ const contextMessagePrefix = "App Context:\n";
366
+ const getContentString = /* @__PURE__ */ __name((msg) => {
367
+ var _a2;
368
+ if (typeof msg.content === "string")
369
+ return msg.content;
370
+ if (Array.isArray(msg.content) && ((_a2 = msg.content[0]) == null ? void 0 : _a2.text))
371
+ return msg.content[0].text;
372
+ return null;
373
+ }, "getContentString");
374
+ let firstSystemIndex = -1;
375
+ for (let i = 0; i < messages.length; i++) {
376
+ const msg = messages[i];
377
+ const type = (_b = msg._getType) == null ? void 0 : _b.call(msg);
378
+ if (type === "system" || type === "developer") {
379
+ const content = getContentString(msg);
380
+ if (content == null ? void 0 : content.startsWith(contextMessagePrefix)) {
381
+ continue;
382
+ }
383
+ firstSystemIndex = i;
384
+ break;
385
+ }
386
+ }
387
+ let existingContextIndex = -1;
388
+ for (let i = 0; i < messages.length; i++) {
389
+ const msg = messages[i];
390
+ const type = (_c = msg._getType) == null ? void 0 : _c.call(msg);
391
+ if (type === "system" || type === "developer") {
392
+ const content = getContentString(msg);
393
+ if (content == null ? void 0 : content.startsWith(contextMessagePrefix)) {
394
+ existingContextIndex = i;
395
+ break;
396
+ }
397
+ }
398
+ }
399
+ const contextMessage = new import_langchain.SystemMessage({
400
+ content: contextMessageContent
401
+ });
402
+ let updatedMessages;
403
+ if (existingContextIndex !== -1) {
404
+ updatedMessages = [
405
+ ...messages
406
+ ];
407
+ updatedMessages[existingContextIndex] = contextMessage;
408
+ } else {
409
+ const insertIndex = firstSystemIndex !== -1 ? firstSystemIndex + 1 : 0;
410
+ updatedMessages = [
411
+ ...messages.slice(0, insertIndex),
412
+ contextMessage,
413
+ ...messages.slice(insertIndex)
414
+ ];
415
+ }
416
+ return {
417
+ ...state,
418
+ messages: updatedMessages
419
+ };
420
+ }, "createAppContextBeforeAgent");
351
421
  var copilotKitStateSchema = z.object({
352
422
  copilotkit: z.object({
353
423
  actions: z.array(z.any()),
@@ -376,6 +446,7 @@ var middlewareInput = {
376
446
  tools: mergedTools
377
447
  });
378
448
  },
449
+ beforeAgent: createAppContextBeforeAgent,
379
450
  // Restore frontend tool calls to AIMessage before agent exits
380
451
  afterAgent: (state) => {
381
452
  var _a, _b;
@@ -1 +1 @@
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,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,IA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AAAA;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"]}
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, SystemMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport * as z from \"zod\";\n\nconst createAppContextBeforeAgent = (state, runtime) => {\n const messages = state.messages;\n\n if (!messages || messages.length === 0) {\n return;\n }\n\n // Get app context from runtime\n const appContext = state[\"copilotkit\"]?.context ?? runtime?.context;\n\n // Check if appContext is missing or empty\n const isEmptyContext =\n !appContext ||\n (typeof appContext === \"string\" && appContext.trim() === \"\") ||\n (typeof appContext === \"object\" && Object.keys(appContext).length === 0);\n\n if (isEmptyContext) {\n return;\n }\n\n // Create the context content\n const contextContent =\n typeof appContext === \"string\" ? appContext : JSON.stringify(appContext, null, 2);\n const contextMessageContent = `App Context:\\n${contextContent}`;\n const contextMessagePrefix = \"App Context:\\n\";\n\n // Helper to get message content as string\n const getContentString = (msg: any): string | null => {\n if (typeof msg.content === \"string\") return msg.content;\n if (Array.isArray(msg.content) && msg.content[0]?.text) return msg.content[0].text;\n return null;\n };\n\n // Find the first system/developer message (not our context message) to determine\n // where to insert our context message (right after it)\n let firstSystemIndex = -1;\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const type = msg._getType?.();\n if (type === \"system\" || type === \"developer\") {\n const content = getContentString(msg);\n // Skip if this is our own context message\n if (content?.startsWith(contextMessagePrefix)) {\n continue;\n }\n firstSystemIndex = i;\n break;\n }\n }\n\n // Check if our context message already exists\n let existingContextIndex = -1;\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const type = msg._getType?.();\n if (type === \"system\" || type === \"developer\") {\n const content = getContentString(msg);\n if (content?.startsWith(contextMessagePrefix)) {\n existingContextIndex = i;\n break;\n }\n }\n }\n\n // Create the context message\n const contextMessage = new SystemMessage({ content: contextMessageContent });\n\n let updatedMessages;\n\n if (existingContextIndex !== -1) {\n // Replace existing context message\n updatedMessages = [...messages];\n updatedMessages[existingContextIndex] = contextMessage;\n } else {\n // Insert after the first system message, or at position 0 if no system message\n const insertIndex = firstSystemIndex !== -1 ? firstSystemIndex + 1 : 0;\n updatedMessages = [\n ...messages.slice(0, insertIndex),\n contextMessage,\n ...messages.slice(insertIndex),\n ];\n }\n\n return {\n ...state,\n messages: updatedMessages,\n };\n};\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\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 beforeAgent: createAppContextBeforeAgent,\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,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,OAAOH,MAAMG,SAAS,UAAU;AACjD,cAAM,IAAIT,oCAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CA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AAoMoEoD,eAAAA,MAAAA,EAAEC,aAAFD,gBAAAA,IAAYzB,SAAQyB,EAAEzB;KAAI,CAAA;AAE1F,UAAM2B,cAAcvE,MAAME,SAASF,MAAME,SAASC,SAAS,CAAA;AAC3D,QAAI,CAACuD,2BAAUC,WAAWY,WAAAA,KAAgB,GAACA,iBAAYT,eAAZS,mBAAwBpE,SAAQ;AACzE;IACF;AAEA,UAAMqE,mBAA0B,CAAA;AAChC,UAAMC,oBAA2B,CAAA;AAEjC,eAAWC,QAAQH,YAAYT,YAAY;AACzC,UAAIK,kBAAkBQ,IAAID,KAAK9B,IAAI,GAAG;AACpC6B,0BAAkBG,KAAKF,IAAAA;MACzB,OAAO;AACLF,yBAAiBI,KAAKF,IAAAA;MACxB;IACF;AAEA,QAAID,kBAAkBtE,WAAW;AAAG;AAEpC,UAAM0E,mBAAmB,IAAInB,2BAAU;MACrCxC,SAASqD,YAAYrD;MACrB4C,YAAYU;MACZZ,IAAIW,YAAYX;IAClB,CAAA;AAEA,WAAO;MACL1D,UAAU;WAAIF,MAAME,SAAS8B,MAAM,GAAG,EAAC;QAAI6C;;MAC3C1C,YAAY;QACV,GAAInC,MAAM,YAAA,KAAiB,CAAC;QAC5BwC,sBAAsBiC;QACtBhC,qBAAqB8B,YAAYX;MACnC;IACF;EACF;AACF;AACA,IAAMkB,6BAA6B,6BAAA;AACjC,aAAOC,mCAAiBpC,eAAAA;AAC1B,GAFmC;AAI5B,IAAMqC,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","createAppContextBeforeAgent","state","runtime","messages","length","appContext","context","isEmptyContext","trim","Object","keys","contextContent","JSON","stringify","contextMessageContent","contextMessagePrefix","getContentString","msg","_a","content","Array","isArray","text","firstSystemIndex","i","type","_getType","startsWith","existingContextIndex","contextMessage","SystemMessage","updatedMessages","insertIndex","slice","copilotKitStateSchema","object","copilotkit","actions","array","any","optional","interceptedToolCalls","originalAIMessageId","string","middlewareInput","name","stateSchema","wrapModelCall","request","handler","frontendTools","existingTools","tools","mergedTools","beforeAgent","afterAgent","originalMessageId","messageFound","map","AIMessage","isInstance","id","existingToolCalls","tool_calls","console","warn","undefined","afterModel","frontendToolNames","Set","t","function","lastMessage","backendToolCalls","frontendToolCalls","call","has","push","updatedAIMessage","createCopilotKitMiddleware","createMiddleware","copilotkitMiddleware"]}
@@ -10,7 +10,7 @@ import {
10
10
  copilotkitEmitToolCall,
11
11
  copilotkitExit,
12
12
  copilotkitMiddleware
13
- } from "./chunk-5AVAJKYU.mjs";
13
+ } from "./chunk-VDFMYX6O.mjs";
14
14
  export {
15
15
  CopilotKitPropertiesAnnotation,
16
16
  CopilotKitStateAnnotation,
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "publishConfig": {
10
10
  "access": "public"
11
11
  },
12
- "version": "1.51.4-next.1",
12
+ "version": "1.51.4-next.3",
13
13
  "sideEffects": false,
14
14
  "main": "./dist/index.js",
15
15
  "module": "./dist/index.mjs",
@@ -33,7 +33,7 @@
33
33
  "types": "./dist/index.d.ts",
34
34
  "license": "MIT",
35
35
  "dependencies": {
36
- "@copilotkit/shared": "1.51.4-next.1"
36
+ "@copilotkit/shared": "1.51.4-next.3"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@langchain/core": "^1.1.8",
@@ -1,7 +1,97 @@
1
- import { createMiddleware, AIMessage } from "langchain";
1
+ import { createMiddleware, AIMessage, SystemMessage } from "langchain";
2
2
  import type { InteropZodObject } from "@langchain/core/utils/types";
3
3
  import * as z from "zod";
4
4
 
5
+ const createAppContextBeforeAgent = (state, runtime) => {
6
+ const messages = state.messages;
7
+
8
+ if (!messages || messages.length === 0) {
9
+ return;
10
+ }
11
+
12
+ // Get app context from runtime
13
+ const appContext = state["copilotkit"]?.context ?? runtime?.context;
14
+
15
+ // Check if appContext is missing or empty
16
+ const isEmptyContext =
17
+ !appContext ||
18
+ (typeof appContext === "string" && appContext.trim() === "") ||
19
+ (typeof appContext === "object" && Object.keys(appContext).length === 0);
20
+
21
+ if (isEmptyContext) {
22
+ return;
23
+ }
24
+
25
+ // Create the context content
26
+ const contextContent =
27
+ typeof appContext === "string" ? appContext : JSON.stringify(appContext, null, 2);
28
+ const contextMessageContent = `App Context:\n${contextContent}`;
29
+ const contextMessagePrefix = "App Context:\n";
30
+
31
+ // Helper to get message content as string
32
+ const getContentString = (msg: any): string | null => {
33
+ if (typeof msg.content === "string") return msg.content;
34
+ if (Array.isArray(msg.content) && msg.content[0]?.text) return msg.content[0].text;
35
+ return null;
36
+ };
37
+
38
+ // Find the first system/developer message (not our context message) to determine
39
+ // where to insert our context message (right after it)
40
+ let firstSystemIndex = -1;
41
+
42
+ for (let i = 0; i < messages.length; i++) {
43
+ const msg = messages[i];
44
+ const type = msg._getType?.();
45
+ if (type === "system" || type === "developer") {
46
+ const content = getContentString(msg);
47
+ // Skip if this is our own context message
48
+ if (content?.startsWith(contextMessagePrefix)) {
49
+ continue;
50
+ }
51
+ firstSystemIndex = i;
52
+ break;
53
+ }
54
+ }
55
+
56
+ // Check if our context message already exists
57
+ let existingContextIndex = -1;
58
+ for (let i = 0; i < messages.length; i++) {
59
+ const msg = messages[i];
60
+ const type = msg._getType?.();
61
+ if (type === "system" || type === "developer") {
62
+ const content = getContentString(msg);
63
+ if (content?.startsWith(contextMessagePrefix)) {
64
+ existingContextIndex = i;
65
+ break;
66
+ }
67
+ }
68
+ }
69
+
70
+ // Create the context message
71
+ const contextMessage = new SystemMessage({ content: contextMessageContent });
72
+
73
+ let updatedMessages;
74
+
75
+ if (existingContextIndex !== -1) {
76
+ // Replace existing context message
77
+ updatedMessages = [...messages];
78
+ updatedMessages[existingContextIndex] = contextMessage;
79
+ } else {
80
+ // Insert after the first system message, or at position 0 if no system message
81
+ const insertIndex = firstSystemIndex !== -1 ? firstSystemIndex + 1 : 0;
82
+ updatedMessages = [
83
+ ...messages.slice(0, insertIndex),
84
+ contextMessage,
85
+ ...messages.slice(insertIndex),
86
+ ];
87
+ }
88
+
89
+ return {
90
+ ...state,
91
+ messages: updatedMessages,
92
+ };
93
+ };
94
+
5
95
  /**
6
96
  * CopilotKit Middleware for LangGraph agents.
7
97
  *
@@ -34,7 +124,6 @@ const copilotKitStateSchema = z.object({
34
124
  .optional(),
35
125
  });
36
126
 
37
-
38
127
  const middlewareInput = {
39
128
  name: "CopilotKitMiddleware",
40
129
 
@@ -57,6 +146,8 @@ const middlewareInput = {
57
146
  });
58
147
  },
59
148
 
149
+ beforeAgent: createAppContextBeforeAgent,
150
+
60
151
  // Restore frontend tool calls to AIMessage before agent exits
61
152
  afterAgent: (state) => {
62
153
  const interceptedToolCalls = state["copilotkit"]?.interceptedToolCalls;
@@ -1 +0,0 @@
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,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qB,oBAAoB,IAAIC,IAAIxB,cAAcW,IAAI,CAACc,MAAAA;AAzGzD,UAAAC;AAyGoED,eAAAA,MAAAA,EAAEE,aAAFF,gBAAAA,IAAY9B,SAAQ8B,EAAE9B;KAAI,CAAA;AAE1F,UAAMiC,cAAc3B,MAAMS,SAAST,MAAMS,SAASR,SAAS,CAAA;AAC3D,QAAI,CAACW,WAAUC,WAAWc,WAAAA,KAAgB,GAACA,iBAAYX,eAAZW,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,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"]}