@copilotkit/sdk-js 1.57.1-canary.1778272612 → 1.57.2

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.
@@ -0,0 +1,37 @@
1
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
+ let node_async_hooks = require("node:async_hooks");
3
+
4
+ //#region src/header-propagation.ts
5
+ const headerStorage = new node_async_hooks.AsyncLocalStorage();
6
+ /**
7
+ * Filter incoming headers to only x-* prefixed headers.
8
+ * Matches the CopilotKit runtime's extractForwardableHeaders() behavior.
9
+ */
10
+ function filterForwardableHeaders(headers) {
11
+ const filtered = {};
12
+ for (const [key, value] of Object.entries(headers)) {
13
+ const lower = key.toLowerCase();
14
+ if (lower.startsWith("x-")) filtered[lower] = value;
15
+ }
16
+ return filtered;
17
+ }
18
+ /**
19
+ * Run a callback with forwarded headers available via getForwardedHeaders().
20
+ * Call this at the AG-UI request entry point.
21
+ */
22
+ function withForwardedHeaders(headers, fn) {
23
+ return headerStorage.run(filterForwardableHeaders(headers), fn);
24
+ }
25
+ /**
26
+ * Get x-* prefixed headers that should be forwarded to outgoing LLM calls.
27
+ * Returns empty object when called outside a withForwardedHeaders() scope
28
+ * (demo traffic).
29
+ */
30
+ function getForwardedHeaders() {
31
+ return headerStorage.getStore() ?? {};
32
+ }
33
+
34
+ //#endregion
35
+ exports.getForwardedHeaders = getForwardedHeaders;
36
+ exports.withForwardedHeaders = withForwardedHeaders;
37
+ //# sourceMappingURL=header-propagation.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header-propagation.cjs","names":["AsyncLocalStorage"],"sources":["../src/header-propagation.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype HeaderMap = Record<string, string>;\n\nconst headerStorage = new AsyncLocalStorage<HeaderMap>();\n\n/**\n * Filter incoming headers to only x-* prefixed headers.\n * Matches the CopilotKit runtime's extractForwardableHeaders() behavior.\n */\nfunction filterForwardableHeaders(headers: HeaderMap): HeaderMap {\n const filtered: HeaderMap = {};\n for (const [key, value] of Object.entries(headers)) {\n const lower = key.toLowerCase();\n if (lower.startsWith(\"x-\")) {\n filtered[lower] = value;\n }\n }\n return filtered;\n}\n\n/**\n * Run a callback with forwarded headers available via getForwardedHeaders().\n * Call this at the AG-UI request entry point.\n */\nexport function withForwardedHeaders<T>(headers: HeaderMap, fn: () => T): T {\n return headerStorage.run(filterForwardableHeaders(headers), fn);\n}\n\n/**\n * Get x-* prefixed headers that should be forwarded to outgoing LLM calls.\n * Returns empty object when called outside a withForwardedHeaders() scope\n * (demo traffic).\n */\nexport function getForwardedHeaders(): HeaderMap {\n return headerStorage.getStore() ?? {};\n}\n"],"mappings":";;;;AAIA,MAAM,gBAAgB,IAAIA,oCAA8B;;;;;AAMxD,SAAS,yBAAyB,SAA+B;CAC/D,MAAM,WAAsB,EAAE;AAC9B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;EAClD,MAAM,QAAQ,IAAI,aAAa;AAC/B,MAAI,MAAM,WAAW,KAAK,CACxB,UAAS,SAAS;;AAGtB,QAAO;;;;;;AAOT,SAAgB,qBAAwB,SAAoB,IAAgB;AAC1E,QAAO,cAAc,IAAI,yBAAyB,QAAQ,EAAE,GAAG;;;;;;;AAQjE,SAAgB,sBAAiC;AAC/C,QAAO,cAAc,UAAU,IAAI,EAAE"}
@@ -0,0 +1,16 @@
1
+ //#region src/header-propagation.d.ts
2
+ type HeaderMap = Record<string, string>;
3
+ /**
4
+ * Run a callback with forwarded headers available via getForwardedHeaders().
5
+ * Call this at the AG-UI request entry point.
6
+ */
7
+ declare function withForwardedHeaders<T>(headers: HeaderMap, fn: () => T): T;
8
+ /**
9
+ * Get x-* prefixed headers that should be forwarded to outgoing LLM calls.
10
+ * Returns empty object when called outside a withForwardedHeaders() scope
11
+ * (demo traffic).
12
+ */
13
+ declare function getForwardedHeaders(): HeaderMap;
14
+ //#endregion
15
+ export { getForwardedHeaders, withForwardedHeaders };
16
+ //# sourceMappingURL=header-propagation.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header-propagation.d.cts","names":[],"sources":["../src/header-propagation.ts"],"mappings":";KAEK,SAAA,GAAY,MAAA;;;;;iBAuBD,oBAAA,GAAA,CAAwB,OAAA,EAAS,SAAA,EAAW,EAAA,QAAU,CAAA,GAAI,CAAA;AAA1E;;;;;AAAA,iBASgB,mBAAA,CAAA,GAAuB,SAAA"}
@@ -0,0 +1,16 @@
1
+ //#region src/header-propagation.d.ts
2
+ type HeaderMap = Record<string, string>;
3
+ /**
4
+ * Run a callback with forwarded headers available via getForwardedHeaders().
5
+ * Call this at the AG-UI request entry point.
6
+ */
7
+ declare function withForwardedHeaders<T>(headers: HeaderMap, fn: () => T): T;
8
+ /**
9
+ * Get x-* prefixed headers that should be forwarded to outgoing LLM calls.
10
+ * Returns empty object when called outside a withForwardedHeaders() scope
11
+ * (demo traffic).
12
+ */
13
+ declare function getForwardedHeaders(): HeaderMap;
14
+ //#endregion
15
+ export { getForwardedHeaders, withForwardedHeaders };
16
+ //# sourceMappingURL=header-propagation.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header-propagation.d.mts","names":[],"sources":["../src/header-propagation.ts"],"mappings":";KAEK,SAAA,GAAY,MAAA;;;;;iBAuBD,oBAAA,GAAA,CAAwB,OAAA,EAAS,SAAA,EAAW,EAAA,QAAU,CAAA,GAAI,CAAA;AAA1E;;;;;AAAA,iBASgB,mBAAA,CAAA,GAAuB,SAAA"}
@@ -0,0 +1,35 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ //#region src/header-propagation.ts
4
+ const headerStorage = new AsyncLocalStorage();
5
+ /**
6
+ * Filter incoming headers to only x-* prefixed headers.
7
+ * Matches the CopilotKit runtime's extractForwardableHeaders() behavior.
8
+ */
9
+ function filterForwardableHeaders(headers) {
10
+ const filtered = {};
11
+ for (const [key, value] of Object.entries(headers)) {
12
+ const lower = key.toLowerCase();
13
+ if (lower.startsWith("x-")) filtered[lower] = value;
14
+ }
15
+ return filtered;
16
+ }
17
+ /**
18
+ * Run a callback with forwarded headers available via getForwardedHeaders().
19
+ * Call this at the AG-UI request entry point.
20
+ */
21
+ function withForwardedHeaders(headers, fn) {
22
+ return headerStorage.run(filterForwardableHeaders(headers), fn);
23
+ }
24
+ /**
25
+ * Get x-* prefixed headers that should be forwarded to outgoing LLM calls.
26
+ * Returns empty object when called outside a withForwardedHeaders() scope
27
+ * (demo traffic).
28
+ */
29
+ function getForwardedHeaders() {
30
+ return headerStorage.getStore() ?? {};
31
+ }
32
+
33
+ //#endregion
34
+ export { getForwardedHeaders, withForwardedHeaders };
35
+ //# sourceMappingURL=header-propagation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header-propagation.mjs","names":[],"sources":["../src/header-propagation.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype HeaderMap = Record<string, string>;\n\nconst headerStorage = new AsyncLocalStorage<HeaderMap>();\n\n/**\n * Filter incoming headers to only x-* prefixed headers.\n * Matches the CopilotKit runtime's extractForwardableHeaders() behavior.\n */\nfunction filterForwardableHeaders(headers: HeaderMap): HeaderMap {\n const filtered: HeaderMap = {};\n for (const [key, value] of Object.entries(headers)) {\n const lower = key.toLowerCase();\n if (lower.startsWith(\"x-\")) {\n filtered[lower] = value;\n }\n }\n return filtered;\n}\n\n/**\n * Run a callback with forwarded headers available via getForwardedHeaders().\n * Call this at the AG-UI request entry point.\n */\nexport function withForwardedHeaders<T>(headers: HeaderMap, fn: () => T): T {\n return headerStorage.run(filterForwardableHeaders(headers), fn);\n}\n\n/**\n * Get x-* prefixed headers that should be forwarded to outgoing LLM calls.\n * Returns empty object when called outside a withForwardedHeaders() scope\n * (demo traffic).\n */\nexport function getForwardedHeaders(): HeaderMap {\n return headerStorage.getStore() ?? {};\n}\n"],"mappings":";;;AAIA,MAAM,gBAAgB,IAAI,mBAA8B;;;;;AAMxD,SAAS,yBAAyB,SAA+B;CAC/D,MAAM,WAAsB,EAAE;AAC9B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;EAClD,MAAM,QAAQ,IAAI,aAAa;AAC/B,MAAI,MAAM,WAAW,KAAK,CACxB,UAAS,SAAS;;AAGtB,QAAO;;;;;;AAOT,SAAgB,qBAAwB,SAAoB,IAAgB;AAC1E,QAAO,cAAc,IAAI,yBAAyB,QAAQ,EAAE,GAAG;;;;;;;AAQjE,SAAgB,sBAAiC;AAC/C,QAAO,cAAc,UAAU,IAAI,EAAE"}
package/dist/index.cjs CHANGED
@@ -0,0 +1,5 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_header_propagation = require('./header-propagation.cjs');
3
+
4
+ exports.getForwardedHeaders = require_header_propagation.getForwardedHeaders;
5
+ exports.withForwardedHeaders = require_header_propagation.withForwardedHeaders;
package/dist/index.d.cts CHANGED
@@ -1 +1,2 @@
1
- export { };
1
+ import { getForwardedHeaders, withForwardedHeaders } from "./header-propagation.cjs";
2
+ export { getForwardedHeaders, withForwardedHeaders };
package/dist/index.d.mts CHANGED
@@ -1 +1,2 @@
1
- export { };
1
+ import { getForwardedHeaders, withForwardedHeaders } from "./header-propagation.mjs";
2
+ export { getForwardedHeaders, withForwardedHeaders };
package/dist/index.mjs CHANGED
@@ -1 +1,3 @@
1
- export { };
1
+ import { getForwardedHeaders, withForwardedHeaders } from "./header-propagation.mjs";
2
+
3
+ export { getForwardedHeaders, withForwardedHeaders };
@@ -1,4 +1,5 @@
1
1
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
+ const require_header_propagation = require('../header-propagation.cjs');
2
3
  let langchain = require("langchain");
3
4
  let zod = require("zod");
4
5
  zod = require_runtime.__toESM(zod);
@@ -175,6 +176,21 @@ const buildMiddlewareInput = (exposeState) => ({
175
176
  stateSchema: copilotKitStateSchema,
176
177
  wrapModelCall: async (request, handler) => {
177
178
  request = applyStateNote(request, exposeState);
179
+ const forwardedHeaders = require_header_propagation.getForwardedHeaders();
180
+ if (Object.keys(forwardedHeaders).length > 0) {
181
+ const existingSettings = request.modelSettings ?? {};
182
+ const existingHeaders = existingSettings.headers ?? {};
183
+ request = {
184
+ ...request,
185
+ modelSettings: {
186
+ ...existingSettings,
187
+ headers: {
188
+ ...existingHeaders,
189
+ ...forwardedHeaders
190
+ }
191
+ }
192
+ };
193
+ }
178
194
  const frontendTools = request.state["copilotkit"]?.actions ?? [];
179
195
  if (frontendTools.length === 0) return handler(request);
180
196
  const mergedTools = [...request.tools || [], ...frontendTools];
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.cjs","names":["z","SystemMessage","AIMessage"],"sources":["../../src/langgraph/middleware.ts"],"sourcesContent":["import { createMiddleware, AIMessage, SystemMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\nimport * as z from \"zod\";\n\ntype WithJsonSchema<T> = T extends { \"~standard\": infer S }\n ? Omit<T, \"~standard\"> & {\n \"~standard\": S &\n StandardJSONSchemaV1.Props<\n S extends StandardSchemaV1.Props<infer I, any> ? I : unknown,\n S extends StandardSchemaV1.Props<any, infer O> ? O : unknown\n >;\n }\n : T;\n\n/**\n * Augment a Standard-Schema–compatible schema (e.g. Zod) with a\n * `~standard.jsonSchema.input` hook so LangGraph's\n * `getJsonSchemaFromSchema` (called from `StateSchema.getJsonSchema`)\n * can serialize the field.\n *\n * Without this, Zod v4 fields carry `~standard.validate` + `vendor` only,\n * and `isStandardJSONSchema()` returns false, so the field is silently\n * dropped from the graph's `output_schema`. That makes AG-UI\n * `STATE_SNAPSHOT` events filter the field out of the payload sent to\n * the frontend even though the underlying thread state has the value.\n *\n * Use this on any custom state field you want visible to the frontend\n * via `useAgent().state.*`.\n *\n * @example\n * ```ts\n * import { zodState } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const stateSchema = z.object({\n * todos: zodState(z.array(TodoSchema).default(() => [])),\n * });\n * ```\n */\nexport function zodState<T extends object>(schema: T): WithJsonSchema<T> {\n const std = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n if (std && typeof std === \"object\" && !(\"jsonSchema\" in std)) {\n let cached: Record<string, unknown> | undefined;\n std.jsonSchema = {\n input: () => {\n if (cached) return cached;\n // Prefer zod-v4's native `toJSONSchema` when available. Falls back to\n // an empty object, which is sufficient for the field to appear in the\n // graph's output_schema (langgraph-api treats it as an opaque field).\n try {\n const maybeV4ToJsonSchema = (\n z as unknown as {\n toJSONSchema?: (s: unknown) => Record<string, unknown>;\n }\n ).toJSONSchema;\n cached =\n typeof maybeV4ToJsonSchema === \"function\"\n ? maybeV4ToJsonSchema(schema)\n : {};\n } catch {\n cached = {};\n }\n return cached;\n },\n };\n }\n return schema as WithJsonSchema<T>;\n}\n\n/**\n * Internal/framework state keys that should never be auto-surfaced to the\n * LLM as user-facing state. These are reducer-managed message buckets,\n * CopilotKit/AG-UI plumbing, or graph-internal scaffolding.\n */\nconst RESERVED_STATE_KEYS: ReadonlySet<string> = new Set([\n \"messages\",\n \"copilotkit\",\n \"ag-ui\",\n \"tools\",\n \"structured_response\",\n \"thread_id\",\n \"remaining_steps\",\n]);\n\n/**\n * Controls how user-defined state keys are surfaced into the LLM prompt\n * on every model call. Off by default to avoid leaking arbitrary state\n * into prompts; opt in explicitly.\n *\n * - `false` (default) — never surface state.\n * - `true` — every state key not in the reserved internal set and not\n * prefixed with `_` is JSON-serialized into a \"Current agent state:\"\n * note appended to the system prompt.\n * - `string[]` — only surface the named keys (use this when you want\n * explicit control over what the LLM sees, e.g. `[\"liked\", \"todos\"]`).\n */\nexport type ExposeStateOption = boolean | readonly string[];\n\nconst buildStateNote = (\n state: Record<string, unknown>,\n expose: ExposeStateOption,\n): string | null => {\n if (expose === false) return null;\n\n const allow: ReadonlySet<string> | null = Array.isArray(expose)\n ? new Set(expose)\n : null;\n\n const snapshot: Record<string, unknown> = {};\n for (const key of Object.keys(state)) {\n if (\n allow\n ? !allow.has(key)\n : RESERVED_STATE_KEYS.has(key) || key.startsWith(\"_\")\n ) {\n continue;\n }\n const value = state[key];\n if (\n value === undefined ||\n value === null ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0) ||\n (typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value as Record<string, unknown>).length === 0)\n ) {\n continue;\n }\n snapshot[key] = value;\n }\n\n if (Object.keys(snapshot).length === 0) return null;\n\n let body: string;\n try {\n body = JSON.stringify(snapshot, null, 2);\n } catch {\n body = String(snapshot);\n }\n return `Current agent state:\\n${body}`;\n};\n\nconst applyStateNote = (request: any, expose: ExposeStateOption): any => {\n const note = buildStateNote(\n (request.state ?? {}) as Record<string, unknown>,\n expose,\n );\n if (!note) return request;\n\n const existing = request.systemPrompt;\n if (existing == null) {\n return { ...request, systemPrompt: new SystemMessage({ content: note }) };\n }\n // existing may be a string OR a SystemMessage\n const baseText =\n typeof existing === \"string\"\n ? existing\n : typeof existing.content === \"string\"\n ? existing.content\n : String(existing.content);\n return {\n ...request,\n systemPrompt: new SystemMessage({ content: `${baseText}\\n\\n${note}` }),\n };\n};\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: zodState(\n z\n .object({\n actions: z.array(z.any()),\n context: z.any().optional(),\n interceptedToolCalls: z.array(z.any()).optional(),\n originalAIMessageId: z.string().optional(),\n })\n .optional(),\n ),\n});\n\nconst buildMiddlewareInput = (exposeState: ExposeStateOption) => ({\n name: \"CopilotKitMiddleware\",\n\n stateSchema: copilotKitStateSchema as unknown as InteropZodObject,\n\n // Inject frontend tools and surface user state before model call\n wrapModelCall: async (request: any, handler: (req: any) => Promise<any>) => {\n request = applyStateNote(request, exposeState);\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});\n\n/**\n * Build a CopilotKit middleware instance with custom options.\n *\n * Use this when you want to override the default state-exposure behavior\n * (for example to hide a sensitive key, or to use an explicit allowlist).\n *\n * @example\n * ```typescript\n * import { createCopilotkitMiddleware } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const middleware = createCopilotkitMiddleware({\n * exposeState: [\"liked\", \"todos\"],\n * });\n * ```\n */\nexport const createCopilotkitMiddleware = (\n options: { exposeState?: ExposeStateOption } = {},\n) => {\n const exposeState = options.exposeState ?? false;\n return createMiddleware(buildMiddlewareInput(exposeState) as any);\n};\n\n/**\n * Default CopilotKit middleware singleton — does NOT surface user state\n * to the LLM. Pass `exposeState: true` (or an allowlist) to\n * {@link createCopilotkitMiddleware} to opt in.\n */\nexport const copilotkitMiddleware = createCopilotkitMiddleware();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,SAA2B,QAA8B;CACvE,MAAM,MAAO,OACX;AAEF,KAAI,OAAO,OAAO,QAAQ,YAAY,EAAE,gBAAgB,MAAM;EAC5D,IAAI;AACJ,MAAI,aAAa,EACf,aAAa;AACX,OAAI,OAAQ,QAAO;AAInB,OAAI;IACF,MAAM,sBACJA,IAGA;AACF,aACE,OAAO,wBAAwB,aAC3B,oBAAoB,OAAO,GAC3B,EAAE;WACF;AACN,aA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G,qBAAqB;KAC3D,IAAI,IAAI;KACT,CAAC;;AAEJ,UAAO;IACP;AAGF,MAAI,CAAC,cAAc;AACjB,WAAQ,KACN,8CAA8C,kBAAkB,wBACjE;AACD;;AAGF,SAAO;GACL,UAAU;GACV,YAAY;IACV,GAAG,MAAM;IACT,sBAAsB;IACtB,qBAAqB;IACtB;GACF;;CAIH,aAAa,UAAU;EACrB,MAAM,gBAAgB,MAAM,eAAe,WAAW,EAAE;AACxD,MAAI,cAAc,WAAW,EAAG;EAEhC,MAAM,oBAAoB,IAAI,IAC5B,cAAc,KAAK,MAAW,EAAE,UAAU,QAAQ,EAAE,KAAK,CAC1D;EAED,MAAM,cAAc,MAAM,SAAS,MAAM,SAAS,SAAS;AAC3D,MAAI,CAACA,oBAAU,WAAW,YAAY,IAAI,CAAC,YAAY,YAAY,OACjE;EAGF,MAAM,mBAA0B,EAAE;EAClC,MAAM,oBAA2B,EAAE;AAEnC,OAAK,MAAM,QAAQ,YAAY,WAC7B,KAAI,kBAAkB,IAAI,KAAK,KAAK,CAClC,mBAAkB,KAAK,KAAK;MAE5B,kBAAiB,KAAK,KAAK;AAI/B,MAAI,kBAAkB,WAAW,EAAG;EAEpC,MAAM,mBAAmB,IAAIA,oBAAU;GACrC,SAAS,YAAY;GACrB,YAAY;GACZ,IAAI,YAAY;GACjB,CAAC;AAEF,SAAO;GACL,UAAU,CAAC,GAAG,MAAM,SAAS,MAAM,GAAG,GAAG,EAAE,iBAAiB;GAC5D,YAAY;IACV,GAAG,MAAM;IACT,sBAAsB;IACtB,qBAAqB,YAAY;IAClC;GACF;;CAEJ;;;;;;;;;;;;;;;;AAiBD,MAAa,8BACX,UAA+C,EAAE,KAC9C;AAEH,wCAAwB,qBADJ,QAAQ,eAAe,MACc,CAAQ;;;;;;;AAQnE,MAAa,uBAAuB,4BAA4B"}
1
+ {"version":3,"file":"middleware.cjs","names":["z","SystemMessage","getForwardedHeaders","AIMessage"],"sources":["../../src/langgraph/middleware.ts"],"sourcesContent":["import { createMiddleware, AIMessage, SystemMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\nimport * as z from \"zod\";\nimport { getForwardedHeaders } from \"../header-propagation\";\n\ntype WithJsonSchema<T> = T extends { \"~standard\": infer S }\n ? Omit<T, \"~standard\"> & {\n \"~standard\": S &\n StandardJSONSchemaV1.Props<\n S extends StandardSchemaV1.Props<infer I, any> ? I : unknown,\n S extends StandardSchemaV1.Props<any, infer O> ? O : unknown\n >;\n }\n : T;\n\n/**\n * Augment a Standard-Schema–compatible schema (e.g. Zod) with a\n * `~standard.jsonSchema.input` hook so LangGraph's\n * `getJsonSchemaFromSchema` (called from `StateSchema.getJsonSchema`)\n * can serialize the field.\n *\n * Without this, Zod v4 fields carry `~standard.validate` + `vendor` only,\n * and `isStandardJSONSchema()` returns false, so the field is silently\n * dropped from the graph's `output_schema`. That makes AG-UI\n * `STATE_SNAPSHOT` events filter the field out of the payload sent to\n * the frontend even though the underlying thread state has the value.\n *\n * Use this on any custom state field you want visible to the frontend\n * via `useAgent().state.*`.\n *\n * @example\n * ```ts\n * import { zodState } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const stateSchema = z.object({\n * todos: zodState(z.array(TodoSchema).default(() => [])),\n * });\n * ```\n */\nexport function zodState<T extends object>(schema: T): WithJsonSchema<T> {\n const std = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n if (std && typeof std === \"object\" && !(\"jsonSchema\" in std)) {\n let cached: Record<string, unknown> | undefined;\n std.jsonSchema = {\n input: () => {\n if (cached) return cached;\n // Prefer zod-v4's native `toJSONSchema` when available. Falls back to\n // an empty object, which is sufficient for the field to appear in the\n // graph's output_schema (langgraph-api treats it as an opaque field).\n try {\n const maybeV4ToJsonSchema = (\n z as unknown as {\n toJSONSchema?: (s: unknown) => Record<string, unknown>;\n }\n ).toJSONSchema;\n cached =\n typeof maybeV4ToJsonSchema === \"function\"\n ? maybeV4ToJsonSchema(schema)\n : {};\n } catch {\n cached = {};\n }\n return cached;\n },\n };\n }\n return schema as WithJsonSchema<T>;\n}\n\n/**\n * Internal/framework state keys that should never be auto-surfaced to the\n * LLM as user-facing state. These are reducer-managed message buckets,\n * CopilotKit/AG-UI plumbing, or graph-internal scaffolding.\n */\nconst RESERVED_STATE_KEYS: ReadonlySet<string> = new Set([\n \"messages\",\n \"copilotkit\",\n \"ag-ui\",\n \"tools\",\n \"structured_response\",\n \"thread_id\",\n \"remaining_steps\",\n]);\n\n/**\n * Controls how user-defined state keys are surfaced into the LLM prompt\n * on every model call. Off by default to avoid leaking arbitrary state\n * into prompts; opt in explicitly.\n *\n * - `false` (default) — never surface state.\n * - `true` — every state key not in the reserved internal set and not\n * prefixed with `_` is JSON-serialized into a \"Current agent state:\"\n * note appended to the system prompt.\n * - `string[]` — only surface the named keys (use this when you want\n * explicit control over what the LLM sees, e.g. `[\"liked\", \"todos\"]`).\n */\nexport type ExposeStateOption = boolean | readonly string[];\n\nconst buildStateNote = (\n state: Record<string, unknown>,\n expose: ExposeStateOption,\n): string | null => {\n if (expose === false) return null;\n\n const allow: ReadonlySet<string> | null = Array.isArray(expose)\n ? new Set(expose)\n : null;\n\n const snapshot: Record<string, unknown> = {};\n for (const key of Object.keys(state)) {\n if (\n allow\n ? !allow.has(key)\n : RESERVED_STATE_KEYS.has(key) || key.startsWith(\"_\")\n ) {\n continue;\n }\n const value = state[key];\n if (\n value === undefined ||\n value === null ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0) ||\n (typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value as Record<string, unknown>).length === 0)\n ) {\n continue;\n }\n snapshot[key] = value;\n }\n\n if (Object.keys(snapshot).length === 0) return null;\n\n let body: string;\n try {\n body = JSON.stringify(snapshot, null, 2);\n } catch {\n body = String(snapshot);\n }\n return `Current agent state:\\n${body}`;\n};\n\nconst applyStateNote = (request: any, expose: ExposeStateOption): any => {\n const note = buildStateNote(\n (request.state ?? {}) as Record<string, unknown>,\n expose,\n );\n if (!note) return request;\n\n const existing = request.systemPrompt;\n if (existing == null) {\n return { ...request, systemPrompt: new SystemMessage({ content: note }) };\n }\n // existing may be a string OR a SystemMessage\n const baseText =\n typeof existing === \"string\"\n ? existing\n : typeof existing.content === \"string\"\n ? existing.content\n : String(existing.content);\n return {\n ...request,\n systemPrompt: new SystemMessage({ content: `${baseText}\\n\\n${note}` }),\n };\n};\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: zodState(\n z\n .object({\n actions: z.array(z.any()),\n context: z.any().optional(),\n interceptedToolCalls: z.array(z.any()).optional(),\n originalAIMessageId: z.string().optional(),\n })\n .optional(),\n ),\n});\n\nconst buildMiddlewareInput = (exposeState: ExposeStateOption) => ({\n name: \"CopilotKitMiddleware\",\n\n stateSchema: copilotKitStateSchema as unknown as InteropZodObject,\n\n // Inject frontend tools, surface user state, and forward x-aimock-* headers\n wrapModelCall: async (request: any, handler: (req: any) => Promise<any>) => {\n request = applyStateNote(request, exposeState);\n\n // Forward x-aimock-* headers from the incoming AG-UI request\n const forwardedHeaders = getForwardedHeaders();\n if (Object.keys(forwardedHeaders).length > 0) {\n const existingSettings = request.modelSettings ?? {};\n const existingHeaders =\n (existingSettings.headers as Record<string, string>) ?? {};\n request = {\n ...request,\n modelSettings: {\n ...existingSettings,\n headers: { ...existingHeaders, ...forwardedHeaders },\n },\n };\n }\n\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});\n\n/**\n * Build a CopilotKit middleware instance with custom options.\n *\n * Use this when you want to override the default state-exposure behavior\n * (for example to hide a sensitive key, or to use an explicit allowlist).\n *\n * @example\n * ```typescript\n * import { createCopilotkitMiddleware } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const middleware = createCopilotkitMiddleware({\n * exposeState: [\"liked\", \"todos\"],\n * });\n * ```\n */\nexport const createCopilotkitMiddleware = (\n options: { exposeState?: ExposeStateOption } = {},\n) => {\n const exposeState = options.exposeState ?? false;\n return createMiddleware(buildMiddlewareInput(exposeState) as any);\n};\n\n/**\n * Default CopilotKit middleware singleton — does NOT surface user state\n * to the LLM. Pass `exposeState: true` (or an allowlist) to\n * {@link createCopilotkitMiddleware} to opt in.\n */\nexport const copilotkitMiddleware = createCopilotkitMiddleware();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,SAA2B,QAA8B;CACvE,MAAM,MAAO,OACX;AAEF,KAAI,OAAO,OAAO,QAAQ,YAAY,EAAE,gBAAgB,MAAM;EAC5D,IAAI;AACJ,MAAI,aAAa,EACf,aAAa;AACX,OAAI,OAAQ,QAAO;AAInB,OAAI;IACF,MAAM,sBACJA,IAGA;AACF,aACE,OAAO,wBAAwB,aAC3B,oBAAoB,OAAO,GAC3B,EAAE;WACF;AACN,aAAS,EAAE;;AAEb,UAAO;KAEV;;AAEH,QAAO;;;;;;;AAQT,MAAM,sBAA2C,IAAI,IAAI;CACvD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAgBF,MAAM,kBACJ,OACA,WACkB;AAClB,KAAI,WAAW,MAAO,QAAO;CAE7B,M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"file":"middleware.d.cts","names":[],"sources":["../../src/langgraph/middleware.ts"],"mappings":";;;;;KAQK,cAAA,MAAoB,CAAA;EAAY,WAAA;AAAA,IACjC,IAAA,CAAK,CAAA;EACH,WAAA,EAAa,CAAA,GACX,oBAAA,CAAqB,KAAA,CACnB,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA,YACjD,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA;AAAA,IAGvD,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BY,QAAA,kBAAA,CAA2B,MAAA,EAAQ,CAAA,GAAI,cAAA,CAAe,CAAA;;;;;;;;;;;AAAtE;;KA2DY,iBAAA;;;;;;;;;;;;;AAAZ;;;cAmUa,0BAAA,GACX,OAAA;EAAW,WAAA,GAAc,iBAAA;AAAA,MAAwB,SAAA,CAAA,eAAA,0CAAP,sBAAA,CAAO,UAAA,GAAA,sBAAA,CAAA,UAAA;;;;;;cAWtC,oBAAA,EAAoB,SAAA,CAAA,eAAA,0CAA+B,sBAAA,CAA/B,UAAA,GAAA,sBAAA,CAAA,UAAA"}
1
+ {"version":3,"file":"middleware.d.cts","names":[],"sources":["../../src/langgraph/middleware.ts"],"mappings":";;;;;KASK,cAAA,MAAoB,CAAA;EAAY,WAAA;AAAA,IACjC,IAAA,CAAK,CAAA;EACH,WAAA,EAAa,CAAA,GACX,oBAAA,CAAqB,KAAA,CACnB,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA,YACjD,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA;AAAA,IAGvD,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BY,QAAA,kBAAA,CAA2B,MAAA,EAAQ,CAAA,GAAI,cAAA,CAAe,CAAA;;;;;;;;;;;AAAtE;;KA2DY,iBAAA;;;;;;;;;;;;;AAAZ;;;cAmVa,0BAAA,GACX,OAAA;EAAW,WAAA,GAAc,iBAAA;AAAA,MAAwB,SAAA,CAAA,eAAA,0CAAP,sBAAA,CAAO,UAAA,GAAA,sBAAA,CAAA,UAAA;;;;;;cAWtC,oBAAA,EAAoB,SAAA,CAAA,eAAA,0CAA+B,sBAAA,CAA/B,UAAA,GAAA,sBAAA,CAAA,UAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.mts","names":[],"sources":["../../src/langgraph/middleware.ts"],"mappings":";;;;;KAQK,cAAA,MAAoB,CAAA;EAAY,WAAA;AAAA,IACjC,IAAA,CAAK,CAAA;EACH,WAAA,EAAa,CAAA,GACX,oBAAA,CAAqB,KAAA,CACnB,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA,YACjD,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA;AAAA,IAGvD,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BY,QAAA,kBAAA,CAA2B,MAAA,EAAQ,CAAA,GAAI,cAAA,CAAe,CAAA;;;;;;;;;;;AAAtE;;KA2DY,iBAAA;;;;;;;;;;;;;AAAZ;;;cAmUa,0BAAA,GACX,OAAA;EAAW,WAAA,GAAc,iBAAA;AAAA,MAAwB,SAAA,CAAA,eAAA,0CAAP,sBAAA,CAAO,UAAA,GAAA,sBAAA,CAAA,UAAA;;;;;;cAWtC,oBAAA,EAAoB,SAAA,CAAA,eAAA,0CAA+B,sBAAA,CAA/B,UAAA,GAAA,sBAAA,CAAA,UAAA"}
1
+ {"version":3,"file":"middleware.d.mts","names":[],"sources":["../../src/langgraph/middleware.ts"],"mappings":";;;;;KASK,cAAA,MAAoB,CAAA;EAAY,WAAA;AAAA,IACjC,IAAA,CAAK,CAAA;EACH,WAAA,EAAa,CAAA,GACX,oBAAA,CAAqB,KAAA,CACnB,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA,YACjD,CAAA,SAAU,gBAAA,CAAiB,KAAA,iBAAsB,CAAA;AAAA,IAGvD,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BY,QAAA,kBAAA,CAA2B,MAAA,EAAQ,CAAA,GAAI,cAAA,CAAe,CAAA;;;;;;;;;;;AAAtE;;KA2DY,iBAAA;;;;;;;;;;;;;AAAZ;;;cAmVa,0BAAA,GACX,OAAA;EAAW,WAAA,GAAc,iBAAA;AAAA,MAAwB,SAAA,CAAA,eAAA,0CAAP,sBAAA,CAAO,UAAA,GAAA,sBAAA,CAAA,UAAA;;;;;;cAWtC,oBAAA,EAAoB,SAAA,CAAA,eAAA,0CAA+B,sBAAA,CAA/B,UAAA,GAAA,sBAAA,CAAA,UAAA"}
@@ -1,3 +1,4 @@
1
+ import { getForwardedHeaders } from "../header-propagation.mjs";
1
2
  import { AIMessage, SystemMessage, createMiddleware } from "langchain";
2
3
  import * as z from "zod";
3
4
 
@@ -173,6 +174,21 @@ const buildMiddlewareInput = (exposeState) => ({
173
174
  stateSchema: copilotKitStateSchema,
174
175
  wrapModelCall: async (request, handler) => {
175
176
  request = applyStateNote(request, exposeState);
177
+ const forwardedHeaders = getForwardedHeaders();
178
+ if (Object.keys(forwardedHeaders).length > 0) {
179
+ const existingSettings = request.modelSettings ?? {};
180
+ const existingHeaders = existingSettings.headers ?? {};
181
+ request = {
182
+ ...request,
183
+ modelSettings: {
184
+ ...existingSettings,
185
+ headers: {
186
+ ...existingHeaders,
187
+ ...forwardedHeaders
188
+ }
189
+ }
190
+ };
191
+ }
176
192
  const frontendTools = request.state["copilotkit"]?.actions ?? [];
177
193
  if (frontendTools.length === 0) return handler(request);
178
194
  const mergedTools = [...request.tools || [], ...frontendTools];
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/langgraph/middleware.ts"],"sourcesContent":["import { createMiddleware, AIMessage, SystemMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\nimport * as z from \"zod\";\n\ntype WithJsonSchema<T> = T extends { \"~standard\": infer S }\n ? Omit<T, \"~standard\"> & {\n \"~standard\": S &\n StandardJSONSchemaV1.Props<\n S extends StandardSchemaV1.Props<infer I, any> ? I : unknown,\n S extends StandardSchemaV1.Props<any, infer O> ? O : unknown\n >;\n }\n : T;\n\n/**\n * Augment a Standard-Schema–compatible schema (e.g. Zod) with a\n * `~standard.jsonSchema.input` hook so LangGraph's\n * `getJsonSchemaFromSchema` (called from `StateSchema.getJsonSchema`)\n * can serialize the field.\n *\n * Without this, Zod v4 fields carry `~standard.validate` + `vendor` only,\n * and `isStandardJSONSchema()` returns false, so the field is silently\n * dropped from the graph's `output_schema`. That makes AG-UI\n * `STATE_SNAPSHOT` events filter the field out of the payload sent to\n * the frontend even though the underlying thread state has the value.\n *\n * Use this on any custom state field you want visible to the frontend\n * via `useAgent().state.*`.\n *\n * @example\n * ```ts\n * import { zodState } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const stateSchema = z.object({\n * todos: zodState(z.array(TodoSchema).default(() => [])),\n * });\n * ```\n */\nexport function zodState<T extends object>(schema: T): WithJsonSchema<T> {\n const std = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n if (std && typeof std === \"object\" && !(\"jsonSchema\" in std)) {\n let cached: Record<string, unknown> | undefined;\n std.jsonSchema = {\n input: () => {\n if (cached) return cached;\n // Prefer zod-v4's native `toJSONSchema` when available. Falls back to\n // an empty object, which is sufficient for the field to appear in the\n // graph's output_schema (langgraph-api treats it as an opaque field).\n try {\n const maybeV4ToJsonSchema = (\n z as unknown as {\n toJSONSchema?: (s: unknown) => Record<string, unknown>;\n }\n ).toJSONSchema;\n cached =\n typeof maybeV4ToJsonSchema === \"function\"\n ? maybeV4ToJsonSchema(schema)\n : {};\n } catch {\n cached = {};\n }\n return cached;\n },\n };\n }\n return schema as WithJsonSchema<T>;\n}\n\n/**\n * Internal/framework state keys that should never be auto-surfaced to the\n * LLM as user-facing state. These are reducer-managed message buckets,\n * CopilotKit/AG-UI plumbing, or graph-internal scaffolding.\n */\nconst RESERVED_STATE_KEYS: ReadonlySet<string> = new Set([\n \"messages\",\n \"copilotkit\",\n \"ag-ui\",\n \"tools\",\n \"structured_response\",\n \"thread_id\",\n \"remaining_steps\",\n]);\n\n/**\n * Controls how user-defined state keys are surfaced into the LLM prompt\n * on every model call. Off by default to avoid leaking arbitrary state\n * into prompts; opt in explicitly.\n *\n * - `false` (default) — never surface state.\n * - `true` — every state key not in the reserved internal set and not\n * prefixed with `_` is JSON-serialized into a \"Current agent state:\"\n * note appended to the system prompt.\n * - `string[]` — only surface the named keys (use this when you want\n * explicit control over what the LLM sees, e.g. `[\"liked\", \"todos\"]`).\n */\nexport type ExposeStateOption = boolean | readonly string[];\n\nconst buildStateNote = (\n state: Record<string, unknown>,\n expose: ExposeStateOption,\n): string | null => {\n if (expose === false) return null;\n\n const allow: ReadonlySet<string> | null = Array.isArray(expose)\n ? new Set(expose)\n : null;\n\n const snapshot: Record<string, unknown> = {};\n for (const key of Object.keys(state)) {\n if (\n allow\n ? !allow.has(key)\n : RESERVED_STATE_KEYS.has(key) || key.startsWith(\"_\")\n ) {\n continue;\n }\n const value = state[key];\n if (\n value === undefined ||\n value === null ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0) ||\n (typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value as Record<string, unknown>).length === 0)\n ) {\n continue;\n }\n snapshot[key] = value;\n }\n\n if (Object.keys(snapshot).length === 0) return null;\n\n let body: string;\n try {\n body = JSON.stringify(snapshot, null, 2);\n } catch {\n body = String(snapshot);\n }\n return `Current agent state:\\n${body}`;\n};\n\nconst applyStateNote = (request: any, expose: ExposeStateOption): any => {\n const note = buildStateNote(\n (request.state ?? {}) as Record<string, unknown>,\n expose,\n );\n if (!note) return request;\n\n const existing = request.systemPrompt;\n if (existing == null) {\n return { ...request, systemPrompt: new SystemMessage({ content: note }) };\n }\n // existing may be a string OR a SystemMessage\n const baseText =\n typeof existing === \"string\"\n ? existing\n : typeof existing.content === \"string\"\n ? existing.content\n : String(existing.content);\n return {\n ...request,\n systemPrompt: new SystemMessage({ content: `${baseText}\\n\\n${note}` }),\n };\n};\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: zodState(\n z\n .object({\n actions: z.array(z.any()),\n context: z.any().optional(),\n interceptedToolCalls: z.array(z.any()).optional(),\n originalAIMessageId: z.string().optional(),\n })\n .optional(),\n ),\n});\n\nconst buildMiddlewareInput = (exposeState: ExposeStateOption) => ({\n name: \"CopilotKitMiddleware\",\n\n stateSchema: copilotKitStateSchema as unknown as InteropZodObject,\n\n // Inject frontend tools and surface user state before model call\n wrapModelCall: async (request: any, handler: (req: any) => Promise<any>) => {\n request = applyStateNote(request, exposeState);\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});\n\n/**\n * Build a CopilotKit middleware instance with custom options.\n *\n * Use this when you want to override the default state-exposure behavior\n * (for example to hide a sensitive key, or to use an explicit allowlist).\n *\n * @example\n * ```typescript\n * import { createCopilotkitMiddleware } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const middleware = createCopilotkitMiddleware({\n * exposeState: [\"liked\", \"todos\"],\n * });\n * ```\n */\nexport const createCopilotkitMiddleware = (\n options: { exposeState?: ExposeStateOption } = {},\n) => {\n const exposeState = options.exposeState ?? false;\n return createMiddleware(buildMiddlewareInput(exposeState) as any);\n};\n\n/**\n * Default CopilotKit middleware singleton — does NOT surface user state\n * to the LLM. Pass `exposeState: true` (or an allowlist) to\n * {@link createCopilotkitMiddleware} to opt in.\n */\nexport const copilotkitMiddleware = createCopilotkitMiddleware();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,SAA2B,QAA8B;CACvE,MAAM,MAAO,OACX;AAEF,KAAI,OAAO,OAAO,QAAQ,YAAY,EAAE,gBAAgB,MAAM;EAC5D,IAAI;AACJ,MAAI,aAAa,EACf,aAAa;AACX,OAAI,OAAQ,QAAO;AAInB,OAAI;IACF,MAAM,sBACJ,EAGA;AACF,aACE,OAAO,wBAAwB,aAC3B,oBAAoB,OAAO,GAC3B,EAAE;WACF;AACN,aAAS,EAAE;;AAEb,UAAO;KAEV;;AAEH,QAAO;;;;;;;AAQT,MAAM,sBAA2C,IAAI,IAAI;CACvD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAgBF,MAAM,kBACJ,OACA,WACkB;AAClB,KAAI,WAAW,MAAO,QAAO;CAE7B,MAAM,QAAoC,MAAM,QAAQ,OAAO,GAC3D,IAAI,IAAI,OAAO,GACf;CAEJ,MAAM,WAAoC,EAAE;AAC5C,MAAK,MAAM,OAAO,OAAO,KAAK,MAAM,EAAE;AACpC,MACE,QACI,CAAC,MAAM,IAAI,IAAI,GACf,oBAAoB,IAAI,IAAI,IAAI,IAAI,WAAW,IAAI,CAEvD;EAEF,MAAM,QAAQ,MAAM;AACpB,MACE,UAAU,UACV,UAAU,QACV,UAAU,MACT,MAAM,QAAQ,MAAM,IAAI,MAAM,WAAW,KACzC,OAAO,UAAU,YAChB,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAO,KAAK,MAAiC,CAAC,WAAW,EAE3D;AAEF,WAAS,OAAO;;AAGlB,KAAI,OAAO,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KAAK,KAAK;AAI/B,MAAI,kBAAkB,WAAW,EAAG;EAEpC,MAAM,mBAAmB,IAAI,UAAU;GACrC,SAAS,YAAY;GACrB,YAAY;GACZ,IAAI,YAAY;GACjB,CAAC;AAEF,SAAO;GACL,UAAU,CAAC,GAAG,MAAM,SAAS,MAAM,GAAG,GAAG,EAAE,iBAAiB;GAC5D,YAAY;IACV,GAAG,MAAM;IACT,sBAAsB;IACtB,qBAAqB,YAAY;IAClC;GACF;;CAEJ;;;;;;;;;;;;;;;;AAiBD,MAAa,8BACX,UAA+C,EAAE,KAC9C;AAEH,QAAO,iBAAiB,qBADJ,QAAQ,eAAe,MACc,CAAQ;;;;;;;AAQnE,MAAa,uBAAuB,4BAA4B"}
1
+ {"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/langgraph/middleware.ts"],"sourcesContent":["import { createMiddleware, AIMessage, SystemMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\nimport * as z from \"zod\";\nimport { getForwardedHeaders } from \"../header-propagation\";\n\ntype WithJsonSchema<T> = T extends { \"~standard\": infer S }\n ? Omit<T, \"~standard\"> & {\n \"~standard\": S &\n StandardJSONSchemaV1.Props<\n S extends StandardSchemaV1.Props<infer I, any> ? I : unknown,\n S extends StandardSchemaV1.Props<any, infer O> ? O : unknown\n >;\n }\n : T;\n\n/**\n * Augment a Standard-Schema–compatible schema (e.g. Zod) with a\n * `~standard.jsonSchema.input` hook so LangGraph's\n * `getJsonSchemaFromSchema` (called from `StateSchema.getJsonSchema`)\n * can serialize the field.\n *\n * Without this, Zod v4 fields carry `~standard.validate` + `vendor` only,\n * and `isStandardJSONSchema()` returns false, so the field is silently\n * dropped from the graph's `output_schema`. That makes AG-UI\n * `STATE_SNAPSHOT` events filter the field out of the payload sent to\n * the frontend even though the underlying thread state has the value.\n *\n * Use this on any custom state field you want visible to the frontend\n * via `useAgent().state.*`.\n *\n * @example\n * ```ts\n * import { zodState } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const stateSchema = z.object({\n * todos: zodState(z.array(TodoSchema).default(() => [])),\n * });\n * ```\n */\nexport function zodState<T extends object>(schema: T): WithJsonSchema<T> {\n const std = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n if (std && typeof std === \"object\" && !(\"jsonSchema\" in std)) {\n let cached: Record<string, unknown> | undefined;\n std.jsonSchema = {\n input: () => {\n if (cached) return cached;\n // Prefer zod-v4's native `toJSONSchema` when available. Falls back to\n // an empty object, which is sufficient for the field to appear in the\n // graph's output_schema (langgraph-api treats it as an opaque field).\n try {\n const maybeV4ToJsonSchema = (\n z as unknown as {\n toJSONSchema?: (s: unknown) => Record<string, unknown>;\n }\n ).toJSONSchema;\n cached =\n typeof maybeV4ToJsonSchema === \"function\"\n ? maybeV4ToJsonSchema(schema)\n : {};\n } catch {\n cached = {};\n }\n return cached;\n },\n };\n }\n return schema as WithJsonSchema<T>;\n}\n\n/**\n * Internal/framework state keys that should never be auto-surfaced to the\n * LLM as user-facing state. These are reducer-managed message buckets,\n * CopilotKit/AG-UI plumbing, or graph-internal scaffolding.\n */\nconst RESERVED_STATE_KEYS: ReadonlySet<string> = new Set([\n \"messages\",\n \"copilotkit\",\n \"ag-ui\",\n \"tools\",\n \"structured_response\",\n \"thread_id\",\n \"remaining_steps\",\n]);\n\n/**\n * Controls how user-defined state keys are surfaced into the LLM prompt\n * on every model call. Off by default to avoid leaking arbitrary state\n * into prompts; opt in explicitly.\n *\n * - `false` (default) — never surface state.\n * - `true` — every state key not in the reserved internal set and not\n * prefixed with `_` is JSON-serialized into a \"Current agent state:\"\n * note appended to the system prompt.\n * - `string[]` — only surface the named keys (use this when you want\n * explicit control over what the LLM sees, e.g. `[\"liked\", \"todos\"]`).\n */\nexport type ExposeStateOption = boolean | readonly string[];\n\nconst buildStateNote = (\n state: Record<string, unknown>,\n expose: ExposeStateOption,\n): string | null => {\n if (expose === false) return null;\n\n const allow: ReadonlySet<string> | null = Array.isArray(expose)\n ? new Set(expose)\n : null;\n\n const snapshot: Record<string, unknown> = {};\n for (const key of Object.keys(state)) {\n if (\n allow\n ? !allow.has(key)\n : RESERVED_STATE_KEYS.has(key) || key.startsWith(\"_\")\n ) {\n continue;\n }\n const value = state[key];\n if (\n value === undefined ||\n value === null ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0) ||\n (typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value as Record<string, unknown>).length === 0)\n ) {\n continue;\n }\n snapshot[key] = value;\n }\n\n if (Object.keys(snapshot).length === 0) return null;\n\n let body: string;\n try {\n body = JSON.stringify(snapshot, null, 2);\n } catch {\n body = String(snapshot);\n }\n return `Current agent state:\\n${body}`;\n};\n\nconst applyStateNote = (request: any, expose: ExposeStateOption): any => {\n const note = buildStateNote(\n (request.state ?? {}) as Record<string, unknown>,\n expose,\n );\n if (!note) return request;\n\n const existing = request.systemPrompt;\n if (existing == null) {\n return { ...request, systemPrompt: new SystemMessage({ content: note }) };\n }\n // existing may be a string OR a SystemMessage\n const baseText =\n typeof existing === \"string\"\n ? existing\n : typeof existing.content === \"string\"\n ? existing.content\n : String(existing.content);\n return {\n ...request,\n systemPrompt: new SystemMessage({ content: `${baseText}\\n\\n${note}` }),\n };\n};\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: zodState(\n z\n .object({\n actions: z.array(z.any()),\n context: z.any().optional(),\n interceptedToolCalls: z.array(z.any()).optional(),\n originalAIMessageId: z.string().optional(),\n })\n .optional(),\n ),\n});\n\nconst buildMiddlewareInput = (exposeState: ExposeStateOption) => ({\n name: \"CopilotKitMiddleware\",\n\n stateSchema: copilotKitStateSchema as unknown as InteropZodObject,\n\n // Inject frontend tools, surface user state, and forward x-aimock-* headers\n wrapModelCall: async (request: any, handler: (req: any) => Promise<any>) => {\n request = applyStateNote(request, exposeState);\n\n // Forward x-aimock-* headers from the incoming AG-UI request\n const forwardedHeaders = getForwardedHeaders();\n if (Object.keys(forwardedHeaders).length > 0) {\n const existingSettings = request.modelSettings ?? {};\n const existingHeaders =\n (existingSettings.headers as Record<string, string>) ?? {};\n request = {\n ...request,\n modelSettings: {\n ...existingSettings,\n headers: { ...existingHeaders, ...forwardedHeaders },\n },\n };\n }\n\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});\n\n/**\n * Build a CopilotKit middleware instance with custom options.\n *\n * Use this when you want to override the default state-exposure behavior\n * (for example to hide a sensitive key, or to use an explicit allowlist).\n *\n * @example\n * ```typescript\n * import { createCopilotkitMiddleware } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const middleware = createCopilotkitMiddleware({\n * exposeState: [\"liked\", \"todos\"],\n * });\n * ```\n */\nexport const createCopilotkitMiddleware = (\n options: { exposeState?: ExposeStateOption } = {},\n) => {\n const exposeState = options.exposeState ?? false;\n return createMiddleware(buildMiddlewareInput(exposeState) as any);\n};\n\n/**\n * Default CopilotKit middleware singleton — does NOT surface user state\n * to the LLM. Pass `exposeState: true` (or an allowlist) to\n * {@link createCopilotkitMiddleware} to opt in.\n */\nexport const copilotkitMiddleware = createCopilotkitMiddleware();\n"],"mappings":";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K;MAE5B,kBAAiB,KAAK,KAAK;AAI/B,MAAI,kBAAkB,WAAW,EAAG;EAEpC,MAAM,mBAAmB,IAAI,UAAU;GACrC,SAAS,YAAY;GACrB,YAAY;GACZ,IAAI,YAAY;GACjB,CAAC;AAEF,SAAO;GACL,UAAU,CAAC,GAAG,MAAM,SAAS,MAAM,GAAG,GAAG,EAAE,iBAAiB;GAC5D,YAAY;IACV,GAAG,MAAM;IACT,sBAAsB;IACtB,qBAAqB,YAAY;IAClC;GACF;;CAEJ;;;;;;;;;;;;;;;;AAiBD,MAAa,8BACX,UAA+C,EAAE,KAC9C;AAEH,QAAO,iBAAiB,qBADJ,QAAQ,eAAe,MACc,CAAQ;;;;;;;AAQnE,MAAa,uBAAuB,4BAA4B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/sdk-js",
3
- "version": "1.57.1-canary.1778272612",
3
+ "version": "1.57.2",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "ai",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@ag-ui/langgraph": "0.0.31",
52
- "@copilotkit/shared": "1.57.1-canary.1778272612"
52
+ "@copilotkit/shared": "1.57.2"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@langchain/core": "^1.1.41",
@@ -0,0 +1,131 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ withForwardedHeaders,
4
+ getForwardedHeaders,
5
+ } from "../header-propagation";
6
+
7
+ describe("header-propagation", () => {
8
+ describe("getForwardedHeaders", () => {
9
+ it("returns empty object when called outside withForwardedHeaders scope", () => {
10
+ const headers = getForwardedHeaders();
11
+ expect(headers).toEqual({});
12
+ });
13
+ });
14
+
15
+ describe("withForwardedHeaders", () => {
16
+ it("filters to only x-* prefixed headers", () => {
17
+ const input = {
18
+ "x-aimock-strict": "true",
19
+ "x-aimock-fixture": "demo",
20
+ "x-request-id": "req-123",
21
+ "x-custom-trace": "abc",
22
+ authorization: "Bearer secret",
23
+ "content-type": "application/json",
24
+ };
25
+
26
+ withForwardedHeaders(input, () => {
27
+ const forwarded = getForwardedHeaders();
28
+ expect(forwarded).toEqual({
29
+ "x-aimock-strict": "true",
30
+ "x-aimock-fixture": "demo",
31
+ "x-request-id": "req-123",
32
+ "x-custom-trace": "abc",
33
+ });
34
+ expect(forwarded).not.toHaveProperty("authorization");
35
+ expect(forwarded).not.toHaveProperty("content-type");
36
+ });
37
+ });
38
+
39
+ it("lowercases header keys", () => {
40
+ const input = {
41
+ "X-AIMock-Strict": "true",
42
+ "X-AIMOCK-FIXTURE": "demo",
43
+ };
44
+
45
+ withForwardedHeaders(input, () => {
46
+ const forwarded = getForwardedHeaders();
47
+ expect(forwarded).toEqual({
48
+ "x-aimock-strict": "true",
49
+ "x-aimock-fixture": "demo",
50
+ });
51
+ });
52
+ });
53
+
54
+ it("returns empty when no x-* headers present", () => {
55
+ const input = {
56
+ authorization: "Bearer token",
57
+ "content-type": "application/json",
58
+ };
59
+
60
+ withForwardedHeaders(input, () => {
61
+ const forwarded = getForwardedHeaders();
62
+ expect(forwarded).toEqual({});
63
+ });
64
+ });
65
+
66
+ it("returns the callback's return value", () => {
67
+ const result = withForwardedHeaders({}, () => 42);
68
+ expect(result).toBe(42);
69
+ });
70
+
71
+ it("restores empty state after scope exits", () => {
72
+ withForwardedHeaders({ "x-aimock-strict": "true" }, () => {
73
+ expect(getForwardedHeaders()).toEqual({ "x-aimock-strict": "true" });
74
+ });
75
+
76
+ // Outside the scope, should be empty again
77
+ expect(getForwardedHeaders()).toEqual({});
78
+ });
79
+ });
80
+
81
+ describe("AsyncLocalStorage isolation", () => {
82
+ it("maintains separate headers across concurrent requests", async () => {
83
+ const results: Record<string, string>[] = [];
84
+
85
+ const request1 = new Promise<void>((resolve) => {
86
+ withForwardedHeaders({ "x-aimock-strict": "true" }, () => {
87
+ // Simulate async work
88
+ setTimeout(() => {
89
+ results.push(getForwardedHeaders());
90
+ resolve();
91
+ }, 10);
92
+ });
93
+ });
94
+
95
+ const request2 = new Promise<void>((resolve) => {
96
+ withForwardedHeaders({ "x-aimock-fixture": "demo" }, () => {
97
+ // Simulate async work
98
+ setTimeout(() => {
99
+ results.push(getForwardedHeaders());
100
+ resolve();
101
+ }, 5);
102
+ });
103
+ });
104
+
105
+ await Promise.all([request1, request2]);
106
+
107
+ // Each request should have its own headers, regardless of timing
108
+ expect(results).toHaveLength(2);
109
+ const strictResult = results.find((r) => "x-aimock-strict" in r);
110
+ const fixtureResult = results.find((r) => "x-aimock-fixture" in r);
111
+ expect(strictResult).toEqual({ "x-aimock-strict": "true" });
112
+ expect(fixtureResult).toEqual({ "x-aimock-fixture": "demo" });
113
+ });
114
+
115
+ it("works with nested withForwardedHeaders calls", () => {
116
+ withForwardedHeaders({ "x-aimock-strict": "true" }, () => {
117
+ expect(getForwardedHeaders()).toEqual({ "x-aimock-strict": "true" });
118
+
119
+ // Inner scope overrides outer
120
+ withForwardedHeaders({ "x-aimock-fixture": "inner" }, () => {
121
+ expect(getForwardedHeaders()).toEqual({
122
+ "x-aimock-fixture": "inner",
123
+ });
124
+ });
125
+
126
+ // Back to outer scope
127
+ expect(getForwardedHeaders()).toEqual({ "x-aimock-strict": "true" });
128
+ });
129
+ });
130
+ });
131
+ });
@@ -0,0 +1,37 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ type HeaderMap = Record<string, string>;
4
+
5
+ const headerStorage = new AsyncLocalStorage<HeaderMap>();
6
+
7
+ /**
8
+ * Filter incoming headers to only x-* prefixed headers.
9
+ * Matches the CopilotKit runtime's extractForwardableHeaders() behavior.
10
+ */
11
+ function filterForwardableHeaders(headers: HeaderMap): HeaderMap {
12
+ const filtered: HeaderMap = {};
13
+ for (const [key, value] of Object.entries(headers)) {
14
+ const lower = key.toLowerCase();
15
+ if (lower.startsWith("x-")) {
16
+ filtered[lower] = value;
17
+ }
18
+ }
19
+ return filtered;
20
+ }
21
+
22
+ /**
23
+ * Run a callback with forwarded headers available via getForwardedHeaders().
24
+ * Call this at the AG-UI request entry point.
25
+ */
26
+ export function withForwardedHeaders<T>(headers: HeaderMap, fn: () => T): T {
27
+ return headerStorage.run(filterForwardableHeaders(headers), fn);
28
+ }
29
+
30
+ /**
31
+ * Get x-* prefixed headers that should be forwarded to outgoing LLM calls.
32
+ * Returns empty object when called outside a withForwardedHeaders() scope
33
+ * (demo traffic).
34
+ */
35
+ export function getForwardedHeaders(): HeaderMap {
36
+ return headerStorage.getStore() ?? {};
37
+ }
package/src/index.ts CHANGED
@@ -0,0 +1,4 @@
1
+ export {
2
+ withForwardedHeaders,
3
+ getForwardedHeaders,
4
+ } from "./header-propagation";
@@ -5,6 +5,7 @@ import type {
5
5
  StandardSchemaV1,
6
6
  } from "@standard-schema/spec";
7
7
  import * as z from "zod";
8
+ import { getForwardedHeaders } from "../header-propagation";
8
9
 
9
10
  type WithJsonSchema<T> = T extends { "~standard": infer S }
10
11
  ? Omit<T, "~standard"> & {
@@ -302,9 +303,25 @@ const buildMiddlewareInput = (exposeState: ExposeStateOption) => ({
302
303
 
303
304
  stateSchema: copilotKitStateSchema as unknown as InteropZodObject,
304
305
 
305
- // Inject frontend tools and surface user state before model call
306
+ // Inject frontend tools, surface user state, and forward x-aimock-* headers
306
307
  wrapModelCall: async (request: any, handler: (req: any) => Promise<any>) => {
307
308
  request = applyStateNote(request, exposeState);
309
+
310
+ // Forward x-aimock-* headers from the incoming AG-UI request
311
+ const forwardedHeaders = getForwardedHeaders();
312
+ if (Object.keys(forwardedHeaders).length > 0) {
313
+ const existingSettings = request.modelSettings ?? {};
314
+ const existingHeaders =
315
+ (existingSettings.headers as Record<string, string>) ?? {};
316
+ request = {
317
+ ...request,
318
+ modelSettings: {
319
+ ...existingSettings,
320
+ headers: { ...existingHeaders, ...forwardedHeaders },
321
+ },
322
+ };
323
+ }
324
+
308
325
  const frontendTools = request.state["copilotkit"]?.actions ?? [];
309
326
 
310
327
  if (frontendTools.length === 0) {