@copilotkit/sdk-js 0.0.0-0.0.0-max-changeset-10101010101010-20260109191632

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,491 @@
1
+ import { RunnableConfig } from "@langchain/core/runnables";
2
+ import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
3
+ import { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from "@copilotkit/shared";
4
+ import { interrupt } from "@langchain/langgraph";
5
+ import { DynamicStructuredTool } from "@langchain/core/tools";
6
+ import { AIMessage } from "@langchain/core/messages";
7
+ import { OptionsConfig } from "./types";
8
+
9
+ /**
10
+ * Customize the LangGraph configuration for use in CopilotKit.
11
+ *
12
+ * To the CopilotKit SDK, run:
13
+ *
14
+ * ```bash
15
+ * npm install @copilotkit/sdk-js
16
+ * ```
17
+ *
18
+ * ### Examples
19
+ *
20
+ * Disable emitting messages and tool calls:
21
+ *
22
+ * ```typescript
23
+ * import { copilotkitCustomizeConfig } from "@copilotkit/sdk-js";
24
+ *
25
+ * config = copilotkitCustomizeConfig(
26
+ * config,
27
+ * emitMessages=false,
28
+ * emitToolCalls=false
29
+ * )
30
+ * ```
31
+ *
32
+ * To emit a tool call as streaming LangGraph state, pass the destination key in state,
33
+ * the tool name and optionally the tool argument. (If you don't pass the argument name,
34
+ * all arguments are emitted under the state key.)
35
+ *
36
+ * ```typescript
37
+ * import { copilotkitCustomizeConfig } from "@copilotkit/sdk-js";
38
+ *
39
+ * config = copilotkitCustomizeConfig(
40
+ * config,
41
+ * emitIntermediateState=[
42
+ * {
43
+ * "stateKey": "steps",
44
+ * "tool": "SearchTool",
45
+ * "toolArgument": "steps",
46
+ * },
47
+ * ],
48
+ * )
49
+ * ```
50
+ */
51
+ export function copilotkitCustomizeConfig(
52
+ /**
53
+ * The LangChain/LangGraph configuration to customize.
54
+ */
55
+ baseConfig: RunnableConfig,
56
+ /**
57
+ * Configuration options:
58
+ * - `emitMessages: boolean?`
59
+ * Configure how messages are emitted. By default, all messages are emitted. Pass false to
60
+ * disable emitting messages.
61
+ * - `emitToolCalls: boolean | string | string[]?`
62
+ * Configure how tool calls are emitted. By default, all tool calls are emitted. Pass false to
63
+ * disable emitting tool calls. Pass a string or list of strings to emit only specific tool calls.
64
+ * - `emitIntermediateState: IntermediateStateConfig[]?`
65
+ * Lets you emit tool calls as streaming LangGraph state.
66
+ */
67
+ options?: OptionsConfig,
68
+ ): RunnableConfig {
69
+ if (baseConfig && typeof baseConfig !== "object") {
70
+ throw new CopilotKitMisuseError({
71
+ message: "baseConfig must be an object or null/undefined",
72
+ });
73
+ }
74
+
75
+ if (options && typeof options !== "object") {
76
+ throw new CopilotKitMisuseError({
77
+ message: "options must be an object when provided",
78
+ });
79
+ }
80
+
81
+ // Validate emitIntermediateState structure
82
+ if (options?.emitIntermediateState) {
83
+ if (!Array.isArray(options.emitIntermediateState)) {
84
+ throw new CopilotKitMisuseError({
85
+ message: "emitIntermediateState must be an array when provided",
86
+ });
87
+ }
88
+
89
+ options.emitIntermediateState.forEach((state, index) => {
90
+ if (!state || typeof state !== "object") {
91
+ throw new CopilotKitMisuseError({
92
+ message: `emitIntermediateState[${index}] must be an object`,
93
+ });
94
+ }
95
+
96
+ if (!state.stateKey || typeof state.stateKey !== "string") {
97
+ throw new CopilotKitMisuseError({
98
+ message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`,
99
+ });
100
+ }
101
+
102
+ if (!state.tool || typeof state.tool !== "string") {
103
+ throw new CopilotKitMisuseError({
104
+ message: `emitIntermediateState[${index}] must have a valid 'tool' string property`,
105
+ });
106
+ }
107
+
108
+ if (state.toolArgument && typeof state.toolArgument !== "string") {
109
+ throw new CopilotKitMisuseError({
110
+ message: `emitIntermediateState[${index}].toolArgument must be a string when provided`,
111
+ });
112
+ }
113
+ });
114
+ }
115
+
116
+ try {
117
+ const metadata = baseConfig?.metadata || {};
118
+
119
+ if (options?.emitAll) {
120
+ metadata["copilotkit:emit-tool-calls"] = true;
121
+ metadata["copilotkit:emit-messages"] = true;
122
+ } else {
123
+ if (options?.emitToolCalls !== undefined) {
124
+ metadata["copilotkit:emit-tool-calls"] = options.emitToolCalls;
125
+ }
126
+ if (options?.emitMessages !== undefined) {
127
+ metadata["copilotkit:emit-messages"] = options.emitMessages;
128
+ }
129
+ }
130
+
131
+ if (options?.emitIntermediateState) {
132
+ const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({
133
+ tool: state.tool,
134
+ tool_argument: state.toolArgument,
135
+ state_key: state.stateKey,
136
+ }));
137
+
138
+ metadata["copilotkit:emit-intermediate-state"] = snakeCaseIntermediateState;
139
+ }
140
+
141
+ baseConfig = baseConfig || {};
142
+
143
+ return {
144
+ ...baseConfig,
145
+ metadata: metadata,
146
+ };
147
+ } catch (error) {
148
+ throw new CopilotKitMisuseError({
149
+ message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`,
150
+ });
151
+ }
152
+ }
153
+ /**
154
+ * Exits the current agent after the run completes. Calling copilotkit_exit() will
155
+ * not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after
156
+ * the run completes.
157
+ *
158
+ * ### Examples
159
+ *
160
+ * ```typescript
161
+ * import { copilotkitExit } from "@copilotkit/sdk-js";
162
+ *
163
+ * async function myNode(state: Any):
164
+ * await copilotkitExit(config)
165
+ * return state
166
+ * ```
167
+ */
168
+ export async function copilotkitExit(
169
+ /**
170
+ * The LangChain/LangGraph configuration.
171
+ */
172
+ config: RunnableConfig,
173
+ ) {
174
+ if (!config) {
175
+ throw new CopilotKitMisuseError({
176
+ message: "LangGraph configuration is required for copilotkitExit",
177
+ });
178
+ }
179
+
180
+ try {
181
+ await dispatchCustomEvent("copilotkit_exit", {}, config);
182
+ } catch (error) {
183
+ throw new CopilotKitMisuseError({
184
+ message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`,
185
+ });
186
+ }
187
+ }
188
+ /**
189
+ * Emits intermediate state to CopilotKit. Useful if you have a longer running node and you want to
190
+ * update the user with the current state of the node.
191
+ *
192
+ * ### Examples
193
+ *
194
+ * ```typescript
195
+ * import { copilotkitEmitState } from "@copilotkit/sdk-js";
196
+ *
197
+ * for (let i = 0; i < 10; i++) {
198
+ * await someLongRunningOperation(i);
199
+ * await copilotkitEmitState(config, { progress: i });
200
+ * }
201
+ * ```
202
+ */
203
+ export async function copilotkitEmitState(
204
+ /**
205
+ * The LangChain/LangGraph configuration.
206
+ */
207
+ config: RunnableConfig,
208
+ /**
209
+ * The state to emit.
210
+ */
211
+ state: any,
212
+ ) {
213
+ if (!config) {
214
+ throw new CopilotKitMisuseError({
215
+ message: "LangGraph configuration is required for copilotkitEmitState",
216
+ });
217
+ }
218
+
219
+ if (state === undefined) {
220
+ throw new CopilotKitMisuseError({
221
+ message: "State is required for copilotkitEmitState",
222
+ });
223
+ }
224
+
225
+ try {
226
+ await dispatchCustomEvent("copilotkit_manually_emit_intermediate_state", state, config);
227
+ } catch (error) {
228
+ throw new CopilotKitMisuseError({
229
+ message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,
230
+ });
231
+ }
232
+ }
233
+ /**
234
+ * Manually emits a message to CopilotKit. Useful in longer running nodes to update the user.
235
+ * Important: You still need to return the messages from the node.
236
+ *
237
+ * ### Examples
238
+ *
239
+ * ```typescript
240
+ * import { copilotkitEmitMessage } from "@copilotkit/sdk-js";
241
+ *
242
+ * const message = "Step 1 of 10 complete";
243
+ * await copilotkitEmitMessage(config, message);
244
+ *
245
+ * // Return the message from the node
246
+ * return {
247
+ * "messages": [AIMessage(content=message)]
248
+ * }
249
+ * ```
250
+ */
251
+ export async function copilotkitEmitMessage(
252
+ /**
253
+ * The LangChain/LangGraph configuration.
254
+ */
255
+ config: RunnableConfig,
256
+ /**
257
+ * The message to emit.
258
+ */
259
+ message: string,
260
+ ) {
261
+ if (!config) {
262
+ throw new CopilotKitMisuseError({
263
+ message: "LangGraph configuration is required for copilotkitEmitMessage",
264
+ });
265
+ }
266
+
267
+ if (!message || typeof message !== "string") {
268
+ throw new CopilotKitMisuseError({
269
+ message: "Message must be a non-empty string for copilotkitEmitMessage",
270
+ });
271
+ }
272
+
273
+ try {
274
+ await dispatchCustomEvent(
275
+ "copilotkit_manually_emit_message",
276
+ { message, message_id: randomId(), role: "assistant" },
277
+ config,
278
+ );
279
+ } catch (error) {
280
+ throw new CopilotKitMisuseError({
281
+ message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`,
282
+ });
283
+ }
284
+ }
285
+ /**
286
+ * Manually emits a tool call to CopilotKit.
287
+ *
288
+ * ### Examples
289
+ *
290
+ * ```typescript
291
+ * import { copilotkitEmitToolCall } from "@copilotkit/sdk-js";
292
+ *
293
+ * await copilotkitEmitToolCall(config, name="SearchTool", args={"steps": 10})
294
+ * ```
295
+ */
296
+ export async function copilotkitEmitToolCall(
297
+ /**
298
+ * The LangChain/LangGraph configuration.
299
+ */
300
+ config: RunnableConfig,
301
+ /**
302
+ * The name of the tool to emit.
303
+ */
304
+ name: string,
305
+ /**
306
+ * The arguments to emit.
307
+ */
308
+ args: any,
309
+ ) {
310
+ if (!config) {
311
+ throw new CopilotKitMisuseError({
312
+ message: "LangGraph configuration is required for copilotkitEmitToolCall",
313
+ });
314
+ }
315
+
316
+ if (!name || typeof name !== "string") {
317
+ throw new CopilotKitMisuseError({
318
+ message: "Tool name must be a non-empty string for copilotkitEmitToolCall",
319
+ });
320
+ }
321
+
322
+ if (args === undefined) {
323
+ throw new CopilotKitMisuseError({
324
+ message: "Tool arguments are required for copilotkitEmitToolCall",
325
+ });
326
+ }
327
+
328
+ try {
329
+ await dispatchCustomEvent(
330
+ "copilotkit_manually_emit_tool_call",
331
+ { name, args, id: randomId() },
332
+ config,
333
+ );
334
+ } catch (error) {
335
+ throw new CopilotKitMisuseError({
336
+ message: `Failed to emit tool call '${name}': ${error instanceof Error ? error.message : String(error)}`,
337
+ });
338
+ }
339
+ }
340
+
341
+ export function convertActionToDynamicStructuredTool(actionInput: any): DynamicStructuredTool<any> {
342
+ if (!actionInput) {
343
+ throw new CopilotKitMisuseError({
344
+ message: "Action input is required but was not provided",
345
+ });
346
+ }
347
+
348
+ if (!actionInput.name || typeof actionInput.name !== "string") {
349
+ throw new CopilotKitMisuseError({
350
+ message: "Action must have a valid 'name' property of type string",
351
+ });
352
+ }
353
+
354
+ if (
355
+ actionInput.description == undefined ||
356
+ actionInput.description == null ||
357
+ typeof actionInput.description !== "string"
358
+ ) {
359
+ throw new CopilotKitMisuseError({
360
+ message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,
361
+ });
362
+ }
363
+
364
+ if (!actionInput.parameters) {
365
+ throw new CopilotKitMisuseError({
366
+ message: `Action '${actionInput.name}' must have a 'parameters' property`,
367
+ });
368
+ }
369
+
370
+ try {
371
+ return new DynamicStructuredTool({
372
+ name: actionInput.name,
373
+ description: actionInput.description,
374
+ schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),
375
+ func: async () => {
376
+ return "";
377
+ },
378
+ });
379
+ } catch (error) {
380
+ throw new CopilotKitMisuseError({
381
+ message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,
382
+ });
383
+ }
384
+ }
385
+ /**
386
+ * Use this function to convert a list of actions you get from state
387
+ * to a list of dynamic structured tools.
388
+ *
389
+ * ### Examples
390
+ *
391
+ * ```typescript
392
+ * import { convertActionsToDynamicStructuredTools } from "@copilotkit/sdk-js";
393
+ *
394
+ * const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);
395
+ * ```
396
+ */
397
+ export function convertActionsToDynamicStructuredTools(
398
+ /**
399
+ * The list of actions to convert.
400
+ */
401
+ actions: any[],
402
+ ): DynamicStructuredTool<any>[] {
403
+ if (!Array.isArray(actions)) {
404
+ throw new CopilotKitMisuseError({
405
+ message: "Actions must be an array",
406
+ });
407
+ }
408
+
409
+ return actions.map((action, index) => {
410
+ try {
411
+ return convertActionToDynamicStructuredTool(
412
+ action.type === "function" ? action.function : action,
413
+ );
414
+ } catch (error) {
415
+ throw new CopilotKitMisuseError({
416
+ message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,
417
+ });
418
+ }
419
+ });
420
+ }
421
+
422
+ export function copilotKitInterrupt({
423
+ message,
424
+ action,
425
+ args,
426
+ }: {
427
+ message?: string;
428
+ action?: string;
429
+ args?: Record<string, any>;
430
+ }) {
431
+ if (!message && !action) {
432
+ throw new CopilotKitMisuseError({
433
+ message:
434
+ "Either message or action (and optional arguments) must be provided for copilotKitInterrupt",
435
+ });
436
+ }
437
+
438
+ if (action && typeof action !== "string") {
439
+ throw new CopilotKitMisuseError({
440
+ message: "Action must be a string when provided to copilotKitInterrupt",
441
+ });
442
+ }
443
+
444
+ if (message && typeof message !== "string") {
445
+ throw new CopilotKitMisuseError({
446
+ message: "Message must be a string when provided to copilotKitInterrupt",
447
+ });
448
+ }
449
+
450
+ if (args && typeof args !== "object") {
451
+ throw new CopilotKitMisuseError({
452
+ message: "Args must be an object when provided to copilotKitInterrupt",
453
+ });
454
+ }
455
+
456
+ let interruptValues = null;
457
+ let interruptMessage = null;
458
+ let answer = null;
459
+
460
+ try {
461
+ if (message) {
462
+ interruptValues = message;
463
+ interruptMessage = new AIMessage({ content: message, id: randomId() });
464
+ } else {
465
+ const toolId = randomId();
466
+ interruptMessage = new AIMessage({
467
+ content: "",
468
+ tool_calls: [{ id: toolId, name: action, args: args ?? {} }],
469
+ });
470
+ interruptValues = {
471
+ action,
472
+ args: args ?? {},
473
+ };
474
+ }
475
+
476
+ const response = interrupt({
477
+ __copilotkit_interrupt_value__: interruptValues,
478
+ __copilotkit_messages__: [interruptMessage],
479
+ });
480
+ answer = response[response.length - 1].content;
481
+
482
+ return {
483
+ answer,
484
+ messages: response,
485
+ };
486
+ } catch (error) {
487
+ throw new CopilotKitMisuseError({
488
+ message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,
489
+ });
490
+ }
491
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "../../utilities/tsconfig/base.json",
3
+ "compilerOptions": {
4
+ "lib": ["es2017", "dom"],
5
+ "emitDecoratorMetadata": true,
6
+ "experimentalDecorators": true,
7
+ "strict": false
8
+ },
9
+ "include": ["./src/**/*.ts"],
10
+ "exclude": ["dist", "build", "node_modules", "**/*.test.ts", "**/*.test.tsx", "**/__tests__/*"]
11
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { defineConfig, Options } from "tsup";
2
+
3
+ export default defineConfig((options: Options) => ({
4
+ ...options,
5
+ entry: {
6
+ index: "src/index.ts",
7
+ langchain: "src/langchain.ts",
8
+ langgraph: "src/langgraph/index.ts",
9
+ },
10
+ format: ["esm", "cjs"],
11
+ dts: {
12
+ entry: ["src/index.ts", "src/langchain.ts", "src/langgraph/index.ts"],
13
+ },
14
+ minify: false,
15
+ external: [],
16
+ sourcemap: true,
17
+ entryNames: "[name]",
18
+ exclude: [
19
+ "**/*.test.ts", // Exclude TypeScript test files
20
+ "**/*.test.tsx", // Exclude TypeScript React test files
21
+ "**/__tests__/*", // Exclude any files inside a __tests__ directory
22
+ ],
23
+ }));
package/typedoc.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": ["../../typedoc.base.json"],
3
+ "entryPoints": ["src/index.ts"]
4
+ }