@copilotkit/sdk-js 1.51.4-next.6 → 1.51.4-next.8

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,17 @@
1
1
  # @copilotkit/sdk-js
2
2
 
3
+ ## 1.51.4-next.8
4
+
5
+ ### Patch Changes
6
+
7
+ - @copilotkit/shared@1.51.4-next.8
8
+
9
+ ## 1.51.4-next.7
10
+
11
+ ### Patch Changes
12
+
13
+ - @copilotkit/shared@1.51.4-next.7
14
+
3
15
  ## 1.51.4-next.6
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,5 @@
1
1
  # CopilotKit - SDK JS
2
2
 
3
-
4
3
  <img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />
5
4
 
6
5
  <br>
@@ -502,4 +502,4 @@ export {
502
502
  copilotKitInterrupt,
503
503
  copilotkitMiddleware
504
504
  };
505
- //# sourceMappingURL=chunk-VDFMYX6O.mjs.map
505
+ //# sourceMappingURL=chunk-A7ZQHBQI.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 {\n convertJsonSchemaToZodSchema,\n randomId,\n CopilotKitMisuseError,\n} 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(\n (state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }),\n );\n\n metadata[\"copilotkit:emit-intermediate-state\"] =\n 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(\n \"copilotkit_manually_emit_intermediate_state\",\n state,\n config,\n );\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:\n \"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(\n actionInput: any,\n): 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\"\n ? appContext\n : 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)\n 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(\n frontendTools.map((t: any) => t.function?.name || t.name),\n );\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,SACEC,8BACAC,UACAC,6BACK;AACP,SAASC,iBAAiB;AAC1B,SAASC,6BAA6B;AACtC,SAASC,iBAAiB;AA6CnB,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,sBAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAAOA,YAAY,UAAU;AAC1C,UAAM,IAAIC,sBAAsB;M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,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"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/langchain.ts","../src/langgraph/types.ts","../src/langgraph/utils.ts"],"sourcesContent":["console.warn(\n \"Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.\",\n);\n\nexport {\n CopilotKitPropertiesAnnotation,\n CopilotKitStateAnnotation,\n type CopilotKitState,\n type CopilotKitProperties,\n copilotkitCustomizeConfig as copilotKitCustomizeConfig,\n copilotkitExit as copilotKitExit,\n copilotkitEmitState as copilotKitEmitState,\n copilotkitEmitMessage as copilotKitEmitMessage,\n copilotkitEmitToolCall as copilotKitEmitToolCall,\n convertActionToDynamicStructuredTool,\n convertActionsToDynamicStructuredTools,\n} from \"./langgraph\";\n","import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n\nexport const CopilotKitPropertiesAnnotation = Annotation.Root({\n actions: Annotation<any[]>,\n context: Annotation<{ description: string; value: string }[]>,\n interceptedToolCalls: Annotation<any[]>,\n originalAIMessageId: Annotation<string>,\n});\n\nexport const CopilotKitStateAnnotation = Annotation.Root({\n copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,\n ...MessagesAnnotation.spec,\n});\n\nexport interface IntermediateStateConfig {\n stateKey: string;\n tool: string;\n toolArgument?: string;\n}\n\nexport interface OptionsConfig {\n emitToolCalls?: boolean | string | string[];\n emitMessages?: boolean;\n emitAll?: boolean;\n emitIntermediateState?: IntermediateStateConfig[];\n}\n\nexport type CopilotKitState = typeof CopilotKitStateAnnotation.State;\nexport type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;\n","import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\nimport { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from \"@copilotkit/shared\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { OptionsConfig } from \"./types\";\n\n/**\n * Customize the LangGraph configuration for use in CopilotKit.\n *\n * To the CopilotKit SDK, run:\n *\n * ```bash\n * npm install @copilotkit/sdk-js\n * ```\n *\n * ### Examples\n *\n * Disable emitting messages and tool calls:\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitMessages=false,\n * emitToolCalls=false\n * )\n * ```\n *\n * To emit a tool call as streaming LangGraph state, pass the destination key in state,\n * the tool name and optionally the tool argument. (If you don't pass the argument name,\n * all arguments are emitted under the state key.)\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitIntermediateState=[\n * {\n * \"stateKey\": \"steps\",\n * \"tool\": \"SearchTool\",\n * \"toolArgument\": \"steps\",\n * },\n * ],\n * )\n * ```\n */\nexport function copilotkitCustomizeConfig(\n /**\n * The LangChain/LangGraph configuration to customize.\n */\n baseConfig: RunnableConfig,\n /**\n * Configuration options:\n * - `emitMessages: boolean?`\n * Configure how messages are emitted. By default, all messages are emitted. Pass false to\n * disable emitting messages.\n * - `emitToolCalls: boolean | string | string[]?`\n * Configure how tool calls are emitted. By default, all tool calls are emitted. Pass false to\n * disable emitting tool calls. Pass a string or list of strings to emit only specific tool calls.\n * - `emitIntermediateState: IntermediateStateConfig[]?`\n * Lets you emit tool calls as streaming LangGraph state.\n */\n options?: OptionsConfig,\n): RunnableConfig {\n if (baseConfig && typeof baseConfig !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"baseConfig must be an object or null/undefined\",\n });\n }\n\n if (options && typeof options !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"options must be an object when provided\",\n });\n }\n\n // Validate emitIntermediateState structure\n if (options?.emitIntermediateState) {\n if (!Array.isArray(options.emitIntermediateState)) {\n throw new CopilotKitMisuseError({\n message: \"emitIntermediateState must be an array when provided\",\n });\n }\n\n options.emitIntermediateState.forEach((state, index) => {\n if (!state || typeof state !== \"object\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must be an object`,\n });\n }\n\n if (!state.stateKey || typeof state.stateKey !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`,\n });\n }\n\n if (!state.tool || typeof state.tool !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'tool' string property`,\n });\n }\n\n if (state.toolArgument && typeof state.toolArgument !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}].toolArgument must be a string when provided`,\n });\n }\n });\n }\n\n try {\n const metadata = baseConfig?.metadata || {};\n\n if (options?.emitAll) {\n metadata[\"copilotkit:emit-tool-calls\"] = true;\n metadata[\"copilotkit:emit-messages\"] = true;\n } else {\n if (options?.emitToolCalls !== undefined) {\n metadata[\"copilotkit:emit-tool-calls\"] = options.emitToolCalls;\n }\n if (options?.emitMessages !== undefined) {\n metadata[\"copilotkit:emit-messages\"] = options.emitMessages;\n }\n }\n\n if (options?.emitIntermediateState) {\n const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }));\n\n metadata[\"copilotkit:emit-intermediate-state\"] = snakeCaseIntermediateState;\n }\n\n baseConfig = baseConfig || {};\n\n return {\n ...baseConfig,\n metadata: metadata,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Exits the current agent after the run completes. Calling copilotkit_exit() will\n * not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after\n * the run completes.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitExit } from \"@copilotkit/sdk-js\";\n *\n * async function myNode(state: Any):\n * await copilotkitExit(config)\n * return state\n * ```\n */\nexport async function copilotkitExit(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitExit\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_exit\", {}, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Emits intermediate state to CopilotKit. Useful if you have a longer running node and you want to\n * update the user with the current state of the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitState } from \"@copilotkit/sdk-js\";\n *\n * for (let i = 0; i < 10; i++) {\n * await someLongRunningOperation(i);\n * await copilotkitEmitState(config, { progress: i });\n * }\n * ```\n */\nexport async function copilotkitEmitState(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The state to emit.\n */\n state: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitState\",\n });\n }\n\n if (state === undefined) {\n throw new CopilotKitMisuseError({\n message: \"State is required for copilotkitEmitState\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_manually_emit_intermediate_state\", state, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a message to CopilotKit. Useful in longer running nodes to update the user.\n * Important: You still need to return the messages from the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitMessage } from \"@copilotkit/sdk-js\";\n *\n * const message = \"Step 1 of 10 complete\";\n * await copilotkitEmitMessage(config, message);\n *\n * // Return the message from the node\n * return {\n * \"messages\": [AIMessage(content=message)]\n * }\n * ```\n */\nexport async function copilotkitEmitMessage(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The message to emit.\n */\n message: string,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitMessage\",\n });\n }\n\n if (!message || typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a non-empty string for copilotkitEmitMessage\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_message\",\n { message, message_id: randomId(), role: \"assistant\" },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a tool call to CopilotKit.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitToolCall } from \"@copilotkit/sdk-js\";\n *\n * await copilotkitEmitToolCall(config, name=\"SearchTool\", args={\"steps\": 10})\n * ```\n */\nexport async function copilotkitEmitToolCall(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The name of the tool to emit.\n */\n name: string,\n /**\n * The arguments to emit.\n */\n args: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitToolCall\",\n });\n }\n\n if (!name || typeof name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Tool name must be a non-empty string for copilotkitEmitToolCall\",\n });\n }\n\n if (args === undefined) {\n throw new CopilotKitMisuseError({\n message: \"Tool arguments are required for copilotkitEmitToolCall\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_tool_call\",\n { name, args, id: randomId() },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit tool call '${name}': ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n\nexport function convertActionToDynamicStructuredTool(actionInput: any): DynamicStructuredTool<any> {\n if (!actionInput) {\n throw new CopilotKitMisuseError({\n message: \"Action input is required but was not provided\",\n });\n }\n\n if (!actionInput.name || typeof actionInput.name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must have a valid 'name' property of type string\",\n });\n }\n\n if (\n actionInput.description == undefined ||\n actionInput.description == null ||\n typeof actionInput.description !== \"string\"\n ) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,\n });\n }\n\n if (!actionInput.parameters) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a 'parameters' property`,\n });\n }\n\n try {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),\n func: async () => {\n return \"\";\n },\n });\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Use this function to convert a list of actions you get from state\n * to a list of dynamic structured tools.\n *\n * ### Examples\n *\n * ```typescript\n * import { convertActionsToDynamicStructuredTools } from \"@copilotkit/sdk-js\";\n *\n * const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);\n * ```\n */\nexport function convertActionsToDynamicStructuredTools(\n /**\n * The list of actions to convert.\n */\n actions: any[],\n): DynamicStructuredTool<any>[] {\n if (!Array.isArray(actions)) {\n throw new CopilotKitMisuseError({\n message: \"Actions must be an array\",\n });\n }\n\n return actions.map((action, index) => {\n try {\n return convertActionToDynamicStructuredTool(\n action.type === \"function\" ? action.function : action,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n });\n}\n\nexport function copilotKitInterrupt({\n message,\n action,\n args,\n}: {\n message?: string;\n action?: string;\n args?: Record<string, any>;\n}) {\n if (!message && !action) {\n throw new CopilotKitMisuseError({\n message:\n \"Either message or action (and optional arguments) must be provided for copilotKitInterrupt\",\n });\n }\n\n if (action && typeof action !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (message && typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (args && typeof args !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"Args must be an object when provided to copilotKitInterrupt\",\n });\n }\n\n let interruptValues = null;\n let interruptMessage = null;\n let answer = null;\n\n try {\n if (message) {\n interruptValues = message;\n interruptMessage = new AIMessage({ content: message, id: randomId() });\n } else {\n const toolId = randomId();\n interruptMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolId, name: action, args: args ?? {} }],\n });\n interruptValues = {\n action,\n args: args ?? {},\n };\n }\n\n const response = interrupt({\n __copilotkit_interrupt_value__: interruptValues,\n __copilotkit_messages__: [interruptMessage],\n });\n answer = response[response.length - 1].content;\n\n return {\n answer,\n messages: response,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAAA;;;;;;;;;;;;;;;ACAA,uBAA+C;AAExC,IAAMC,iCAAiCC,4BAAWC,KAAK;EAC5DC,SAASF;EACTG,SAASH;EACTI,sBAAsBJ;EACtBK,qBAAqBL;AACvB,CAAA;AAEO,IAAMM,4BAA4BN,4BAAWC,KAAK;EACvDM,YAAYP;EACZ,GAAGQ,oCAAmBC;AACxB,CAAA;;;ACXA,sBAAoC;AACpC,oBAA8E;AAC9E,IAAAC,oBAA0B;AAC1B,mBAAsC;AACtC,sBAA0B;AA6CnB,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAAOA,YAA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IAClC,CAAA;EACF;AAEA,MAAI,CAACI,YAAYE,YAAY;AAC3B,UAAM,IAAItC,oCAAsB;MAC9BC,SAAS,WAAWmC,YAAYJ;IAClC,CAAA;EACF;AAEA,MAAI;AACF,WAAO,IAAIO,mCAAsB;MAC/BP,MAAMI,YAAYJ;MAClBK,aAAaD,YAAYC;MACzBG,YAAQC,4CAA6BL,YAAYE,YAAY,IAAA;MAC7DI,MAAM,YAAA;AACJ,eAAO;MACT;IACF,CAAA;EACF,SAAStB,OAAP;AACA,UAAM,IAAIpB,oCAAsB;MAC9BC,SAAS,6BAA6BmC,YAAYJ,mCAAmCZ,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;IACvI,CAAA;EACF;AACF;AA3CgBe;AAwDT,SAASQ,uCAIdC,SAAc;AAEd,MAAI,CAACzC,MAAMC,QAAQwC,OAAAA,GAAU;AAC3B,UAAM,IAAI5C,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,SAAO2C,QAAQ3B,IAAI,CAAC4B,QAAQtC,UAAAA;AAC1B,QAAI;AACF,aAAO4B,qCACLU,OAAOC,SAAS,aAAaD,OAAOE,WAAWF,MAAAA;IAEnD,SAASzB,OAAP;AACA,YAAM,IAAIpB,oCAAsB;QAC9BC,SAAS,qCAAqCM,UAAUa,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;MAC1G,CAAA;IACF;EACF,CAAA;AACF;AAvBgBuB;;;AF5YhBK,QAAQC,KACN,mJAAA;","names":["console","CopilotKitPropertiesAnnotation","Annotation","Root","actions","context","interceptedToolCalls","originalAIMessageId","CopilotKitStateAnnotation","copilotkit","MessagesAnnotation","spec","import_langgraph","copilotkitCustomizeConfig","baseConfig","options","CopilotKitMisuseError","message","emitIntermediateState","Array","isArray","forEach","state","index","stateKey","tool","toolArgument","metadata","emitAll","emitToolCalls","undefined","emitMessages","snakeCaseIntermediateState","map","tool_argument","state_key","error","Error","String","copilotkitExit","config","dispatchCustomEvent","copilotkitEmitState","copilotkitEmitMessage","message_id","randomId","role","copilotkitEmitToolCall","name","args","id","convertActionToDynamicStructuredTool","actionInput","description","parameters","DynamicStructuredTool","schema","convertJsonSchemaToZodSchema","func","convertActionsToDynamicStructuredTools","actions","action","type","function","console","warn"]}
1
+ {"version":3,"sources":["../src/langchain.ts","../src/langgraph/types.ts","../src/langgraph/utils.ts"],"sourcesContent":["console.warn(\n \"Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.\",\n);\n\nexport {\n CopilotKitPropertiesAnnotation,\n CopilotKitStateAnnotation,\n type CopilotKitState,\n type CopilotKitProperties,\n copilotkitCustomizeConfig as copilotKitCustomizeConfig,\n copilotkitExit as copilotKitExit,\n copilotkitEmitState as copilotKitEmitState,\n copilotkitEmitMessage as copilotKitEmitMessage,\n copilotkitEmitToolCall as copilotKitEmitToolCall,\n convertActionToDynamicStructuredTool,\n convertActionsToDynamicStructuredTools,\n} from \"./langgraph\";\n","import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n\nexport const CopilotKitPropertiesAnnotation = Annotation.Root({\n actions: Annotation<any[]>,\n context: Annotation<{ description: string; value: string }[]>,\n interceptedToolCalls: Annotation<any[]>,\n originalAIMessageId: Annotation<string>,\n});\n\nexport const CopilotKitStateAnnotation = Annotation.Root({\n copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,\n ...MessagesAnnotation.spec,\n});\n\nexport interface IntermediateStateConfig {\n stateKey: string;\n tool: string;\n toolArgument?: string;\n}\n\nexport interface OptionsConfig {\n emitToolCalls?: boolean | string | string[];\n emitMessages?: boolean;\n emitAll?: boolean;\n emitIntermediateState?: IntermediateStateConfig[];\n}\n\nexport type CopilotKitState = typeof CopilotKitStateAnnotation.State;\nexport type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;\n","import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\nimport {\n convertJsonSchemaToZodSchema,\n randomId,\n CopilotKitMisuseError,\n} 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(\n (state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }),\n );\n\n metadata[\"copilotkit:emit-intermediate-state\"] =\n 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(\n \"copilotkit_manually_emit_intermediate_state\",\n state,\n config,\n );\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:\n \"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(\n actionInput: any,\n): DynamicStructuredTool<any> {\n if (!actionInput) {\n throw new CopilotKitMisuseError({\n message: \"Action input is required but was not provided\",\n });\n }\n\n if (!actionInput.name || typeof actionInput.name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must have a valid 'name' property of type string\",\n });\n }\n\n if (\n actionInput.description == undefined ||\n actionInput.description == null ||\n typeof actionInput.description !== \"string\"\n ) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,\n });\n }\n\n if (!actionInput.parameters) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a 'parameters' property`,\n });\n }\n\n try {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),\n func: async () => {\n return \"\";\n },\n });\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Use this function to convert a list of actions you get from state\n * to a list of dynamic structured tools.\n *\n * ### Examples\n *\n * ```typescript\n * import { convertActionsToDynamicStructuredTools } from \"@copilotkit/sdk-js\";\n *\n * const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);\n * ```\n */\nexport function convertActionsToDynamicStructuredTools(\n /**\n * The list of actions to convert.\n */\n actions: any[],\n): DynamicStructuredTool<any>[] {\n if (!Array.isArray(actions)) {\n throw new CopilotKitMisuseError({\n message: \"Actions must be an array\",\n });\n }\n\n return actions.map((action, index) => {\n try {\n return convertActionToDynamicStructuredTool(\n action.type === \"function\" ? action.function : action,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n });\n}\n\nexport function copilotKitInterrupt({\n message,\n action,\n args,\n}: {\n message?: string;\n action?: string;\n args?: Record<string, any>;\n}) {\n if (!message && !action) {\n throw new CopilotKitMisuseError({\n message:\n \"Either message or action (and optional arguments) must be provided for copilotKitInterrupt\",\n });\n }\n\n if (action && typeof action !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (message && typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (args && typeof args !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"Args must be an object when provided to copilotKitInterrupt\",\n });\n }\n\n let interruptValues = null;\n let interruptMessage = null;\n let answer = null;\n\n try {\n if (message) {\n interruptValues = message;\n interruptMessage = new AIMessage({ content: message, id: randomId() });\n } else {\n const toolId = randomId();\n interruptMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolId, name: action, args: args ?? {} }],\n });\n interruptValues = {\n action,\n args: args ?? {},\n };\n }\n\n const response = interrupt({\n __copilotkit_interrupt_value__: interruptValues,\n __copilotkit_messages__: [interruptMessage],\n });\n answer = response[response.length - 1].content;\n\n return {\n answer,\n messages: response,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAAA;;;;;;;;;;;;;;;ACAA,uBAA+C;AAExC,IAAMC,iCAAiCC,4BAAWC,KAAK;EAC5DC,SAASF;EACTG,SAASH;EACTI,sBAAsBJ;EACtBK,qBAAqBL;AACvB,CAAA;AAEO,IAAMM,4BAA4BN,4BAAWC,KAAK;EACvDM,YAAYP;EACZ,GAAGQ,oCAAmBC;AACxB,CAAA;;;ACXA,sBAAoC;AACpC,oBAIO;AACP,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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AA;EACF;AAEA,MAAI,CAACI,YAAYE,YAAY;AAC3B,UAAM,IAAItC,oCAAsB;MAC9BC,SAAS,WAAWmC,YAAYJ;IAClC,CAAA;EACF;AAEA,MAAI;AACF,WAAO,IAAIO,mCAAsB;MAC/BP,MAAMI,YAAYJ;MAClBK,aAAaD,YAAYC;MACzBG,YAAQC,4CAA6BL,YAAYE,YAAY,IAAA;MAC7DI,MAAM,YAAA;AACJ,eAAO;MACT;IACF,CAAA;EACF,SAAStB,OAAP;AACA,UAAM,IAAIpB,oCAAsB;MAC9BC,SAAS,6BAA6BmC,YAAYJ,mCAAmCZ,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;IACvI,CAAA;EACF;AACF;AA7CgBe;AA0DT,SAASQ,uCAIdC,SAAc;AAEd,MAAI,CAACzC,MAAMC,QAAQwC,OAAAA,GAAU;AAC3B,UAAM,IAAI5C,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,SAAO2C,QAAQ3B,IAAI,CAAC4B,QAAQtC,UAAAA;AAC1B,QAAI;AACF,aAAO4B,qCACLU,OAAOC,SAAS,aAAaD,OAAOE,WAAWF,MAAAA;IAEnD,SAASzB,OAAP;AACA,YAAM,IAAIpB,oCAAsB;QAC9BC,SAAS,qCAAqCM,UAAUa,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;MAC1G,CAAA;IACF;EACF,CAAA;AACF;AAvBgBuB;;;AF1ZhBK,QAAQC,KACN,mJAAA;","names":["console","CopilotKitPropertiesAnnotation","Annotation","Root","actions","context","interceptedToolCalls","originalAIMessageId","CopilotKitStateAnnotation","copilotkit","MessagesAnnotation","spec","import_langgraph","copilotkitCustomizeConfig","baseConfig","options","CopilotKitMisuseError","message","emitIntermediateState","Array","isArray","forEach","state","index","stateKey","tool","toolArgument","metadata","emitAll","emitToolCalls","undefined","emitMessages","snakeCaseIntermediateState","map","tool_argument","state_key","error","Error","String","copilotkitExit","config","dispatchCustomEvent","copilotkitEmitState","copilotkitEmitMessage","message_id","randomId","role","copilotkitEmitToolCall","name","args","id","convertActionToDynamicStructuredTool","actionInput","description","parameters","DynamicStructuredTool","schema","convertJsonSchemaToZodSchema","func","convertActionsToDynamicStructuredTools","actions","action","type","function","console","warn"]}
@@ -8,7 +8,7 @@ import {
8
8
  copilotkitEmitState,
9
9
  copilotkitEmitToolCall,
10
10
  copilotkitExit
11
- } from "./chunk-VDFMYX6O.mjs";
11
+ } from "./chunk-A7ZQHBQI.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.");
@@ -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, 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,oCAA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notation","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"]}
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 {\n convertJsonSchemaToZodSchema,\n randomId,\n CopilotKitMisuseError,\n} 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(\n (state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }),\n );\n\n metadata[\"copilotkit:emit-intermediate-state\"] =\n 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(\n \"copilotkit_manually_emit_intermediate_state\",\n state,\n config,\n );\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:\n \"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(\n actionInput: any,\n): 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\"\n ? appContext\n : 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)\n 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(\n frontendTools.map((t: any) => t.function?.name || t.name),\n );\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,4BAA4B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,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-VDFMYX6O.mjs";
13
+ } from "./chunk-A7ZQHBQI.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.6",
12
+ "version": "1.51.4-next.8",
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.6"
36
+ "@copilotkit/shared": "1.51.4-next.8"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@langchain/core": "^1.1.8",
@@ -79,7 +79,6 @@
79
79
  "dev": "tsup --watch --no-splitting",
80
80
  "test": "jest --passWithNoTests",
81
81
  "check-types": "tsc --noEmit",
82
- "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next",
83
82
  "link:global": "pnpm link --global",
84
83
  "unlink:global": "pnpm unlink --global"
85
84
  }
@@ -31,7 +31,9 @@ describe("SDK-JS Error Handling", () => {
31
31
 
32
32
  expect(() => {
33
33
  copilotKitInterrupt({ action: 123 as any });
34
- }).toThrow("Action must be a string when provided to copilotKitInterrupt");
34
+ }).toThrow(
35
+ "Action must be a string when provided to copilotKitInterrupt",
36
+ );
35
37
  });
36
38
 
37
39
  it("should throw CopilotKitMisuseError when message is not a string", () => {
@@ -41,7 +43,9 @@ describe("SDK-JS Error Handling", () => {
41
43
 
42
44
  expect(() => {
43
45
  copilotKitInterrupt({ message: 123 as any });
44
- }).toThrow("Message must be a string when provided to copilotKitInterrupt");
46
+ }).toThrow(
47
+ "Message must be a string when provided to copilotKitInterrupt",
48
+ );
45
49
  });
46
50
 
47
51
  it("should throw CopilotKitMisuseError when args is not an object", () => {
@@ -83,16 +87,24 @@ describe("SDK-JS Error Handling", () => {
83
87
 
84
88
  expect(() => {
85
89
  convertActionToDynamicStructuredTool({ name: "test" });
86
- }).toThrow("Action 'test' must have a valid 'description' property of type string");
90
+ }).toThrow(
91
+ "Action 'test' must have a valid 'description' property of type string",
92
+ );
87
93
  });
88
94
 
89
95
  it("should throw CopilotKitMisuseError when parameters is missing", () => {
90
96
  expect(() => {
91
- convertActionToDynamicStructuredTool({ name: "test", description: "test desc" });
97
+ convertActionToDynamicStructuredTool({
98
+ name: "test",
99
+ description: "test desc",
100
+ });
92
101
  }).toThrow(CopilotKitMisuseError);
93
102
 
94
103
  expect(() => {
95
- convertActionToDynamicStructuredTool({ name: "test", description: "test desc" });
104
+ convertActionToDynamicStructuredTool({
105
+ name: "test",
106
+ description: "test desc",
107
+ });
96
108
  }).toThrow("Action 'test' must have a 'parameters' property");
97
109
  });
98
110
  });
@@ -132,22 +144,36 @@ describe("SDK-JS Error Handling", () => {
132
144
 
133
145
  it("should throw CopilotKitMisuseError when emitIntermediateState is not an array", () => {
134
146
  expect(() => {
135
- copilotkitCustomizeConfig({}, { emitIntermediateState: "invalid" as any });
147
+ copilotkitCustomizeConfig(
148
+ {},
149
+ { emitIntermediateState: "invalid" as any },
150
+ );
136
151
  }).toThrow(CopilotKitMisuseError);
137
152
 
138
153
  expect(() => {
139
- copilotkitCustomizeConfig({}, { emitIntermediateState: "invalid" as any });
154
+ copilotkitCustomizeConfig(
155
+ {},
156
+ { emitIntermediateState: "invalid" as any },
157
+ );
140
158
  }).toThrow("emitIntermediateState must be an array when provided");
141
159
  });
142
160
 
143
161
  it("should throw CopilotKitMisuseError when emitIntermediateState item is invalid", () => {
144
162
  expect(() => {
145
- copilotkitCustomizeConfig({}, { emitIntermediateState: [{ invalidKey: "value" }] as any });
163
+ copilotkitCustomizeConfig(
164
+ {},
165
+ { emitIntermediateState: [{ invalidKey: "value" }] as any },
166
+ );
146
167
  }).toThrow(CopilotKitMisuseError);
147
168
 
148
169
  expect(() => {
149
- copilotkitCustomizeConfig({}, { emitIntermediateState: [{ invalidKey: "value" }] as any });
150
- }).toThrow("emitIntermediateState[0] must have a valid 'stateKey' string property");
170
+ copilotkitCustomizeConfig(
171
+ {},
172
+ { emitIntermediateState: [{ invalidKey: "value" }] as any },
173
+ );
174
+ }).toThrow(
175
+ "emitIntermediateState[0] must have a valid 'stateKey' string property",
176
+ );
151
177
  });
152
178
  });
153
179
 
@@ -155,14 +181,18 @@ describe("SDK-JS Error Handling", () => {
155
181
  const mockConfig = { metadata: {} };
156
182
 
157
183
  it("should throw CopilotKitMisuseError when config is missing for copilotkitExit", async () => {
158
- await expect(copilotkitExit(null as any)).rejects.toThrow(CopilotKitMisuseError);
184
+ await expect(copilotkitExit(null as any)).rejects.toThrow(
185
+ CopilotKitMisuseError,
186
+ );
159
187
  await expect(copilotkitExit(null as any)).rejects.toThrow(
160
188
  "LangGraph configuration is required for copilotkitExit",
161
189
  );
162
190
  });
163
191
 
164
192
  it("should throw CopilotKitMisuseError when config is missing for copilotkitEmitState", async () => {
165
- await expect(copilotkitEmitState(null as any, {})).rejects.toThrow(CopilotKitMisuseError);
193
+ await expect(copilotkitEmitState(null as any, {})).rejects.toThrow(
194
+ CopilotKitMisuseError,
195
+ );
166
196
  await expect(copilotkitEmitState(null as any, {})).rejects.toThrow(
167
197
  "LangGraph configuration is required for copilotkitEmitState",
168
198
  );
@@ -178,10 +208,12 @@ describe("SDK-JS Error Handling", () => {
178
208
  });
179
209
 
180
210
  it("should throw CopilotKitMisuseError when message is invalid for copilotkitEmitMessage", async () => {
181
- await expect(copilotkitEmitMessage(mockConfig, "" as any)).rejects.toThrow(
182
- CopilotKitMisuseError,
183
- );
184
- await expect(copilotkitEmitMessage(mockConfig, "" as any)).rejects.toThrow(
211
+ await expect(
212
+ copilotkitEmitMessage(mockConfig, "" as any),
213
+ ).rejects.toThrow(CopilotKitMisuseError);
214
+ await expect(
215
+ copilotkitEmitMessage(mockConfig, "" as any),
216
+ ).rejects.toThrow(
185
217
  "Message must be a non-empty string for copilotkitEmitMessage",
186
218
  );
187
219
  });
@@ -196,10 +228,12 @@ describe("SDK-JS Error Handling", () => {
196
228
  });
197
229
 
198
230
  it("should throw CopilotKitMisuseError when args is undefined for copilotkitEmitToolCall", async () => {
199
- await expect(copilotkitEmitToolCall(mockConfig, "testTool", undefined)).rejects.toThrow(
200
- CopilotKitMisuseError,
201
- );
202
- await expect(copilotkitEmitToolCall(mockConfig, "testTool", undefined)).rejects.toThrow(
231
+ await expect(
232
+ copilotkitEmitToolCall(mockConfig, "testTool", undefined),
233
+ ).rejects.toThrow(CopilotKitMisuseError);
234
+ await expect(
235
+ copilotkitEmitToolCall(mockConfig, "testTool", undefined),
236
+ ).rejects.toThrow(
203
237
  "Tool arguments are required for copilotkitEmitToolCall",
204
238
  );
205
239
  });
@@ -24,14 +24,17 @@ const createAppContextBeforeAgent = (state, runtime) => {
24
24
 
25
25
  // Create the context content
26
26
  const contextContent =
27
- typeof appContext === "string" ? appContext : JSON.stringify(appContext, null, 2);
27
+ typeof appContext === "string"
28
+ ? appContext
29
+ : JSON.stringify(appContext, null, 2);
28
30
  const contextMessageContent = `App Context:\n${contextContent}`;
29
31
  const contextMessagePrefix = "App Context:\n";
30
32
 
31
33
  // Helper to get message content as string
32
34
  const getContentString = (msg: any): string | null => {
33
35
  if (typeof msg.content === "string") return msg.content;
34
- if (Array.isArray(msg.content) && msg.content[0]?.text) return msg.content[0].text;
36
+ if (Array.isArray(msg.content) && msg.content[0]?.text)
37
+ return msg.content[0].text;
35
38
  return null;
36
39
  };
37
40
 
@@ -194,7 +197,9 @@ const middlewareInput = {
194
197
  const frontendTools = state["copilotkit"]?.actions ?? [];
195
198
  if (frontendTools.length === 0) return;
196
199
 
197
- const frontendToolNames = new Set(frontendTools.map((t: any) => t.function?.name || t.name));
200
+ const frontendToolNames = new Set(
201
+ frontendTools.map((t: any) => t.function?.name || t.name),
202
+ );
198
203
 
199
204
  const lastMessage = state.messages[state.messages.length - 1];
200
205
  if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls?.length) {
@@ -1,6 +1,10 @@
1
1
  import { RunnableConfig } from "@langchain/core/runnables";
2
2
  import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
3
- import { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from "@copilotkit/shared";
3
+ import {
4
+ convertJsonSchemaToZodSchema,
5
+ randomId,
6
+ CopilotKitMisuseError,
7
+ } from "@copilotkit/shared";
4
8
  import { interrupt } from "@langchain/langgraph";
5
9
  import { DynamicStructuredTool } from "@langchain/core/tools";
6
10
  import { AIMessage } from "@langchain/core/messages";
@@ -129,13 +133,16 @@ export function copilotkitCustomizeConfig(
129
133
  }
130
134
 
131
135
  if (options?.emitIntermediateState) {
132
- const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({
133
- tool: state.tool,
134
- tool_argument: state.toolArgument,
135
- state_key: state.stateKey,
136
- }));
136
+ const snakeCaseIntermediateState = options.emitIntermediateState.map(
137
+ (state) => ({
138
+ tool: state.tool,
139
+ tool_argument: state.toolArgument,
140
+ state_key: state.stateKey,
141
+ }),
142
+ );
137
143
 
138
- metadata["copilotkit:emit-intermediate-state"] = snakeCaseIntermediateState;
144
+ metadata["copilotkit:emit-intermediate-state"] =
145
+ snakeCaseIntermediateState;
139
146
  }
140
147
 
141
148
  baseConfig = baseConfig || {};
@@ -223,7 +230,11 @@ export async function copilotkitEmitState(
223
230
  }
224
231
 
225
232
  try {
226
- await dispatchCustomEvent("copilotkit_manually_emit_intermediate_state", state, config);
233
+ await dispatchCustomEvent(
234
+ "copilotkit_manually_emit_intermediate_state",
235
+ state,
236
+ config,
237
+ );
227
238
  } catch (error) {
228
239
  throw new CopilotKitMisuseError({
229
240
  message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,
@@ -315,7 +326,8 @@ export async function copilotkitEmitToolCall(
315
326
 
316
327
  if (!name || typeof name !== "string") {
317
328
  throw new CopilotKitMisuseError({
318
- message: "Tool name must be a non-empty string for copilotkitEmitToolCall",
329
+ message:
330
+ "Tool name must be a non-empty string for copilotkitEmitToolCall",
319
331
  });
320
332
  }
321
333
 
@@ -338,7 +350,9 @@ export async function copilotkitEmitToolCall(
338
350
  }
339
351
  }
340
352
 
341
- export function convertActionToDynamicStructuredTool(actionInput: any): DynamicStructuredTool<any> {
353
+ export function convertActionToDynamicStructuredTool(
354
+ actionInput: any,
355
+ ): DynamicStructuredTool<any> {
342
356
  if (!actionInput) {
343
357
  throw new CopilotKitMisuseError({
344
358
  message: "Action input is required but was not provided",
package/tsconfig.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "extends": "../../utilities/tsconfig/base.json",
2
+ "extends": "../tsconfig/base.json",
3
3
  "compilerOptions": {
4
4
  "lib": ["es2017", "dom"],
5
5
  "emitDecoratorMetadata": true,
@@ -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, 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,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,SAAS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AAkBG,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"]}