@copilotkit/sdk-js 2.0.0-next.1 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +0 -1
  3. package/dist/_virtual/_rolldown/runtime.cjs +29 -0
  4. package/dist/header-propagation.cjs +37 -0
  5. package/dist/header-propagation.cjs.map +1 -0
  6. package/dist/header-propagation.d.cts +16 -0
  7. package/dist/header-propagation.d.cts.map +1 -0
  8. package/dist/header-propagation.d.mts +16 -0
  9. package/dist/header-propagation.d.mts.map +1 -0
  10. package/dist/header-propagation.mjs +35 -0
  11. package/dist/header-propagation.mjs.map +1 -0
  12. package/dist/index.cjs +5 -0
  13. package/dist/index.d.cts +18 -0
  14. package/dist/index.d.mts +18 -0
  15. package/dist/index.mjs +3 -1
  16. package/dist/langchain.cjs +21 -0
  17. package/dist/langchain.cjs.map +1 -0
  18. package/dist/langchain.d.cts +139 -0
  19. package/dist/langchain.d.mts +140 -0
  20. package/dist/langchain.mjs +7 -23
  21. package/dist/langchain.mjs.map +1 -1
  22. package/dist/langgraph/middleware.cjs +433 -0
  23. package/dist/langgraph/middleware.cjs.map +1 -0
  24. package/dist/langgraph/middleware.d.cts +86 -0
  25. package/dist/langgraph/middleware.d.cts.map +1 -0
  26. package/dist/langgraph/middleware.d.mts +86 -0
  27. package/dist/langgraph/middleware.d.mts.map +1 -0
  28. package/dist/langgraph/middleware.mjs +429 -0
  29. package/dist/langgraph/middleware.mjs.map +1 -0
  30. package/dist/langgraph/state-schema.cjs +37 -0
  31. package/dist/langgraph/state-schema.cjs.map +1 -0
  32. package/dist/langgraph/state-schema.d.cts +118 -0
  33. package/dist/langgraph/state-schema.d.cts.map +1 -0
  34. package/dist/langgraph/state-schema.d.mts +118 -0
  35. package/dist/langgraph/state-schema.d.mts.map +1 -0
  36. package/dist/langgraph/state-schema.mjs +36 -0
  37. package/dist/langgraph/state-schema.mjs.map +1 -0
  38. package/dist/langgraph/types.cjs +60 -0
  39. package/dist/langgraph/types.cjs.map +1 -0
  40. package/dist/langgraph/types.d.cts +335 -0
  41. package/dist/langgraph/types.d.cts.map +1 -0
  42. package/dist/langgraph/types.d.mts +335 -0
  43. package/dist/langgraph/types.d.mts.map +1 -0
  44. package/dist/langgraph/types.mjs +57 -0
  45. package/dist/langgraph/types.mjs.map +1 -0
  46. package/dist/langgraph/utils.cjs +297 -0
  47. package/dist/langgraph/utils.cjs.map +1 -0
  48. package/dist/langgraph/utils.d.cts +209 -0
  49. package/dist/langgraph/utils.d.cts.map +1 -0
  50. package/dist/langgraph/utils.d.mts +209 -0
  51. package/dist/langgraph/utils.d.mts.map +1 -0
  52. package/dist/langgraph/utils.mjs +289 -0
  53. package/dist/langgraph/utils.mjs.map +1 -0
  54. package/dist/langgraph-middlewares.cjs +22 -0
  55. package/dist/langgraph-middlewares.d.cts +30 -0
  56. package/dist/langgraph-middlewares.d.mts +30 -0
  57. package/dist/langgraph-middlewares.mjs +5 -0
  58. package/dist/langgraph.cjs +21 -0
  59. package/dist/langgraph.d.cts +5 -0
  60. package/dist/langgraph.d.mts +5 -0
  61. package/dist/langgraph.mjs +6 -27
  62. package/package.json +50 -47
  63. package/src/__tests__/error-handling.test.ts +54 -20
  64. package/src/__tests__/header-propagation.test.ts +131 -0
  65. package/src/header-propagation.ts +61 -0
  66. package/src/index.ts +41 -0
  67. package/src/langchain.ts +168 -8
  68. package/src/langgraph/__tests__/middleware.a2ui-params.test.ts +139 -0
  69. package/src/langgraph/__tests__/middleware.native-a2ui.test.ts +118 -0
  70. package/src/langgraph/__tests__/middleware.properties.test.ts +357 -0
  71. package/src/langgraph/__tests__/middleware.test.ts +1141 -0
  72. package/src/langgraph/__tests__/state-schema.test.ts +85 -0
  73. package/src/langgraph/__tests__/utils.test.ts +363 -0
  74. package/src/langgraph/index.ts +1 -0
  75. package/src/langgraph/middleware.ts +698 -95
  76. package/src/langgraph/state-schema.ts +34 -0
  77. package/src/langgraph/types.ts +57 -0
  78. package/src/langgraph/utils.ts +76 -19
  79. package/src/langgraph-middlewares.ts +55 -0
  80. package/tsconfig.json +11 -2
  81. package/tsdown.config.ts +18 -0
  82. package/vitest.config.mjs +11 -0
  83. package/CHANGELOG.md +0 -2169
  84. package/dist/chunk-JLGOQLGS.mjs +0 -433
  85. package/dist/chunk-JLGOQLGS.mjs.map +0 -1
  86. package/dist/index.d.ts +0 -2
  87. package/dist/index.js +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/index.mjs.map +0 -1
  90. package/dist/langchain-2645763d.d.ts +0 -427
  91. package/dist/langchain.d.ts +0 -6
  92. package/dist/langchain.js +0 -284
  93. package/dist/langchain.js.map +0 -1
  94. package/dist/langgraph/index.d.ts +0 -11
  95. package/dist/langgraph.js +0 -476
  96. package/dist/langgraph.js.map +0 -1
  97. package/dist/langgraph.mjs.map +0 -1
  98. package/jest.config.js +0 -5
  99. package/tsup.config.ts +0 -23
@@ -0,0 +1,86 @@
1
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
2
+ import * as langchain from "langchain";
3
+ import { A2UIToolParams } from "@ag-ui/langgraph";
4
+ import { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
5
+
6
+ //#region src/langgraph/middleware.d.ts
7
+ type WithJsonSchema<T> = T extends {
8
+ "~standard": infer S;
9
+ } ? Omit<T, "~standard"> & {
10
+ "~standard": S & StandardJSONSchemaV1.Props<S extends StandardSchemaV1.Props<infer I, any> ? I : unknown, S extends StandardSchemaV1.Props<any, infer O> ? O : unknown>;
11
+ } : T;
12
+ /**
13
+ * Augment a Standard-Schema–compatible schema (e.g. Zod) with a
14
+ * `~standard.jsonSchema.input` hook so LangGraph's
15
+ * `getJsonSchemaFromSchema` (called from `StateSchema.getJsonSchema`)
16
+ * can serialize the field.
17
+ *
18
+ * Without this, Zod v4 fields carry `~standard.validate` + `vendor` only,
19
+ * and `isStandardJSONSchema()` returns false, so the field is silently
20
+ * dropped from the graph's `output_schema`. That makes AG-UI
21
+ * `STATE_SNAPSHOT` events filter the field out of the payload sent to
22
+ * the frontend even though the underlying thread state has the value.
23
+ *
24
+ * Use this on any custom state field you want visible to the frontend
25
+ * via `useAgent().state.*`.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * import { zodState } from "@copilotkit/sdk-js/langgraph";
30
+ *
31
+ * const stateSchema = z.object({
32
+ * todos: zodState(z.array(TodoSchema).default(() => [])),
33
+ * });
34
+ * ```
35
+ */
36
+ declare function zodState<T extends object>(schema: T): WithJsonSchema<T>;
37
+ /**
38
+ * Controls how user-defined state keys are surfaced into the LLM prompt
39
+ * on every model call. Off by default to avoid leaking arbitrary state
40
+ * into prompts; opt in explicitly.
41
+ *
42
+ * - `false` (default) — never surface state.
43
+ * - `true` — every state key not in the reserved internal set and not
44
+ * prefixed with `_` is JSON-serialized into a "Current agent state:"
45
+ * note appended to the system prompt.
46
+ * - `string[]` — only surface the named keys (use this when you want
47
+ * explicit control over what the LLM sees, e.g. `["liked", "todos"]`).
48
+ */
49
+ type ExposeStateOption = boolean | readonly string[];
50
+ /**
51
+ * Build a CopilotKit middleware instance with custom options.
52
+ *
53
+ * Use this when you want to override the default state-exposure behavior
54
+ * (for example to hide a sensitive key, or to use an explicit allowlist), or
55
+ * to steer the auto-injected `generate_a2ui` subagent via `a2uiParams`.
56
+ *
57
+ * `a2uiParams` is an `A2UIToolParams` without `model` (the middleware always
58
+ * injects the bound model). Use it to override the subagent guidelines
59
+ * (`generationGuidelines` / `designGuidelines` / `compositionGuide`),
60
+ * `defaultCatalogId`, `toolName`, `recovery`, etc. on the auto-inject path —
61
+ * which otherwise only ever uses the toolkit defaults. The registered catalog
62
+ * is still folded in, but host-set values win.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * import { createCopilotkitMiddleware } from "@copilotkit/sdk-js/langgraph";
67
+ *
68
+ * const middleware = createCopilotkitMiddleware({
69
+ * exposeState: ["liked", "todos"],
70
+ * a2uiParams: { guidelines: { designGuidelines: "...repeating-card layout..." } },
71
+ * });
72
+ * ```
73
+ */
74
+ declare const createCopilotkitMiddleware: (options?: {
75
+ exposeState?: ExposeStateOption;
76
+ a2uiParams?: Omit<A2UIToolParams, "model">;
77
+ }) => langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools0.ClientTool | _langchain_core_tools0.ServerTool)[]>;
78
+ /**
79
+ * Default CopilotKit middleware singleton — does NOT surface user state
80
+ * to the LLM. Pass `exposeState: true` (or an allowlist) to
81
+ * {@link createCopilotkitMiddleware} to opt in.
82
+ */
83
+ declare const copilotkitMiddleware: langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools0.ClientTool | _langchain_core_tools0.ServerTool)[]>;
84
+ //#endregion
85
+ export { ExposeStateOption, copilotkitMiddleware, createCopilotkitMiddleware, zodState };
86
+ //# sourceMappingURL=middleware.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.mts","names":[],"sources":["../../src/langgraph/middleware.ts"],"mappings":";;;;;;KAwHK,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;;;;;AAogBA;;;;;;;cAAa,0BAAA,GACX,OAAA;EACE,WAAA,GAAc,iBAAA;EACd,UAAA,GAAa,IAAA,CAAK,cAAA;AAAA,MACd,SAAA,CAAA,eAAA,0CADa,sBAAA,CACb,UAAA,GAAA,sBAAA,CAAA,UAAA;;;;;;cAaK,oBAAA,EAAoB,SAAA,CAAA,eAAA,0CAA+B,sBAAA,CAA/B,UAAA,GAAA,sBAAA,CAAA,UAAA"}
@@ -0,0 +1,429 @@
1
+ import { getForwardedHeaders } from "../header-propagation.mjs";
2
+ import { AIMessage, createMiddleware } from "langchain";
3
+ import * as z from "zod";
4
+ import { getA2UITools } from "@ag-ui/langgraph";
5
+
6
+ //#region src/langgraph/middleware.ts
7
+ const a2uiToolsByThread = /* @__PURE__ */ new Map();
8
+ const A2UI_DEFAULT_THREAD_KEY = "__copilotkit_a2ui_default__";
9
+ const a2uiThreadKey = (state) => state?.thread_id || A2UI_DEFAULT_THREAD_KEY;
10
+ /**
11
+ * Merge AG-UI defaults with CopilotKit overrides. Dictionaries recurse; every
12
+ * conflicting leaf uses CopilotKit, including false, null and empty values.
13
+ * Arrays and serialized strings are atomic: no positional pairing or decoding.
14
+ */
15
+ const isPropertyBag = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
16
+ const mergeProperties = (base, overrides) => Object.fromEntries(Array.from(new Set([...Object.keys(base), ...Object.keys(overrides)])).map((key) => {
17
+ return [key, Object.prototype.hasOwnProperty.call(overrides, key) ? isPropertyBag(base[key]) && isPropertyBag(overrides[key]) ? mergeProperties(base[key], overrides[key]) : overrides[key] : base[key]];
18
+ }));
19
+ const effectiveProperties = (state) => {
20
+ const source = isPropertyBag(state) ? state : {};
21
+ return mergeProperties(isPropertyBag(source["ag-ui"]) ? source["ag-ui"] : {}, isPropertyBag(source.copilotkit) ? source.copilotkit : {});
22
+ };
23
+ const decodeCatalogValue = (value) => {
24
+ if (typeof value !== "string") return value;
25
+ try {
26
+ return JSON.parse(value);
27
+ } catch {
28
+ return value;
29
+ }
30
+ };
31
+ /**
32
+ * Find the frontend-registered A2UI catalog wherever it was passed. Returns
33
+ * `{ compositionGuide?, catalogId? }` when a catalog is present, else `null`
34
+ * independently of the explicit tool-injection decision. Two
35
+ * delivery paths, depending on how the agent is served:
36
+ * - AG-UI native endpoint → `state["ag-ui"].a2ui_schema` (JSON
37
+ * `{ catalogId, components }`); the toolkit reads it from state itself.
38
+ * - Runtime proxy → an effective `context` entry describing
39
+ * the A2UI catalog (catalog id + component schemas as text), passed to the
40
+ * subagent via `compositionGuide`.
41
+ * `catalogId` binds generated surfaces to the frontend's catalog so BYOC
42
+ * custom catalogs render their own components (not the basic one).
43
+ */
44
+ const resolveA2uiCatalog = (state) => {
45
+ const properties = effectiveProperties(state);
46
+ const a2uiSchema = properties.a2ui_schema;
47
+ if (a2uiSchema) {
48
+ let catalogId;
49
+ try {
50
+ catalogId = (typeof a2uiSchema === "string" ? JSON.parse(a2uiSchema) : a2uiSchema)?.catalogId;
51
+ } catch {}
52
+ return { catalogId };
53
+ }
54
+ const context = decodeCatalogValue(properties.context);
55
+ for (const entry of Array.isArray(context) ? context : []) {
56
+ const description = entry?.description;
57
+ const value = decodeCatalogValue(entry?.value);
58
+ if (typeof description !== "string" || typeof value !== "string" || !description.includes("A2UI catalog") || !value) continue;
59
+ return {
60
+ compositionGuide: value,
61
+ catalogId: /^\s*-\s+(\S+)/m.exec(value)?.[1]
62
+ };
63
+ }
64
+ return null;
65
+ };
66
+ /**
67
+ * The A2UI `injectA2UITool` decision. The `@ag-ui/a2ui-middleware` forwards it on
68
+ * `forwardedProps`, which `ag-ui-langgraph` surfaces into agent state at
69
+ * `state["ag-ui"].inject_a2ui_tool` — present only when the host turned the
70
+ * runtime A2UI tool on (truthy or a custom tool-name string). `undefined` means
71
+ * no signal (off, or no A2UI middleware in the pipeline) → no auto-injection.
72
+ */
73
+ const a2uiInjectDecision = (state) => effectiveProperties(state).inject_a2ui_tool;
74
+ /**
75
+ * Augment a Standard-Schema–compatible schema (e.g. Zod) with a
76
+ * `~standard.jsonSchema.input` hook so LangGraph's
77
+ * `getJsonSchemaFromSchema` (called from `StateSchema.getJsonSchema`)
78
+ * can serialize the field.
79
+ *
80
+ * Without this, Zod v4 fields carry `~standard.validate` + `vendor` only,
81
+ * and `isStandardJSONSchema()` returns false, so the field is silently
82
+ * dropped from the graph's `output_schema`. That makes AG-UI
83
+ * `STATE_SNAPSHOT` events filter the field out of the payload sent to
84
+ * the frontend even though the underlying thread state has the value.
85
+ *
86
+ * Use this on any custom state field you want visible to the frontend
87
+ * via `useAgent().state.*`.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { zodState } from "@copilotkit/sdk-js/langgraph";
92
+ *
93
+ * const stateSchema = z.object({
94
+ * todos: zodState(z.array(TodoSchema).default(() => [])),
95
+ * });
96
+ * ```
97
+ */
98
+ function zodState(schema) {
99
+ const std = schema["~standard"];
100
+ if (std && typeof std === "object" && !("jsonSchema" in std)) {
101
+ let cached;
102
+ std.jsonSchema = { input: () => {
103
+ if (cached) return cached;
104
+ try {
105
+ const maybeV4ToJsonSchema = z.toJSONSchema;
106
+ cached = typeof maybeV4ToJsonSchema === "function" ? maybeV4ToJsonSchema(schema) : {};
107
+ } catch {
108
+ cached = {};
109
+ }
110
+ return cached;
111
+ } };
112
+ }
113
+ return schema;
114
+ }
115
+ /**
116
+ * Internal/framework state keys that should never be auto-surfaced to the
117
+ * LLM as user-facing state. These are reducer-managed message buckets,
118
+ * CopilotKit/AG-UI plumbing, or graph-internal scaffolding.
119
+ */
120
+ const RESERVED_STATE_KEYS = new Set([
121
+ "messages",
122
+ "copilotkit",
123
+ "ag-ui",
124
+ "tools",
125
+ "structured_response",
126
+ "thread_id",
127
+ "remaining_steps"
128
+ ]);
129
+ const buildStateNote = (state, expose) => {
130
+ if (expose === false) return null;
131
+ const allow = Array.isArray(expose) ? new Set(expose) : null;
132
+ const snapshot = {};
133
+ for (const key of Object.keys(state)) {
134
+ if (allow ? !allow.has(key) : RESERVED_STATE_KEYS.has(key) || key.startsWith("_")) continue;
135
+ const value = state[key];
136
+ if (value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 || typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue;
137
+ snapshot[key] = value;
138
+ }
139
+ if (Object.keys(snapshot).length === 0) return null;
140
+ let body;
141
+ try {
142
+ body = JSON.stringify(snapshot, null, 2);
143
+ } catch {
144
+ body = String(snapshot);
145
+ }
146
+ return `Current agent state:\n${body}`;
147
+ };
148
+ const appendSystemNote = (request, note) => {
149
+ const existingMessage = request.systemMessage;
150
+ if (existingMessage != null) {
151
+ const separator = existingMessage.text === "" ? "" : "\n\n";
152
+ return {
153
+ ...request,
154
+ systemMessage: existingMessage.concat(`${separator}${note}`)
155
+ };
156
+ }
157
+ const existing = request.systemPrompt;
158
+ if (existing == null) return {
159
+ ...request,
160
+ systemPrompt: note
161
+ };
162
+ const baseText = typeof existing === "string" ? existing : typeof existing.content === "string" ? existing.content : String(existing.content);
163
+ return {
164
+ ...request,
165
+ systemPrompt: `${baseText}\n\n${note}`
166
+ };
167
+ };
168
+ const applyStateNote = (request, expose) => {
169
+ const note = buildStateNote(request.state ?? {}, expose);
170
+ return note ? appendSystemNote(request, note) : request;
171
+ };
172
+ const APP_CONTEXT_PREFIX = "App Context:\n";
173
+ const runtimeCarrierProperties = (carrier, namespace) => {
174
+ if (!isPropertyBag(carrier)) return {};
175
+ const nested = carrier[namespace];
176
+ if (isPropertyBag(nested) && Object.keys(nested).length > 0) return nested;
177
+ if (namespace === "copilotkit" && ("actions" in carrier || "context" in carrier)) return carrier;
178
+ return {};
179
+ };
180
+ const BOOKKEEPING_KEYS = new Set(["interceptedToolCalls", "originalAIMessageId"]);
181
+ const definedProperties = (value) => isPropertyBag(value) ? Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0)) : {};
182
+ const contextNamespace = (state, runtimeContext, namespace) => {
183
+ const fromState = definedProperties(isPropertyBag(state) ? state[namespace] : void 0);
184
+ return Object.keys(fromState).some((key) => !BOOKKEEPING_KEYS.has(key)) ? fromState : definedProperties(runtimeCarrierProperties(runtimeContext, namespace));
185
+ };
186
+ const buildAppContextNote = (state, runtimeContext) => {
187
+ const properties = mergeProperties(contextNamespace(state, runtimeContext, "ag-ui"), contextNamespace(state, runtimeContext, "copilotkit"));
188
+ const appContext = isPropertyBag(properties.context) ? Object.fromEntries(Object.entries(properties.context).filter(([key]) => key !== "copilotkit_forwarded_headers")) : properties.context;
189
+ if (!appContext || typeof appContext === "string" && appContext.trim() === "" || typeof appContext === "object" && Object.keys(appContext).length === 0) return null;
190
+ return `${APP_CONTEXT_PREFIX}${typeof appContext === "string" ? appContext : JSON.stringify(appContext, null, 2)}`;
191
+ };
192
+ const isAppContextMessage = (msg) => {
193
+ const type = msg?._getType?.();
194
+ if (type !== "system" && type !== "developer") return false;
195
+ const content = typeof msg.content === "string" ? msg.content : msg.content?.[0]?.text;
196
+ return typeof content === "string" && content.startsWith(APP_CONTEXT_PREFIX);
197
+ };
198
+ const applyAppContextNote = (request) => {
199
+ const messages = request.messages ?? [];
200
+ const keptMessages = messages.filter((msg) => !isAppContextMessage(msg));
201
+ if (keptMessages.length !== messages.length) request = {
202
+ ...request,
203
+ messages: keptMessages
204
+ };
205
+ const note = buildAppContextNote(request.state, request.runtime?.context);
206
+ return note ? appendSystemNote(request, note) : request;
207
+ };
208
+ /**
209
+ * CopilotKit Middleware for LangGraph agents.
210
+ *
211
+ * Enables:
212
+ * - Dynamic frontend tools from state.tools
213
+ * - Context provided from CopilotKit useCopilotReadable
214
+ *
215
+ * Works with any agent (prebuilt or custom).
216
+ *
217
+ * @example
218
+ * ```typescript
219
+ * import { createAgent } from "langchain";
220
+ * import { copilotkitMiddleware } from "@copilotkit/sdk-js/langgraph";
221
+ *
222
+ * const agent = createAgent({
223
+ * model: "gpt-4o",
224
+ * tools: [backendTool],
225
+ * middleware: [copilotkitMiddleware],
226
+ * });
227
+ * ```
228
+ */
229
+ const copilotKitStateSchema = z.object({
230
+ "ag-ui": zodState(z.record(z.string(), z.unknown()).optional()),
231
+ copilotkit: zodState(z.object({
232
+ actions: z.union([z.array(z.any()), z.literal(false)]).nullable().optional(),
233
+ context: z.any().optional(),
234
+ interceptedToolCalls: z.array(z.any()).optional(),
235
+ originalAIMessageId: z.string().optional()
236
+ }).passthrough().optional())
237
+ }).passthrough();
238
+ const isToolCallContentBlock = (block) => typeof block === "object" && block !== null && "type" in block && (block.type === "tool_call" || block.type === "tool_call_chunk");
239
+ const usesV1ContentBlocks = (responseMetadata) => typeof responseMetadata === "object" && responseMetadata !== null && "output_version" in responseMetadata && responseMetadata.output_version === "v1";
240
+ /**
241
+ * Rebuilds an AIMessage with `toolCalls` as the source of truth while
242
+ * preserving its non-tool content and metadata. For v1 content blocks, old
243
+ * tool blocks must be removed before construction so they cannot duplicate or
244
+ * override the supplied tool calls when AIMessage synchronizes both fields.
245
+ */
246
+ const rebuildAIMessageWithToolCalls = (message, toolCalls) => {
247
+ let content = message.content;
248
+ if (usesV1ContentBlocks(message.response_metadata) && Array.isArray(content)) content = content.filter((block) => !isToolCallContentBlock(block));
249
+ return new AIMessage({
250
+ content,
251
+ additional_kwargs: message.additional_kwargs,
252
+ response_metadata: message.response_metadata,
253
+ tool_calls: toolCalls,
254
+ invalid_tool_calls: message.invalid_tool_calls,
255
+ usage_metadata: message.usage_metadata,
256
+ id: message.id,
257
+ name: message.name
258
+ });
259
+ };
260
+ const buildMiddlewareInput = (exposeState, a2uiParams) => ({
261
+ name: "CopilotKitMiddleware",
262
+ stateSchema: copilotKitStateSchema,
263
+ wrapModelCall: async (request, handler) => {
264
+ request = applyStateNote(request, exposeState);
265
+ request = applyAppContextNote(request);
266
+ const forwardedHeaders = getForwardedHeaders();
267
+ if (Object.keys(forwardedHeaders).length > 0) {
268
+ const existingSettings = request.modelSettings ?? {};
269
+ const existingHeaders = existingSettings.headers ?? {};
270
+ request = {
271
+ ...request,
272
+ modelSettings: {
273
+ ...existingSettings,
274
+ headers: {
275
+ ...existingHeaders,
276
+ ...forwardedHeaders
277
+ }
278
+ }
279
+ };
280
+ }
281
+ let a2uiTool = null;
282
+ const decision = a2uiInjectDecision(request.state);
283
+ if (typeof getA2UITools === "function" && decision) {
284
+ const catalog = resolveA2uiCatalog(request.state);
285
+ const params = {
286
+ ...a2uiParams,
287
+ model: request.model
288
+ };
289
+ if (catalog?.catalogId && params.defaultCatalogId == null) params.defaultCatalogId = catalog.catalogId;
290
+ if (catalog?.compositionGuide) {
291
+ const guidelines = { ...params.guidelines };
292
+ if (guidelines.compositionGuide == null) guidelines.compositionGuide = catalog.compositionGuide;
293
+ params.guidelines = guidelines;
294
+ }
295
+ const candidate = getA2UITools(params);
296
+ if (!new Set((request.tools || []).map((t) => t?.name)).has(candidate.name)) {
297
+ const invoke = candidate.invoke.bind(candidate);
298
+ candidate.invoke = (input, config) => {
299
+ const state = config && "state" in config && isPropertyBag(config.state) ? config.state : request.state;
300
+ const properties = effectiveProperties(state);
301
+ const schema = properties.a2ui_schema;
302
+ const context = decodeCatalogValue(properties.context);
303
+ return invoke(input, {
304
+ ...config,
305
+ state: {
306
+ ...state,
307
+ "ag-ui": {
308
+ ...properties,
309
+ context: Array.isArray(context) ? context : [],
310
+ a2ui_schema: isPropertyBag(schema) ? JSON.stringify(schema) : schema
311
+ }
312
+ }
313
+ });
314
+ };
315
+ a2uiTool = candidate;
316
+ a2uiToolsByThread.set(a2uiThreadKey(request.state), a2uiTool);
317
+ }
318
+ }
319
+ const actions = effectiveProperties(request.state).actions;
320
+ let frontendTools = Array.isArray(actions) ? actions : [];
321
+ if (a2uiTool) {
322
+ const drop = typeof decision === "string" ? decision : "render_a2ui";
323
+ frontendTools = frontendTools.filter((t) => (t?.function?.name ?? t?.name) !== drop);
324
+ }
325
+ if (frontendTools.length === 0 && !a2uiTool) return handler(request);
326
+ const mergedTools = [
327
+ ...request.tools || [],
328
+ ...a2uiTool ? [a2uiTool] : [],
329
+ ...frontendTools
330
+ ];
331
+ return handler({
332
+ ...request,
333
+ tools: mergedTools
334
+ });
335
+ },
336
+ wrapToolCall: async (request, handler) => {
337
+ const tool = a2uiToolsByThread.get(a2uiThreadKey(request.state));
338
+ if (tool && !request.tool && request.toolCall?.name === tool.name) return handler({
339
+ ...request,
340
+ tool
341
+ });
342
+ return handler(request);
343
+ },
344
+ afterAgent: (state) => {
345
+ a2uiToolsByThread.delete(a2uiThreadKey(state));
346
+ const interceptedToolCalls = state["copilotkit"]?.interceptedToolCalls;
347
+ const originalMessageId = state["copilotkit"]?.originalAIMessageId;
348
+ if (!interceptedToolCalls?.length || !originalMessageId) return;
349
+ let messageFound = false;
350
+ const updatedMessages = state.messages.map((msg) => {
351
+ if (AIMessage.isInstance(msg) && msg.id === originalMessageId) {
352
+ messageFound = true;
353
+ return rebuildAIMessageWithToolCalls(msg, [...msg.tool_calls || [], ...interceptedToolCalls]);
354
+ }
355
+ return msg;
356
+ });
357
+ if (!messageFound) {
358
+ console.warn(`CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`);
359
+ return;
360
+ }
361
+ return {
362
+ messages: updatedMessages,
363
+ copilotkit: {
364
+ ...state["copilotkit"],
365
+ interceptedToolCalls: void 0,
366
+ originalAIMessageId: void 0
367
+ }
368
+ };
369
+ },
370
+ afterModel: (state) => {
371
+ const actions = effectiveProperties(state).actions;
372
+ const frontendTools = Array.isArray(actions) ? actions : [];
373
+ if (frontendTools.length === 0) return;
374
+ const frontendToolNames = new Set(frontendTools.map((t) => t.function?.name || t.name));
375
+ const lastMessage = state.messages[state.messages.length - 1];
376
+ if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls?.length) return;
377
+ const backendToolCalls = [];
378
+ const frontendToolCalls = [];
379
+ for (const call of lastMessage.tool_calls) if (frontendToolNames.has(call.name)) frontendToolCalls.push(call);
380
+ else backendToolCalls.push(call);
381
+ if (frontendToolCalls.length === 0) return;
382
+ const updatedAIMessage = rebuildAIMessageWithToolCalls(lastMessage, backendToolCalls);
383
+ return {
384
+ messages: [...state.messages.slice(0, -1), updatedAIMessage],
385
+ copilotkit: {
386
+ ...state["copilotkit"],
387
+ interceptedToolCalls: frontendToolCalls,
388
+ originalAIMessageId: lastMessage.id
389
+ }
390
+ };
391
+ }
392
+ });
393
+ /**
394
+ * Build a CopilotKit middleware instance with custom options.
395
+ *
396
+ * Use this when you want to override the default state-exposure behavior
397
+ * (for example to hide a sensitive key, or to use an explicit allowlist), or
398
+ * to steer the auto-injected `generate_a2ui` subagent via `a2uiParams`.
399
+ *
400
+ * `a2uiParams` is an `A2UIToolParams` without `model` (the middleware always
401
+ * injects the bound model). Use it to override the subagent guidelines
402
+ * (`generationGuidelines` / `designGuidelines` / `compositionGuide`),
403
+ * `defaultCatalogId`, `toolName`, `recovery`, etc. on the auto-inject path —
404
+ * which otherwise only ever uses the toolkit defaults. The registered catalog
405
+ * is still folded in, but host-set values win.
406
+ *
407
+ * @example
408
+ * ```typescript
409
+ * import { createCopilotkitMiddleware } from "@copilotkit/sdk-js/langgraph";
410
+ *
411
+ * const middleware = createCopilotkitMiddleware({
412
+ * exposeState: ["liked", "todos"],
413
+ * a2uiParams: { guidelines: { designGuidelines: "...repeating-card layout..." } },
414
+ * });
415
+ * ```
416
+ */
417
+ const createCopilotkitMiddleware = (options = {}) => {
418
+ return createMiddleware(buildMiddlewareInput(options.exposeState ?? false, options.a2uiParams));
419
+ };
420
+ /**
421
+ * Default CopilotKit middleware singleton — does NOT surface user state
422
+ * to the LLM. Pass `exposeState: true` (or an allowlist) to
423
+ * {@link createCopilotkitMiddleware} to opt in.
424
+ */
425
+ const copilotkitMiddleware = createCopilotkitMiddleware();
426
+
427
+ //#endregion
428
+ export { copilotkitMiddleware, createCopilotkitMiddleware, zodState };
429
+ //# sourceMappingURL=middleware.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/langgraph/middleware.ts"],"sourcesContent":["import { createMiddleware, AIMessage } 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 { getA2UITools } from \"@ag-ui/langgraph\";\nimport type { A2UIToolParams } from \"@ag-ui/langgraph\";\nimport { getForwardedHeaders } from \"../header-propagation\";\n\n// ---------------------------------------------------------------------------\n// Auto-A2UI: bridge the inferred model's generate_a2ui tool from wrapModelCall\n// (the only hook that exposes the bound model) to wrapToolCall (where the tool\n// actually executes but the model is absent). Keyed by the run's thread id so\n// concurrent runs don't clobber each other.\n// ---------------------------------------------------------------------------\nconst a2uiToolsByThread = new Map<string, any>();\nconst A2UI_DEFAULT_THREAD_KEY = \"__copilotkit_a2ui_default__\";\nconst a2uiThreadKey = (state: any): string =>\n (state?.thread_id as string) || A2UI_DEFAULT_THREAD_KEY;\n\n/**\n * Merge AG-UI defaults with CopilotKit overrides. Dictionaries recurse; every\n * conflicting leaf uses CopilotKit, including false, null and empty values.\n * Arrays and serialized strings are atomic: no positional pairing or decoding.\n */\nconst isPropertyBag = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst mergeProperties = (\n base: Record<string, unknown>,\n overrides: Record<string, unknown>,\n): Record<string, unknown> =>\n Object.fromEntries(\n Array.from(new Set([...Object.keys(base), ...Object.keys(overrides)])).map(\n (key) => {\n const value = Object.prototype.hasOwnProperty.call(overrides, key)\n ? isPropertyBag(base[key]) && isPropertyBag(overrides[key])\n ? mergeProperties(base[key], overrides[key])\n : overrides[key]\n : base[key];\n return [key, value];\n },\n ),\n );\n\nconst effectiveProperties = (state: unknown): Record<string, unknown> => {\n const source = isPropertyBag(state) ? state : {};\n return mergeProperties(\n isPropertyBag(source[\"ag-ui\"]) ? source[\"ag-ui\"] : {},\n isPropertyBag(source.copilotkit) ? source.copilotkit : {},\n );\n};\n\nconst decodeCatalogValue = (value: unknown): unknown => {\n if (typeof value !== \"string\") return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n};\n\n/**\n * Find the frontend-registered A2UI catalog wherever it was passed. Returns\n * `{ compositionGuide?, catalogId? }` when a catalog is present, else `null`\n * independently of the explicit tool-injection decision. Two\n * delivery paths, depending on how the agent is served:\n * - AG-UI native endpoint → `state[\"ag-ui\"].a2ui_schema` (JSON\n * `{ catalogId, components }`); the toolkit reads it from state itself.\n * - Runtime proxy → an effective `context` entry describing\n * the A2UI catalog (catalog id + component schemas as text), passed to the\n * subagent via `compositionGuide`.\n * `catalogId` binds generated surfaces to the frontend's catalog so BYOC\n * custom catalogs render their own components (not the basic one).\n */\nconst resolveA2uiCatalog = (\n state: any,\n): { compositionGuide?: string; catalogId?: string } | null => {\n const properties = effectiveProperties(state);\n const a2uiSchema = properties.a2ui_schema;\n if (a2uiSchema) {\n let catalogId: string | undefined;\n try {\n const parsed =\n typeof a2uiSchema === \"string\" ? JSON.parse(a2uiSchema) : a2uiSchema;\n catalogId = parsed?.catalogId;\n } catch {\n // non-JSON schema — fall back to the toolkit's basic catalog\n }\n return { catalogId };\n }\n const context = decodeCatalogValue(properties.context);\n for (const entry of Array.isArray(context) ? context : []) {\n const description = entry?.description;\n const value = decodeCatalogValue(entry?.value);\n if (\n typeof description !== \"string\" ||\n typeof value !== \"string\" ||\n !description.includes(\"A2UI catalog\") ||\n !value\n )\n continue;\n const match = /^\\s*-\\s+(\\S+)/m.exec(value);\n return { compositionGuide: value, catalogId: match?.[1] };\n }\n return null;\n};\n\n/**\n * The A2UI `injectA2UITool` decision. The `@ag-ui/a2ui-middleware` forwards it on\n * `forwardedProps`, which `ag-ui-langgraph` surfaces into agent state at\n * `state[\"ag-ui\"].inject_a2ui_tool` — present only when the host turned the\n * runtime A2UI tool on (truthy or a custom tool-name string). `undefined` means\n * no signal (off, or no A2UI middleware in the pipeline) → no auto-injection.\n */\nconst a2uiInjectDecision = (state: any): boolean | string | undefined =>\n effectiveProperties(state).inject_a2ui_tool as boolean | string | undefined;\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 appendSystemNote = (request: any, note: string): any => {\n const existingMessage = request.systemMessage;\n if (existingMessage != null) {\n const separator = existingMessage.text === \"\" ? \"\" : \"\\n\\n\";\n return {\n ...request,\n systemMessage: existingMessage.concat(`${separator}${note}`),\n };\n }\n\n const existing = request.systemPrompt;\n if (existing == null) {\n return { ...request, systemPrompt: 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: `${baseText}\\n\\n${note}`,\n };\n};\n\nconst applyStateNote = (request: any, expose: ExposeStateOption): any => {\n const note = buildStateNote(\n (request.state ?? {}) as Record<string, unknown>,\n expose,\n );\n return note ? appendSystemNote(request, note) : request;\n};\n\nconst APP_CONTEXT_PREFIX = \"App Context:\\n\";\n\n// LangGraph runtime context carries trusted run configuration (thread, tenant\n// and user ids) that must never reach the model, so only a CopilotKit carrier\n// inside it counts: an \"ag-ui\" or \"copilotkit\" namespace, or a legacy\n// unnamespaced carrier with an actions or context key. See #7077.\nconst runtimeCarrierProperties = (\n carrier: unknown,\n namespace: \"ag-ui\" | \"copilotkit\",\n): Record<string, unknown> => {\n if (!isPropertyBag(carrier)) return {};\n const nested = carrier[namespace];\n if (isPropertyBag(nested) && Object.keys(nested).length > 0) return nested;\n if (\n namespace === \"copilotkit\" &&\n (\"actions\" in carrier || \"context\" in carrier)\n )\n return carrier;\n return {};\n};\n\n// Interception bookkeeping alone does not make a state namespace present.\nconst BOOKKEEPING_KEYS = new Set([\n \"interceptedToolCalls\",\n \"originalAIMessageId\",\n]);\n\nconst definedProperties = (value: unknown): Record<string, unknown> =>\n isPropertyBag(value)\n ? Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined),\n )\n : {};\n\n// Each namespace comes from state, or from its runtime carrier when state has\n// none of it. CopilotKit then merges over AG-UI, as in the Python middleware.\nconst contextNamespace = (\n state: unknown,\n runtimeContext: unknown,\n namespace: \"ag-ui\" | \"copilotkit\",\n): Record<string, unknown> => {\n const fromState = definedProperties(\n isPropertyBag(state) ? state[namespace] : undefined,\n );\n return Object.keys(fromState).some((key) => !BOOKKEEPING_KEYS.has(key))\n ? fromState\n : definedProperties(runtimeCarrierProperties(runtimeContext, namespace));\n};\n\nconst buildAppContextNote = (\n state: unknown,\n runtimeContext: unknown,\n): string | null => {\n const properties = mergeProperties(\n contextNamespace(state, runtimeContext, \"ag-ui\"),\n contextNamespace(state, runtimeContext, \"copilotkit\"),\n );\n // Forwarded request headers are transport data, never model context.\n const appContext = isPropertyBag(properties.context)\n ? Object.fromEntries(\n Object.entries(properties.context).filter(\n ([key]) => key !== \"copilotkit_forwarded_headers\",\n ),\n )\n : properties.context;\n\n const isEmptyContext =\n !appContext ||\n (typeof appContext === \"string\" && appContext.trim() === \"\") ||\n (typeof appContext === \"object\" && Object.keys(appContext).length === 0);\n if (isEmptyContext) return null;\n\n const contextContent =\n typeof appContext === \"string\"\n ? appContext\n : JSON.stringify(appContext, null, 2);\n return `${APP_CONTEXT_PREFIX}${contextContent}`;\n};\n\nconst isAppContextMessage = (msg: any): boolean => {\n const type = msg?._getType?.();\n if (type !== \"system\" && type !== \"developer\") return false;\n const content =\n typeof msg.content === \"string\" ? msg.content : msg.content?.[0]?.text;\n return typeof content === \"string\" && content.startsWith(APP_CONTEXT_PREFIX);\n};\n\n// App context goes into the one leading system message, never a message of its\n// own: Anthropic and Gemini reject a second system message. Older releases\n// wrote an \"App Context:\" SystemMessage into the thread, so drop any such\n// message from the model's input too.\nconst applyAppContextNote = (request: any): any => {\n const messages = request.messages ?? [];\n const keptMessages = messages.filter((msg: any) => !isAppContextMessage(msg));\n if (keptMessages.length !== messages.length) {\n request = { ...request, messages: keptMessages };\n }\n\n const note = buildAppContextNote(request.state, request.runtime?.context);\n return note ? appendSystemNote(request, note) : request;\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\n .object({\n \"ag-ui\": zodState(z.record(z.string(), z.unknown()).optional()),\n copilotkit: zodState(\n z\n .object({\n actions: z\n .union([z.array(z.any()), z.literal(false)])\n .nullable()\n .optional(),\n context: z.any().optional(),\n interceptedToolCalls: z.array(z.any()).optional(),\n originalAIMessageId: z.string().optional(),\n })\n .passthrough()\n .optional(),\n ),\n })\n .passthrough();\n\nconst isToolCallContentBlock = (block: unknown) =>\n typeof block === \"object\" &&\n block !== null &&\n \"type\" in block &&\n (block.type === \"tool_call\" || block.type === \"tool_call_chunk\");\n\nconst usesV1ContentBlocks = (responseMetadata: unknown) =>\n typeof responseMetadata === \"object\" &&\n responseMetadata !== null &&\n \"output_version\" in responseMetadata &&\n responseMetadata.output_version === \"v1\";\n\n/**\n * Rebuilds an AIMessage with `toolCalls` as the source of truth while\n * preserving its non-tool content and metadata. For v1 content blocks, old\n * tool blocks must be removed before construction so they cannot duplicate or\n * override the supplied tool calls when AIMessage synchronizes both fields.\n */\nconst rebuildAIMessageWithToolCalls = (\n message: AIMessage,\n toolCalls: AIMessage[\"tool_calls\"],\n) => {\n let content = message.content;\n if (\n usesV1ContentBlocks(message.response_metadata) &&\n Array.isArray(content)\n ) {\n content = content.filter((block) => !isToolCallContentBlock(block));\n }\n\n return new AIMessage({\n content,\n additional_kwargs: message.additional_kwargs,\n response_metadata: message.response_metadata,\n tool_calls: toolCalls,\n invalid_tool_calls: message.invalid_tool_calls,\n usage_metadata: message.usage_metadata,\n id: message.id,\n name: message.name,\n });\n};\n\nconst buildMiddlewareInput = (\n exposeState: ExposeStateOption,\n a2uiParams?: Omit<A2UIToolParams, \"model\">,\n) => ({\n name: \"CopilotKitMiddleware\",\n\n stateSchema: copilotKitStateSchema as unknown as InteropZodObject,\n\n // Inject frontend tools, surface user state and app context, and forward\n // x-aimock-* headers\n wrapModelCall: async (request: any, handler: (req: any) => Promise<any>) => {\n request = applyStateNote(request, exposeState);\n request = applyAppContextNote(request);\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 // Opt-in auto-injection of generate_a2ui:\n // (1) only inject when the A2UI injectA2UITool flag is truthy (forwarded by\n // @ag-ui/a2ui-middleware and surfaced at state[\"ag-ui\"].inject_a2ui_tool);\n // (2) don't double-inject if the agent already defines this tool.\n // The catalog (when present) only binds surfaces to the FE's catalog; it is\n // not the gate. The model is inferred from request.model; the built tool is\n // stashed for wrapToolCall to execute.\n let a2uiTool: any = null;\n const decision = a2uiInjectDecision(request.state);\n if (typeof getA2UITools === \"function\" && decision) {\n const catalog = resolveA2uiCatalog(request.state);\n // Shared A2UIToolParams: a single params object owned by the toolkit.\n // Start from the host overrides (guidelines / catalog id / tool name /\n // recovery) so a host can steer the subagent, then layer in only what the\n // host cannot know — the bound model, and the registered catalog id +\n // compositionGuide — without clobbering any host-set value.\n const params: A2UIToolParams = {\n ...a2uiParams,\n model: request.model,\n };\n if (catalog?.catalogId && params.defaultCatalogId == null)\n params.defaultCatalogId = catalog.catalogId;\n // Merge the registered catalog schema into any host `guidelines` bag; a\n // host-set compositionGuide wins, host generation/design overrides stay.\n if (catalog?.compositionGuide) {\n const guidelines = { ...params.guidelines };\n if (guidelines.compositionGuide == null)\n guidelines.compositionGuide = catalog.compositionGuide;\n params.guidelines = guidelines;\n }\n const candidate = getA2UITools(params);\n const existingNames = new Set(\n (request.tools || []).map((t: any) => t?.name),\n );\n if (!existingNames.has(candidate.name)) {\n // ToolNode derives tool runtime state from its config, ignoring an\n // overridden middleware request.state. Adapt the tool's invocation\n // config so the toolkit sees the same effective properties.\n const invoke = candidate.invoke.bind(candidate);\n candidate.invoke = (input, config) => {\n const state =\n config && \"state\" in config && isPropertyBag(config.state)\n ? config.state\n : request.state;\n const properties = effectiveProperties(state);\n const schema = properties.a2ui_schema;\n const context = decodeCatalogValue(properties.context);\n return invoke(input, {\n ...config,\n state: {\n ...state,\n \"ag-ui\": {\n ...properties,\n context: Array.isArray(context) ? context : [],\n // The toolkit interpolates the native schema into its prompt.\n a2ui_schema: isPropertyBag(schema)\n ? JSON.stringify(schema)\n : schema,\n },\n },\n });\n };\n a2uiTool = candidate;\n a2uiToolsByThread.set(a2uiThreadKey(request.state), a2uiTool);\n }\n }\n\n const actions = effectiveProperties(request.state).actions;\n let frontendTools = Array.isArray(actions) ? actions : [];\n if (a2uiTool) {\n // Our generate_a2ui replaces the runtime's render tool — don't advertise\n // both. Drop the render tool the A2UI middleware injected.\n const drop = typeof decision === \"string\" ? decision : \"render_a2ui\";\n frontendTools = frontendTools.filter(\n (t: any) => (t?.function?.name ?? t?.name) !== drop,\n );\n }\n\n if (frontendTools.length === 0 && !a2uiTool) {\n return handler(request);\n }\n\n const existingTools = request.tools || [];\n const mergedTools = [\n ...existingTools,\n ...(a2uiTool ? [a2uiTool] : []),\n ...frontendTools,\n ];\n\n return handler({\n ...request,\n tools: mergedTools,\n });\n },\n\n // Execute the dynamically-advertised generate_a2ui tool. It is not in the\n // agent's static tool registry, so the tool node cannot run it on its own;\n // we supply the implementation (built with the inferred model) for that one\n // tool. This hook's presence also disables createAgent's \"unknown tool\"\n // guard for dynamically-advertised tools.\n wrapToolCall: async (request: any, handler: (req: any) => Promise<any>) => {\n const tool = a2uiToolsByThread.get(a2uiThreadKey(request.state));\n if (tool && !request.tool && request.toolCall?.name === tool.name) {\n return handler({ ...request, tool });\n }\n return handler(request);\n },\n\n // Restore frontend tool calls to AIMessage before agent exits\n afterAgent: (state) => {\n // Drop the bridged A2UI tool for this run — all tool calls for the turn\n // have executed by now; the next model call re-stashes if needed.\n a2uiToolsByThread.delete(a2uiThreadKey(state));\n\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 rebuildAIMessageWithToolCalls(msg, [\n ...existingToolCalls,\n ...interceptedToolCalls,\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 actions = effectiveProperties(state).actions;\n const frontendTools = Array.isArray(actions) ? 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 = rebuildAIMessageWithToolCalls(\n lastMessage,\n backendToolCalls,\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), or\n * to steer the auto-injected `generate_a2ui` subagent via `a2uiParams`.\n *\n * `a2uiParams` is an `A2UIToolParams` without `model` (the middleware always\n * injects the bound model). Use it to override the subagent guidelines\n * (`generationGuidelines` / `designGuidelines` / `compositionGuide`),\n * `defaultCatalogId`, `toolName`, `recovery`, etc. on the auto-inject path —\n * which otherwise only ever uses the toolkit defaults. The registered catalog\n * is still folded in, but host-set values win.\n *\n * @example\n * ```typescript\n * import { createCopilotkitMiddleware } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const middleware = createCopilotkitMiddleware({\n * exposeState: [\"liked\", \"todos\"],\n * a2uiParams: { guidelines: { designGuidelines: \"...repeating-card layout...\" } },\n * });\n * ```\n */\nexport const createCopilotkitMiddleware = (\n options: {\n exposeState?: ExposeStateOption;\n a2uiParams?: Omit<A2UIToolParams, \"model\">;\n } = {},\n) => {\n const exposeState = options.exposeState ?? false;\n return createMiddleware(\n buildMiddlewareInput(exposeState, options.a2uiParams) as any,\n );\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":";;;;;;AAiBA,MAAM,oCAAoB,IAAI,KAAkB;AAChD,MAAM,0BAA0B;AAChC,MAAM,iBAAiB,UACpB,OAAO,aAAwB;;;;;;AAOlC,MAAM,iBAAiB,UACrB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM;AAEtE,MAAM,mBACJ,MACA,cAEA,OAAO,YACL,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,KAAK,EAAE,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,CAAC,KACpE,QAAQ;AAMP,QAAO,CAAC,KALM,OAAO,UAAU,eAAe,KAAK,WAAW,IAAI,GAC9D,cAAc,KAAK,KAAK,IAAI,cAAc,UAAU,KAAK,GACvD,gBAAgB,KAAK,MAAM,UAAU,KAAK,GAC1C,UAAU,OACZ,KAAK,KACU;EAEtB,CACF;AAEH,MAAM,uBAAuB,UAA4C;CACvE,MAAM,SAAS,cAAc,MAAM,GAAG,QAAQ,EAAE;AAChD,QAAO,gBACL,cAAc,OAAO,SAAS,GAAG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AkB,WAAW,EAAG;EAEpC,MAAM,mBAAmB,8BACvB,aACA,iBACD;AAED,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;;;;;;;;;;;;;;;;;;;;;;;;;AA0BD,MAAa,8BACX,UAGI,EAAE,KACH;AAEH,QAAO,iBACL,qBAFkB,QAAQ,eAAe,OAEP,QAAQ,WAAW,CACtD;;;;;;;AAQH,MAAa,uBAAuB,4BAA4B"}
@@ -0,0 +1,37 @@
1
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
+ const require_types = require('./types.cjs');
3
+ let _langchain_langgraph = require("@langchain/langgraph");
4
+
5
+ //#region src/langgraph/state-schema.ts
6
+ /**
7
+ * CopilotKit agent state defined with LangGraph's modern
8
+ * [`StateSchema`](https://docs.langchain.com/oss/javascript/langgraph/graph-api)
9
+ * API.
10
+ *
11
+ * Prefer this over `CopilotKitStateAnnotation` when starting a new
12
+ * TypeScript agent. `Annotation.Root` is still supported by LangGraph but
13
+ * `StateSchema` is the recommended API going forward.
14
+ *
15
+ * ### Example
16
+ *
17
+ * ```typescript
18
+ * import { StateSchema } from "@langchain/langgraph";
19
+ * import { CopilotKitStateSchema } from "@copilotkit/sdk-js/langgraph";
20
+ * import { z } from "zod";
21
+ *
22
+ * export const AgentStateSchema = new StateSchema({
23
+ * language: z.enum(["english", "spanish"]),
24
+ * ...CopilotKitStateSchema.fields,
25
+ * });
26
+ *
27
+ * export type AgentState = typeof AgentStateSchema.State;
28
+ * ```
29
+ */
30
+ const CopilotKitStateSchema = new _langchain_langgraph.StateSchema({
31
+ copilotkit: require_types.CopilotKitPropertiesSchema,
32
+ messages: _langchain_langgraph.MessagesValue
33
+ });
34
+
35
+ //#endregion
36
+ exports.CopilotKitStateSchema = CopilotKitStateSchema;
37
+ //# sourceMappingURL=state-schema.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state-schema.cjs","names":["StateSchema","CopilotKitPropertiesSchema","MessagesValue"],"sources":["../../src/langgraph/state-schema.ts"],"sourcesContent":["import { MessagesValue, StateSchema } from \"@langchain/langgraph\";\nimport { CopilotKitPropertiesSchema } from \"./types\";\n\n/**\n * CopilotKit agent state defined with LangGraph's modern\n * [`StateSchema`](https://docs.langchain.com/oss/javascript/langgraph/graph-api)\n * API.\n *\n * Prefer this over `CopilotKitStateAnnotation` when starting a new\n * TypeScript agent. `Annotation.Root` is still supported by LangGraph but\n * `StateSchema` is the recommended API going forward.\n *\n * ### Example\n *\n * ```typescript\n * import { StateSchema } from \"@langchain/langgraph\";\n * import { CopilotKitStateSchema } from \"@copilotkit/sdk-js/langgraph\";\n * import { z } from \"zod\";\n *\n * export const AgentStateSchema = new StateSchema({\n * language: z.enum([\"english\", \"spanish\"]),\n * ...CopilotKitStateSchema.fields,\n * });\n *\n * export type AgentState = typeof AgentStateSchema.State;\n * ```\n */\nexport const CopilotKitStateSchema = new StateSchema({\n copilotkit: CopilotKitPropertiesSchema,\n messages: MessagesValue,\n});\n\nexport type CopilotKitSchemaState = typeof CopilotKitStateSchema.State;\nexport type CopilotKitSchemaUpdate = typeof CopilotKitStateSchema.Update;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,wBAAwB,IAAIA,iCAAY;CACnD,YAAYC;CACZ,UAAUC;CACX,CAAC"}