@copilotkitnext/shared 1.53.1-next.1 → 1.54.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4,6 +4,7 @@ const require_logger = require('./logger.cjs');
4
4
  const require_constants = require('./constants.cjs');
5
5
  const require_finalize_events = require('./finalize-events.cjs');
6
6
  const require_transcription_errors = require('./transcription-errors.cjs');
7
+ const require_standard_schema = require('./standard-schema.cjs');
7
8
 
8
9
  exports.AG_UI_CHANNEL_EVENT = require_constants.AG_UI_CHANNEL_EVENT;
9
10
  exports.DEFAULT_AGENT_ID = require_constants.DEFAULT_AGENT_ID;
@@ -13,4 +14,6 @@ exports.finalizeRunEvents = require_finalize_events.finalizeRunEvents;
13
14
  exports.logger = require_logger.logger;
14
15
  exports.partialJSONParse = require_utils.partialJSONParse;
15
16
  exports.phoenixExponentialBackoff = require_utils.phoenixExponentialBackoff;
16
- exports.randomUUID = require_utils.randomUUID;
17
+ exports.randomUUID = require_utils.randomUUID;
18
+ exports.safeParseToolArgs = require_utils.safeParseToolArgs;
19
+ exports.schemaToJsonSchema = require_standard_schema.schemaToJsonSchema;
package/dist/index.d.cts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { AgentDescription, MaybePromise, NonEmptyRecord, RuntimeInfo } from "./types.cjs";
2
- import { partialJSONParse, phoenixExponentialBackoff, randomUUID } from "./utils.cjs";
2
+ import { partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs } from "./utils.cjs";
3
3
  import { logger } from "./logger.cjs";
4
4
  import { AG_UI_CHANNEL_EVENT, DEFAULT_AGENT_ID } from "./constants.cjs";
5
5
  import { finalizeRunEvents } from "./finalize-events.cjs";
6
6
  import { TranscriptionErrorCode, TranscriptionErrorResponse, TranscriptionErrors } from "./transcription-errors.cjs";
7
- export { AG_UI_CHANNEL_EVENT, type AgentDescription, DEFAULT_AGENT_ID, type MaybePromise, type NonEmptyRecord, type RuntimeInfo, TranscriptionErrorCode, type TranscriptionErrorResponse, TranscriptionErrors, finalizeRunEvents, logger, partialJSONParse, phoenixExponentialBackoff, randomUUID };
7
+ import { InferSchemaOutput, SchemaToJsonSchemaOptions, StandardJSONSchemaV1, StandardSchemaV1, schemaToJsonSchema } from "./standard-schema.cjs";
8
+ export { AG_UI_CHANNEL_EVENT, type AgentDescription, DEFAULT_AGENT_ID, type InferSchemaOutput, type MaybePromise, type NonEmptyRecord, type RuntimeInfo, type SchemaToJsonSchemaOptions, type StandardJSONSchemaV1, type StandardSchemaV1, TranscriptionErrorCode, type TranscriptionErrorResponse, TranscriptionErrors, finalizeRunEvents, logger, partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs, schemaToJsonSchema };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { AgentDescription, MaybePromise, NonEmptyRecord, RuntimeInfo } from "./types.mjs";
2
- import { partialJSONParse, phoenixExponentialBackoff, randomUUID } from "./utils.mjs";
2
+ import { partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs } from "./utils.mjs";
3
3
  import { logger } from "./logger.mjs";
4
4
  import { AG_UI_CHANNEL_EVENT, DEFAULT_AGENT_ID } from "./constants.mjs";
5
5
  import { finalizeRunEvents } from "./finalize-events.mjs";
6
6
  import { TranscriptionErrorCode, TranscriptionErrorResponse, TranscriptionErrors } from "./transcription-errors.mjs";
7
- export { AG_UI_CHANNEL_EVENT, type AgentDescription, DEFAULT_AGENT_ID, type MaybePromise, type NonEmptyRecord, type RuntimeInfo, TranscriptionErrorCode, type TranscriptionErrorResponse, TranscriptionErrors, finalizeRunEvents, logger, partialJSONParse, phoenixExponentialBackoff, randomUUID };
7
+ import { InferSchemaOutput, SchemaToJsonSchemaOptions, StandardJSONSchemaV1, StandardSchemaV1, schemaToJsonSchema } from "./standard-schema.mjs";
8
+ export { AG_UI_CHANNEL_EVENT, type AgentDescription, DEFAULT_AGENT_ID, type InferSchemaOutput, type MaybePromise, type NonEmptyRecord, type RuntimeInfo, type SchemaToJsonSchemaOptions, type StandardJSONSchemaV1, type StandardSchemaV1, TranscriptionErrorCode, type TranscriptionErrorResponse, TranscriptionErrors, finalizeRunEvents, logger, partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs, schemaToJsonSchema };
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
- import { partialJSONParse, phoenixExponentialBackoff, randomUUID } from "./utils.mjs";
1
+ import { partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs } from "./utils.mjs";
2
2
  import { logger } from "./logger.mjs";
3
3
  import { AG_UI_CHANNEL_EVENT, DEFAULT_AGENT_ID } from "./constants.mjs";
4
4
  import { finalizeRunEvents } from "./finalize-events.mjs";
5
5
  import { TranscriptionErrorCode, TranscriptionErrors } from "./transcription-errors.mjs";
6
+ import { schemaToJsonSchema } from "./standard-schema.mjs";
6
7
 
7
- export { AG_UI_CHANNEL_EVENT, DEFAULT_AGENT_ID, TranscriptionErrorCode, TranscriptionErrors, finalizeRunEvents, logger, partialJSONParse, phoenixExponentialBackoff, randomUUID };
8
+ export { AG_UI_CHANNEL_EVENT, DEFAULT_AGENT_ID, TranscriptionErrorCode, TranscriptionErrors, finalizeRunEvents, logger, partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs, schemaToJsonSchema };
package/dist/index.umd.js CHANGED
@@ -39,12 +39,33 @@ partial_json = __toESM(partial_json);
39
39
  }
40
40
  function partialJSONParse(json) {
41
41
  try {
42
- return partial_json.parse(json);
42
+ const parsed = partial_json.parse(json);
43
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
44
+ console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
45
+ return {};
43
46
  } catch (error) {
44
47
  return {};
45
48
  }
46
49
  }
47
50
  /**
51
+ * Safely parses a JSON string into a plain object for tool arguments.
52
+ * Handles two failure modes:
53
+ * 1. Malformed JSON (SyntaxError from JSON.parse)
54
+ * 2. Valid JSON that isn't a plain object (e.g. "", [], null, 42, true)
55
+ * Falls back to an empty object for safety in both cases.
56
+ */
57
+ function safeParseToolArgs(raw) {
58
+ try {
59
+ const parsed = JSON.parse(raw);
60
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
61
+ console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
62
+ return {};
63
+ } catch (_unused) {
64
+ console.warn("[CopilotKit] Failed to parse tool arguments, falling back to empty object");
65
+ return {};
66
+ }
67
+ }
68
+ /**
48
69
  * Returns an exponential backoff function suitable for Phoenix.js
49
70
  * `reconnectAfterMs` and `rejoinAfterMs` options.
50
71
  *
@@ -248,6 +269,32 @@ partial_json = __toESM(partial_json);
248
269
  })
249
270
  };
250
271
 
272
+ //#endregion
273
+ //#region src/standard-schema.ts
274
+ /**
275
+ * Check whether a schema implements the Standard JSON Schema V1 protocol.
276
+ */
277
+ function hasStandardJsonSchema(schema) {
278
+ const props = schema["~standard"];
279
+ return props != null && typeof props === "object" && "jsonSchema" in props && props.jsonSchema != null && typeof props.jsonSchema === "object" && "input" in props.jsonSchema && typeof props.jsonSchema.input === "function";
280
+ }
281
+ /**
282
+ * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.
283
+ *
284
+ * Strategy:
285
+ * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
286
+ * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
287
+ * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
288
+ * injected `zodToJsonSchema()` function.
289
+ * 3. Otherwise throw a descriptive error.
290
+ */
291
+ function schemaToJsonSchema(schema, options) {
292
+ if (hasStandardJsonSchema(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
293
+ const vendor = schema["~standard"].vendor;
294
+ if (vendor === "zod" && (options === null || options === void 0 ? void 0 : options.zodToJsonSchema)) return options.zodToJsonSchema(schema, { $refStrategy: "none" });
295
+ throw new Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${vendor}") does not implement Standard JSON Schema V1 and no zodToJsonSchema fallback is available. Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) or pass a zodToJsonSchema function in options.`);
296
+ }
297
+
251
298
  //#endregion
252
299
  exports.AG_UI_CHANNEL_EVENT = AG_UI_CHANNEL_EVENT;
253
300
  exports.DEFAULT_AGENT_ID = DEFAULT_AGENT_ID;
@@ -258,5 +305,7 @@ exports.logger = logger;
258
305
  exports.partialJSONParse = partialJSONParse;
259
306
  exports.phoenixExponentialBackoff = phoenixExponentialBackoff;
260
307
  exports.randomUUID = randomUUID;
308
+ exports.safeParseToolArgs = safeParseToolArgs;
309
+ exports.schemaToJsonSchema = schemaToJsonSchema;
261
310
  });
262
311
  //# sourceMappingURL=index.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","names":["PartialJSON","EventType"],"sources":["../src/utils.ts","../src/logger.ts","../src/constants.ts","../src/finalize-events.ts","../src/transcription-errors.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport * as PartialJSON from \"partial-json\";\n\nexport function randomUUID() {\n return uuidv4();\n}\n\nexport function partialJSONParse(json: string) {\n try {\n return PartialJSON.parse(json);\n } catch (error) {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n","export const logger = console;\n","export const DEFAULT_AGENT_ID = \"default\";\n\n/** Phoenix channel event name used for all AG-UI events. */\nexport const AG_UI_CHANNEL_EVENT = \"ag-ui\";\n","import { BaseEvent, EventType, RunErrorEvent } from \"@ag-ui/client\";\nimport { randomUUID } from \"./utils\";\n\ninterface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const { stopRequested = false, interruptionMessage } = options;\n\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n\n const appended: BaseEvent[] = [];\n\n const openMessageIds = new Set<string>();\n const openToolCalls = new Map<\n string,\n {\n hasEnd: boolean;\n hasResult: boolean;\n }\n >();\n\n for (const event of events) {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.add(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.delete(messageId);\n }\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (typeof toolCallId === \"string\") {\n openToolCalls.set(toolCallId, {\n hasEnd: false,\n hasResult: false,\n });\n }\n break;\n }\n case EventType.TOOL_CALL_END: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasEnd = true;\n }\n break;\n }\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasResult = true;\n }\n break;\n }\n default:\n break;\n }\n }\n\n const hasRunFinished = events.some(\n (event) => event.type === EventType.RUN_FINISHED,\n );\n const hasRunError = events.some(\n (event) => event.type === EventType.RUN_ERROR,\n );\n const hasTerminalEvent = hasRunFinished || hasRunError;\n const terminalEventMissing = !hasTerminalEvent;\n\n for (const messageId of openMessageIds) {\n const endEvent = {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n const endEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n if (terminalEventMissing && !info.hasResult) {\n const resultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId ?? randomUUID()}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent;\n events.push(resultEvent);\n appended.push(resultEvent);\n }\n }\n\n if (terminalEventMissing) {\n if (stopRequested) {\n const finishedEvent = {\n type: EventType.RUN_FINISHED,\n } as BaseEvent;\n events.push(finishedEvent);\n appended.push(finishedEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n events.push(errorEvent);\n appended.push(errorEvent);\n }\n }\n\n return appended;\n}\n","/**\n * Error codes for transcription HTTP responses.\n * Uses snake_case to align with existing CopilotKitCoreErrorCode pattern.\n * These codes are returned by the runtime and parsed by the client.\n */\nexport enum TranscriptionErrorCode {\n /** Transcription service not configured in runtime */\n SERVICE_NOT_CONFIGURED = \"service_not_configured\",\n /** Audio format not supported */\n INVALID_AUDIO_FORMAT = \"invalid_audio_format\",\n /** Audio file is too long */\n AUDIO_TOO_LONG = \"audio_too_long\",\n /** Audio file is empty or too short */\n AUDIO_TOO_SHORT = \"audio_too_short\",\n /** Rate limited by transcription provider */\n RATE_LIMITED = \"rate_limited\",\n /** Authentication failed with transcription provider */\n AUTH_FAILED = \"auth_failed\",\n /** Transcription provider returned an error */\n PROVIDER_ERROR = \"provider_error\",\n /** Network error during transcription */\n NETWORK_ERROR = \"network_error\",\n /** Invalid request format */\n INVALID_REQUEST = \"invalid_request\",\n}\n\n/**\n * Error response format returned by the transcription endpoint.\n */\nexport interface TranscriptionErrorResponse {\n error: TranscriptionErrorCode;\n message: string;\n retryable?: boolean;\n}\n\n/**\n * Helper functions to create transcription error responses.\n * Used by the runtime to return consistent error responses.\n */\nexport const TranscriptionErrors = {\n serviceNotConfigured: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.SERVICE_NOT_CONFIGURED,\n message: \"Transcription service is not configured\",\n retryable: false,\n }),\n\n invalidAudioFormat: (\n format: string,\n supported: string[],\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_AUDIO_FORMAT,\n message: `Unsupported audio format: ${format}. Supported: ${supported.join(\", \")}`,\n retryable: false,\n }),\n\n invalidRequest: (details: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_REQUEST,\n message: details,\n retryable: false,\n }),\n\n rateLimited: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.RATE_LIMITED,\n message: \"Rate limited. Please try again later.\",\n retryable: true,\n }),\n\n authFailed: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUTH_FAILED,\n message: \"Authentication failed with transcription provider\",\n retryable: false,\n }),\n\n providerError: (message: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.PROVIDER_ERROR,\n message,\n retryable: true,\n }),\n\n networkError: (\n message: string = \"Network error during transcription\",\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.NETWORK_ERROR,\n message,\n retryable: true,\n }),\n\n audioTooLong: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_LONG,\n message: \"Audio file is too long\",\n retryable: false,\n }),\n\n audioTooShort: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_SHORT,\n message: \"Audio is too short to transcribe\",\n retryable: false,\n }),\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"index.umd.js","names":["PartialJSON","EventType"],"sources":["../src/utils.ts","../src/logger.ts","../src/constants.ts","../src/finalize-events.ts","../src/transcription-errors.ts","../src/standard-schema.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport * as PartialJSON from \"partial-json\";\n\nexport function randomUUID() {\n return uuidv4();\n}\n\nexport function partialJSONParse(json: string): unknown {\n try {\n const parsed = PartialJSON.parse(json);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch (error) {\n return {};\n }\n}\n\n/**\n * Safely parses a JSON string into a plain object for tool arguments.\n * Handles two failure modes:\n * 1. Malformed JSON (SyntaxError from JSON.parse)\n * 2. Valid JSON that isn't a plain object (e.g. \"\", [], null, 42, true)\n * Falls back to an empty object for safety in both cases.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n","export const logger = console;\n","export const DEFAULT_AGENT_ID = \"default\";\n\n/** Phoenix channel event name used for all AG-UI events. */\nexport const AG_UI_CHANNEL_EVENT = \"ag-ui\";\n","import { BaseEvent, EventType, RunErrorEvent } from \"@ag-ui/client\";\nimport { randomUUID } from \"./utils\";\n\ninterface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const { stopRequested = false, interruptionMessage } = options;\n\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n\n const appended: BaseEvent[] = [];\n\n const openMessageIds = new Set<string>();\n const openToolCalls = new Map<\n string,\n {\n hasEnd: boolean;\n hasResult: boolean;\n }\n >();\n\n for (const event of events) {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.add(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.delete(messageId);\n }\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (typeof toolCallId === \"string\") {\n openToolCalls.set(toolCallId, {\n hasEnd: false,\n hasResult: false,\n });\n }\n break;\n }\n case EventType.TOOL_CALL_END: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasEnd = true;\n }\n break;\n }\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasResult = true;\n }\n break;\n }\n default:\n break;\n }\n }\n\n const hasRunFinished = events.some(\n (event) => event.type === EventType.RUN_FINISHED,\n );\n const hasRunError = events.some(\n (event) => event.type === EventType.RUN_ERROR,\n );\n const hasTerminalEvent = hasRunFinished || hasRunError;\n const terminalEventMissing = !hasTerminalEvent;\n\n for (const messageId of openMessageIds) {\n const endEvent = {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n const endEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n if (terminalEventMissing && !info.hasResult) {\n const resultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId ?? randomUUID()}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent;\n events.push(resultEvent);\n appended.push(resultEvent);\n }\n }\n\n if (terminalEventMissing) {\n if (stopRequested) {\n const finishedEvent = {\n type: EventType.RUN_FINISHED,\n } as BaseEvent;\n events.push(finishedEvent);\n appended.push(finishedEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n events.push(errorEvent);\n appended.push(errorEvent);\n }\n }\n\n return appended;\n}\n","/**\n * Error codes for transcription HTTP responses.\n * Uses snake_case to align with existing CopilotKitCoreErrorCode pattern.\n * These codes are returned by the runtime and parsed by the client.\n */\nexport enum TranscriptionErrorCode {\n /** Transcription service not configured in runtime */\n SERVICE_NOT_CONFIGURED = \"service_not_configured\",\n /** Audio format not supported */\n INVALID_AUDIO_FORMAT = \"invalid_audio_format\",\n /** Audio file is too long */\n AUDIO_TOO_LONG = \"audio_too_long\",\n /** Audio file is empty or too short */\n AUDIO_TOO_SHORT = \"audio_too_short\",\n /** Rate limited by transcription provider */\n RATE_LIMITED = \"rate_limited\",\n /** Authentication failed with transcription provider */\n AUTH_FAILED = \"auth_failed\",\n /** Transcription provider returned an error */\n PROVIDER_ERROR = \"provider_error\",\n /** Network error during transcription */\n NETWORK_ERROR = \"network_error\",\n /** Invalid request format */\n INVALID_REQUEST = \"invalid_request\",\n}\n\n/**\n * Error response format returned by the transcription endpoint.\n */\nexport interface TranscriptionErrorResponse {\n error: TranscriptionErrorCode;\n message: string;\n retryable?: boolean;\n}\n\n/**\n * Helper functions to create transcription error responses.\n * Used by the runtime to return consistent error responses.\n */\nexport const TranscriptionErrors = {\n serviceNotConfigured: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.SERVICE_NOT_CONFIGURED,\n message: \"Transcription service is not configured\",\n retryable: false,\n }),\n\n invalidAudioFormat: (\n format: string,\n supported: string[],\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_AUDIO_FORMAT,\n message: `Unsupported audio format: ${format}. Supported: ${supported.join(\", \")}`,\n retryable: false,\n }),\n\n invalidRequest: (details: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_REQUEST,\n message: details,\n retryable: false,\n }),\n\n rateLimited: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.RATE_LIMITED,\n message: \"Rate limited. Please try again later.\",\n retryable: true,\n }),\n\n authFailed: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUTH_FAILED,\n message: \"Authentication failed with transcription provider\",\n retryable: false,\n }),\n\n providerError: (message: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.PROVIDER_ERROR,\n message,\n retryable: true,\n }),\n\n networkError: (\n message: string = \"Network error during transcription\",\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.NETWORK_ERROR,\n message,\n retryable: true,\n }),\n\n audioTooLong: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_LONG,\n message: \"Audio file is too long\",\n retryable: false,\n }),\n\n audioTooShort: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_SHORT,\n message: \"Audio is too short to transcribe\",\n retryable: false,\n }),\n};\n","import type {\n StandardSchemaV1,\n StandardJSONSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type { StandardSchemaV1, StandardJSONSchemaV1 };\n\n/**\n * Extract the Output type from a StandardSchemaV1 schema.\n * Replaces `z.infer<S>` for generic schema inference.\n */\nexport type InferSchemaOutput<S> =\n S extends StandardSchemaV1<any, infer O> ? O : never;\n\nexport interface SchemaToJsonSchemaOptions {\n /**\n * Injected `zodToJsonSchema` function so that `shared` does not depend on\n * `zod-to-json-schema`. Required when the schema is a Zod v3 schema that\n * does not implement Standard JSON Schema V1.\n */\n zodToJsonSchema?: (\n schema: unknown,\n options?: { $refStrategy?: string },\n ) => Record<string, unknown>;\n}\n\n/**\n * Check whether a schema implements the Standard JSON Schema V1 protocol.\n */\nfunction hasStandardJsonSchema(\n schema: StandardSchemaV1,\n): schema is StandardSchemaV1 & StandardJSONSchemaV1 {\n const props = schema[\"~standard\"];\n return (\n props != null &&\n typeof props === \"object\" &&\n \"jsonSchema\" in props &&\n props.jsonSchema != null &&\n typeof props.jsonSchema === \"object\" &&\n \"input\" in props.jsonSchema &&\n typeof props.jsonSchema.input === \"function\"\n );\n}\n\n/**\n * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.\n *\n * Strategy:\n * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),\n * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.\n * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the\n * injected `zodToJsonSchema()` function.\n * 3. Otherwise throw a descriptive error.\n */\nexport function schemaToJsonSchema(\n schema: StandardSchemaV1,\n options?: SchemaToJsonSchemaOptions,\n): Record<string, unknown> {\n // 1. Standard JSON Schema V1\n if (hasStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n }\n\n // 2. Zod v3 fallback\n const vendor = schema[\"~standard\"].vendor;\n if (vendor === \"zod\" && options?.zodToJsonSchema) {\n return options.zodToJsonSchema(schema, { $refStrategy: \"none\" });\n }\n\n throw new Error(\n `Cannot convert schema to JSON Schema. The schema (vendor: \"${vendor}\") does not implement Standard JSON Schema V1 ` +\n `and no zodToJsonSchema fallback is available. ` +\n `Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) ` +\n `or pass a zodToJsonSchema function in options.`,\n );\n}\n"],"mappings":"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"}
@@ -0,0 +1,29 @@
1
+
2
+ //#region src/standard-schema.ts
3
+ /**
4
+ * Check whether a schema implements the Standard JSON Schema V1 protocol.
5
+ */
6
+ function hasStandardJsonSchema(schema) {
7
+ const props = schema["~standard"];
8
+ return props != null && typeof props === "object" && "jsonSchema" in props && props.jsonSchema != null && typeof props.jsonSchema === "object" && "input" in props.jsonSchema && typeof props.jsonSchema.input === "function";
9
+ }
10
+ /**
11
+ * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.
12
+ *
13
+ * Strategy:
14
+ * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
15
+ * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
16
+ * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
17
+ * injected `zodToJsonSchema()` function.
18
+ * 3. Otherwise throw a descriptive error.
19
+ */
20
+ function schemaToJsonSchema(schema, options) {
21
+ if (hasStandardJsonSchema(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
22
+ const vendor = schema["~standard"].vendor;
23
+ if (vendor === "zod" && options?.zodToJsonSchema) return options.zodToJsonSchema(schema, { $refStrategy: "none" });
24
+ throw new Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${vendor}") does not implement Standard JSON Schema V1 and no zodToJsonSchema fallback is available. Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) or pass a zodToJsonSchema function in options.`);
25
+ }
26
+
27
+ //#endregion
28
+ exports.schemaToJsonSchema = schemaToJsonSchema;
29
+ //# sourceMappingURL=standard-schema.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard-schema.cjs","names":[],"sources":["../src/standard-schema.ts"],"sourcesContent":["import type {\n StandardSchemaV1,\n StandardJSONSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type { StandardSchemaV1, StandardJSONSchemaV1 };\n\n/**\n * Extract the Output type from a StandardSchemaV1 schema.\n * Replaces `z.infer<S>` for generic schema inference.\n */\nexport type InferSchemaOutput<S> =\n S extends StandardSchemaV1<any, infer O> ? O : never;\n\nexport interface SchemaToJsonSchemaOptions {\n /**\n * Injected `zodToJsonSchema` function so that `shared` does not depend on\n * `zod-to-json-schema`. Required when the schema is a Zod v3 schema that\n * does not implement Standard JSON Schema V1.\n */\n zodToJsonSchema?: (\n schema: unknown,\n options?: { $refStrategy?: string },\n ) => Record<string, unknown>;\n}\n\n/**\n * Check whether a schema implements the Standard JSON Schema V1 protocol.\n */\nfunction hasStandardJsonSchema(\n schema: StandardSchemaV1,\n): schema is StandardSchemaV1 & StandardJSONSchemaV1 {\n const props = schema[\"~standard\"];\n return (\n props != null &&\n typeof props === \"object\" &&\n \"jsonSchema\" in props &&\n props.jsonSchema != null &&\n typeof props.jsonSchema === \"object\" &&\n \"input\" in props.jsonSchema &&\n typeof props.jsonSchema.input === \"function\"\n );\n}\n\n/**\n * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.\n *\n * Strategy:\n * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),\n * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.\n * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the\n * injected `zodToJsonSchema()` function.\n * 3. Otherwise throw a descriptive error.\n */\nexport function schemaToJsonSchema(\n schema: StandardSchemaV1,\n options?: SchemaToJsonSchemaOptions,\n): Record<string, unknown> {\n // 1. Standard JSON Schema V1\n if (hasStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n }\n\n // 2. Zod v3 fallback\n const vendor = schema[\"~standard\"].vendor;\n if (vendor === \"zod\" && options?.zodToJsonSchema) {\n return options.zodToJsonSchema(schema, { $refStrategy: \"none\" });\n }\n\n throw new Error(\n `Cannot convert schema to JSON Schema. The schema (vendor: \"${vendor}\") does not implement Standard JSON Schema V1 ` +\n `and no zodToJsonSchema fallback is available. ` +\n `Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) ` +\n `or pass a zodToJsonSchema function in options.`,\n );\n}\n"],"mappings":";;;;;AA6BA,SAAS,sBACP,QACmD;CACnD,MAAM,QAAQ,OAAO;AACrB,QACE,SAAS,QACT,OAAO,UAAU,YACjB,gBAAgB,SAChB,MAAM,cAAc,QACpB,OAAO,MAAM,eAAe,YAC5B,WAAW,MAAM,cACjB,OAAO,MAAM,WAAW,UAAU;;;;;;;;;;;;AActC,SAAgB,mBACd,QACA,SACyB;AAEzB,KAAI,sBAAsB,OAAO,CAC/B,QAAO,OAAO,aAAa,WAAW,MAAM,EAAE,QAAQ,YAAY,CAAC;CAIrE,MAAM,SAAS,OAAO,aAAa;AACnC,KAAI,WAAW,SAAS,SAAS,gBAC/B,QAAO,QAAQ,gBAAgB,QAAQ,EAAE,cAAc,QAAQ,CAAC;AAGlE,OAAM,IAAI,MACR,8DAA8D,OAAO,yOAItE"}
@@ -0,0 +1,32 @@
1
+ import { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
2
+
3
+ //#region src/standard-schema.d.ts
4
+ /**
5
+ * Extract the Output type from a StandardSchemaV1 schema.
6
+ * Replaces `z.infer<S>` for generic schema inference.
7
+ */
8
+ type InferSchemaOutput<S> = S extends StandardSchemaV1<any, infer O> ? O : never;
9
+ interface SchemaToJsonSchemaOptions {
10
+ /**
11
+ * Injected `zodToJsonSchema` function so that `shared` does not depend on
12
+ * `zod-to-json-schema`. Required when the schema is a Zod v3 schema that
13
+ * does not implement Standard JSON Schema V1.
14
+ */
15
+ zodToJsonSchema?: (schema: unknown, options?: {
16
+ $refStrategy?: string;
17
+ }) => Record<string, unknown>;
18
+ }
19
+ /**
20
+ * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.
21
+ *
22
+ * Strategy:
23
+ * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
24
+ * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
25
+ * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
26
+ * injected `zodToJsonSchema()` function.
27
+ * 3. Otherwise throw a descriptive error.
28
+ */
29
+ declare function schemaToJsonSchema(schema: StandardSchemaV1, options?: SchemaToJsonSchemaOptions): Record<string, unknown>;
30
+ //#endregion
31
+ export { InferSchemaOutput, SchemaToJsonSchemaOptions, type StandardJSONSchemaV1, type StandardSchemaV1, schemaToJsonSchema };
32
+ //# sourceMappingURL=standard-schema.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard-schema.d.cts","names":[],"sources":["../src/standard-schema.ts"],"mappings":";;;;AAWA;;;KAAY,iBAAA,MACV,CAAA,SAAU,gBAAA,iBAAiC,CAAA;AAAA,UAE5B,yBAAA;EAFf;;;;;EAQA,eAAA,IACE,MAAA,WACA,OAAA;IAAY,YAAA;EAAA,MACT,MAAA;AAAA;;;;;;;;;AA+BP;;iBAAgB,kBAAA,CACd,MAAA,EAAQ,gBAAA,EACR,OAAA,GAAU,yBAAA,GACT,MAAA"}
@@ -0,0 +1,32 @@
1
+ import { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
2
+
3
+ //#region src/standard-schema.d.ts
4
+ /**
5
+ * Extract the Output type from a StandardSchemaV1 schema.
6
+ * Replaces `z.infer<S>` for generic schema inference.
7
+ */
8
+ type InferSchemaOutput<S> = S extends StandardSchemaV1<any, infer O> ? O : never;
9
+ interface SchemaToJsonSchemaOptions {
10
+ /**
11
+ * Injected `zodToJsonSchema` function so that `shared` does not depend on
12
+ * `zod-to-json-schema`. Required when the schema is a Zod v3 schema that
13
+ * does not implement Standard JSON Schema V1.
14
+ */
15
+ zodToJsonSchema?: (schema: unknown, options?: {
16
+ $refStrategy?: string;
17
+ }) => Record<string, unknown>;
18
+ }
19
+ /**
20
+ * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.
21
+ *
22
+ * Strategy:
23
+ * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
24
+ * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
25
+ * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
26
+ * injected `zodToJsonSchema()` function.
27
+ * 3. Otherwise throw a descriptive error.
28
+ */
29
+ declare function schemaToJsonSchema(schema: StandardSchemaV1, options?: SchemaToJsonSchemaOptions): Record<string, unknown>;
30
+ //#endregion
31
+ export { InferSchemaOutput, SchemaToJsonSchemaOptions, type StandardJSONSchemaV1, type StandardSchemaV1, schemaToJsonSchema };
32
+ //# sourceMappingURL=standard-schema.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard-schema.d.mts","names":[],"sources":["../src/standard-schema.ts"],"mappings":";;;;AAWA;;;KAAY,iBAAA,MACV,CAAA,SAAU,gBAAA,iBAAiC,CAAA;AAAA,UAE5B,yBAAA;EAFf;;;;;EAQA,eAAA,IACE,MAAA,WACA,OAAA;IAAY,YAAA;EAAA,MACT,MAAA;AAAA;;;;;;;;;AA+BP;;iBAAgB,kBAAA,CACd,MAAA,EAAQ,gBAAA,EACR,OAAA,GAAU,yBAAA,GACT,MAAA"}
@@ -0,0 +1,28 @@
1
+ //#region src/standard-schema.ts
2
+ /**
3
+ * Check whether a schema implements the Standard JSON Schema V1 protocol.
4
+ */
5
+ function hasStandardJsonSchema(schema) {
6
+ const props = schema["~standard"];
7
+ return props != null && typeof props === "object" && "jsonSchema" in props && props.jsonSchema != null && typeof props.jsonSchema === "object" && "input" in props.jsonSchema && typeof props.jsonSchema.input === "function";
8
+ }
9
+ /**
10
+ * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.
11
+ *
12
+ * Strategy:
13
+ * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
14
+ * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
15
+ * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
16
+ * injected `zodToJsonSchema()` function.
17
+ * 3. Otherwise throw a descriptive error.
18
+ */
19
+ function schemaToJsonSchema(schema, options) {
20
+ if (hasStandardJsonSchema(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
21
+ const vendor = schema["~standard"].vendor;
22
+ if (vendor === "zod" && options?.zodToJsonSchema) return options.zodToJsonSchema(schema, { $refStrategy: "none" });
23
+ throw new Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${vendor}") does not implement Standard JSON Schema V1 and no zodToJsonSchema fallback is available. Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) or pass a zodToJsonSchema function in options.`);
24
+ }
25
+
26
+ //#endregion
27
+ export { schemaToJsonSchema };
28
+ //# sourceMappingURL=standard-schema.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard-schema.mjs","names":[],"sources":["../src/standard-schema.ts"],"sourcesContent":["import type {\n StandardSchemaV1,\n StandardJSONSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type { StandardSchemaV1, StandardJSONSchemaV1 };\n\n/**\n * Extract the Output type from a StandardSchemaV1 schema.\n * Replaces `z.infer<S>` for generic schema inference.\n */\nexport type InferSchemaOutput<S> =\n S extends StandardSchemaV1<any, infer O> ? O : never;\n\nexport interface SchemaToJsonSchemaOptions {\n /**\n * Injected `zodToJsonSchema` function so that `shared` does not depend on\n * `zod-to-json-schema`. Required when the schema is a Zod v3 schema that\n * does not implement Standard JSON Schema V1.\n */\n zodToJsonSchema?: (\n schema: unknown,\n options?: { $refStrategy?: string },\n ) => Record<string, unknown>;\n}\n\n/**\n * Check whether a schema implements the Standard JSON Schema V1 protocol.\n */\nfunction hasStandardJsonSchema(\n schema: StandardSchemaV1,\n): schema is StandardSchemaV1 & StandardJSONSchemaV1 {\n const props = schema[\"~standard\"];\n return (\n props != null &&\n typeof props === \"object\" &&\n \"jsonSchema\" in props &&\n props.jsonSchema != null &&\n typeof props.jsonSchema === \"object\" &&\n \"input\" in props.jsonSchema &&\n typeof props.jsonSchema.input === \"function\"\n );\n}\n\n/**\n * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.\n *\n * Strategy:\n * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),\n * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.\n * 2. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the\n * injected `zodToJsonSchema()` function.\n * 3. Otherwise throw a descriptive error.\n */\nexport function schemaToJsonSchema(\n schema: StandardSchemaV1,\n options?: SchemaToJsonSchemaOptions,\n): Record<string, unknown> {\n // 1. Standard JSON Schema V1\n if (hasStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n }\n\n // 2. Zod v3 fallback\n const vendor = schema[\"~standard\"].vendor;\n if (vendor === \"zod\" && options?.zodToJsonSchema) {\n return options.zodToJsonSchema(schema, { $refStrategy: \"none\" });\n }\n\n throw new Error(\n `Cannot convert schema to JSON Schema. The schema (vendor: \"${vendor}\") does not implement Standard JSON Schema V1 ` +\n `and no zodToJsonSchema fallback is available. ` +\n `Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) ` +\n `or pass a zodToJsonSchema function in options.`,\n );\n}\n"],"mappings":";;;;AA6BA,SAAS,sBACP,QACmD;CACnD,MAAM,QAAQ,OAAO;AACrB,QACE,SAAS,QACT,OAAO,UAAU,YACjB,gBAAgB,SAChB,MAAM,cAAc,QACpB,OAAO,MAAM,eAAe,YAC5B,WAAW,MAAM,cACjB,OAAO,MAAM,WAAW,UAAU;;;;;;;;;;;;AActC,SAAgB,mBACd,QACA,SACyB;AAEzB,KAAI,sBAAsB,OAAO,CAC/B,QAAO,OAAO,aAAa,WAAW,MAAM,EAAE,QAAQ,YAAY,CAAC;CAIrE,MAAM,SAAS,OAAO,aAAa;AACnC,KAAI,WAAW,SAAS,SAAS,gBAC/B,QAAO,QAAQ,gBAAgB,QAAQ,EAAE,cAAc,QAAQ,CAAC;AAGlE,OAAM,IAAI,MACR,8DAA8D,OAAO,yOAItE"}
package/dist/types.d.cts CHANGED
@@ -16,6 +16,7 @@ interface RuntimeInfo {
16
16
  version: string;
17
17
  agents: Record<string, AgentDescription>;
18
18
  audioFileTranscriptionEnabled: boolean;
19
+ a2uiEnabled?: boolean;
19
20
  }
20
21
  //#endregion
21
22
  export { AgentDescription, MaybePromise, NonEmptyRecord, RuntimeInfo };
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"mappings":";KAAY,YAAA,MAAkB,CAAA,GAAI,WAAA,CAAY,CAAA;AAA9C;;;AAAA,KAKY,cAAA,MACV,CAAA,SAAU,MAAA,0BACA,CAAA,yBAEJ,CAAA;;;;UAMS,gBAAA;EACf,IAAA;EACA,SAAA;EACA,WAAA;AAAA;AAAA,UAGe,WAAA;EACf,OAAA;EACA,MAAA,EAAQ,MAAA,SAAe,gBAAA;EACvB,6BAAA;AAAA"}
1
+ {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"mappings":";KAAY,YAAA,MAAkB,CAAA,GAAI,WAAA,CAAY,CAAA;AAA9C;;;AAAA,KAKY,cAAA,MACV,CAAA,SAAU,MAAA,0BACA,CAAA,yBAEJ,CAAA;;;;UAMS,gBAAA;EACf,IAAA;EACA,SAAA;EACA,WAAA;AAAA;AAAA,UAGe,WAAA;EACf,OAAA;EACA,MAAA,EAAQ,MAAA,SAAe,gBAAA;EACvB,6BAAA;EACA,WAAA;AAAA"}
package/dist/types.d.mts CHANGED
@@ -16,6 +16,7 @@ interface RuntimeInfo {
16
16
  version: string;
17
17
  agents: Record<string, AgentDescription>;
18
18
  audioFileTranscriptionEnabled: boolean;
19
+ a2uiEnabled?: boolean;
19
20
  }
20
21
  //#endregion
21
22
  export { AgentDescription, MaybePromise, NonEmptyRecord, RuntimeInfo };
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";KAAY,YAAA,MAAkB,CAAA,GAAI,WAAA,CAAY,CAAA;AAA9C;;;AAAA,KAKY,cAAA,MACV,CAAA,SAAU,MAAA,0BACA,CAAA,yBAEJ,CAAA;;;;UAMS,gBAAA;EACf,IAAA;EACA,SAAA;EACA,WAAA;AAAA;AAAA,UAGe,WAAA;EACf,OAAA;EACA,MAAA,EAAQ,MAAA,SAAe,gBAAA;EACvB,6BAAA;AAAA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";KAAY,YAAA,MAAkB,CAAA,GAAI,WAAA,CAAY,CAAA;AAA9C;;;AAAA,KAKY,cAAA,MACV,CAAA,SAAU,MAAA,0BACA,CAAA,yBAEJ,CAAA;;;;UAMS,gBAAA;EACf,IAAA;EACA,SAAA;EACA,WAAA;AAAA;AAAA,UAGe,WAAA;EACf,OAAA;EACA,MAAA,EAAQ,MAAA,SAAe,gBAAA;EACvB,6BAAA;EACA,WAAA;AAAA"}
package/dist/utils.cjs CHANGED
@@ -9,12 +9,33 @@ function randomUUID() {
9
9
  }
10
10
  function partialJSONParse(json) {
11
11
  try {
12
- return partial_json.parse(json);
12
+ const parsed = partial_json.parse(json);
13
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
14
+ console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
15
+ return {};
13
16
  } catch (error) {
14
17
  return {};
15
18
  }
16
19
  }
17
20
  /**
21
+ * Safely parses a JSON string into a plain object for tool arguments.
22
+ * Handles two failure modes:
23
+ * 1. Malformed JSON (SyntaxError from JSON.parse)
24
+ * 2. Valid JSON that isn't a plain object (e.g. "", [], null, 42, true)
25
+ * Falls back to an empty object for safety in both cases.
26
+ */
27
+ function safeParseToolArgs(raw) {
28
+ try {
29
+ const parsed = JSON.parse(raw);
30
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
31
+ console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
32
+ return {};
33
+ } catch {
34
+ console.warn("[CopilotKit] Failed to parse tool arguments, falling back to empty object");
35
+ return {};
36
+ }
37
+ }
38
+ /**
18
39
  * Returns an exponential backoff function suitable for Phoenix.js
19
40
  * `reconnectAfterMs` and `rejoinAfterMs` options.
20
41
  *
@@ -32,4 +53,5 @@ function phoenixExponentialBackoff(baseMs, maxMs) {
32
53
  exports.partialJSONParse = partialJSONParse;
33
54
  exports.phoenixExponentialBackoff = phoenixExponentialBackoff;
34
55
  exports.randomUUID = randomUUID;
56
+ exports.safeParseToolArgs = safeParseToolArgs;
35
57
  //# sourceMappingURL=utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":["PartialJSON"],"sources":["../src/utils.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport * as PartialJSON from \"partial-json\";\n\nexport function randomUUID() {\n return uuidv4();\n}\n\nexport function partialJSONParse(json: string) {\n try {\n return PartialJSON.parse(json);\n } catch (error) {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n"],"mappings":";;;;;;AAGA,SAAgB,aAAa;AAC3B,sBAAe;;AAGjB,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;AACF,SAAOA,aAAY,MAAM,KAAK;UACvB,OAAO;AACd,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM"}
1
+ {"version":3,"file":"utils.cjs","names":["PartialJSON"],"sources":["../src/utils.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport * as PartialJSON from \"partial-json\";\n\nexport function randomUUID() {\n return uuidv4();\n}\n\nexport function partialJSONParse(json: string): unknown {\n try {\n const parsed = PartialJSON.parse(json);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch (error) {\n return {};\n }\n}\n\n/**\n * Safely parses a JSON string into a plain object for tool arguments.\n * Handles two failure modes:\n * 1. Malformed JSON (SyntaxError from JSON.parse)\n * 2. Valid JSON that isn't a plain object (e.g. \"\", [], null, 42, true)\n * Falls back to an empty object for safety in both cases.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n"],"mappings":";;;;;;AAGA,SAAgB,aAAa;AAC3B,sBAAe;;AAGjB,SAAgB,iBAAiB,MAAuB;AACtD,KAAI;EACF,MAAM,SAASA,aAAY,MAAM,KAAK;AACtC,MACE,OAAO,WAAW,YAClB,WAAW,QACX,CAAC,MAAM,QAAQ,OAAO,CAEtB,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;UACF,OAAO;AACd,SAAO,EAAE;;;;;;;;;;AAWb,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MACE,OAAO,WAAW,YAClB,WAAW,QACX,CAAC,MAAM,QAAQ,OAAO,CAEtB,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM"}
package/dist/utils.d.cts CHANGED
@@ -1,6 +1,14 @@
1
1
  //#region src/utils.d.ts
2
2
  declare function randomUUID(): string;
3
- declare function partialJSONParse(json: string): any;
3
+ declare function partialJSONParse(json: string): unknown;
4
+ /**
5
+ * Safely parses a JSON string into a plain object for tool arguments.
6
+ * Handles two failure modes:
7
+ * 1. Malformed JSON (SyntaxError from JSON.parse)
8
+ * 2. Valid JSON that isn't a plain object (e.g. "", [], null, 42, true)
9
+ * Falls back to an empty object for safety in both cases.
10
+ */
11
+ declare function safeParseToolArgs(raw: string): Record<string, unknown>;
4
12
  /**
5
13
  * Returns an exponential backoff function suitable for Phoenix.js
6
14
  * `reconnectAfterMs` and `rejoinAfterMs` options.
@@ -13,5 +21,5 @@ declare function partialJSONParse(json: string): any;
13
21
  */
14
22
  declare function phoenixExponentialBackoff(baseMs: number, maxMs: number): (tries: number) => number;
15
23
  //#endregion
16
- export { partialJSONParse, phoenixExponentialBackoff, randomUUID };
24
+ export { partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs };
17
25
  //# sourceMappingURL=utils.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","names":[],"sources":["../src/utils.ts"],"mappings":";iBAGgB,UAAA,CAAA;AAAA,iBAIA,gBAAA,CAAiB,IAAA;;;;;AAAjC;;;;;AAkBA;iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA"}
1
+ {"version":3,"file":"utils.d.cts","names":[],"sources":["../src/utils.ts"],"mappings":";iBAGgB,UAAA,CAAA;AAAA,iBAIA,gBAAA,CAAiB,IAAA;;;;;AAAjC;;;iBA0BgB,iBAAA,CAAkB,GAAA,WAAc,MAAA;;AAAhD;;;;;AAgCA;;;;iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA"}
package/dist/utils.d.mts CHANGED
@@ -1,6 +1,14 @@
1
1
  //#region src/utils.d.ts
2
2
  declare function randomUUID(): string;
3
- declare function partialJSONParse(json: string): any;
3
+ declare function partialJSONParse(json: string): unknown;
4
+ /**
5
+ * Safely parses a JSON string into a plain object for tool arguments.
6
+ * Handles two failure modes:
7
+ * 1. Malformed JSON (SyntaxError from JSON.parse)
8
+ * 2. Valid JSON that isn't a plain object (e.g. "", [], null, 42, true)
9
+ * Falls back to an empty object for safety in both cases.
10
+ */
11
+ declare function safeParseToolArgs(raw: string): Record<string, unknown>;
4
12
  /**
5
13
  * Returns an exponential backoff function suitable for Phoenix.js
6
14
  * `reconnectAfterMs` and `rejoinAfterMs` options.
@@ -13,5 +21,5 @@ declare function partialJSONParse(json: string): any;
13
21
  */
14
22
  declare function phoenixExponentialBackoff(baseMs: number, maxMs: number): (tries: number) => number;
15
23
  //#endregion
16
- export { partialJSONParse, phoenixExponentialBackoff, randomUUID };
24
+ export { partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs };
17
25
  //# sourceMappingURL=utils.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../src/utils.ts"],"mappings":";iBAGgB,UAAA,CAAA;AAAA,iBAIA,gBAAA,CAAiB,IAAA;;;;;AAAjC;;;;;AAkBA;iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../src/utils.ts"],"mappings":";iBAGgB,UAAA,CAAA;AAAA,iBAIA,gBAAA,CAAiB,IAAA;;;;;AAAjC;;;iBA0BgB,iBAAA,CAAkB,GAAA,WAAc,MAAA;;AAAhD;;;;;AAgCA;;;;iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA"}
package/dist/utils.mjs CHANGED
@@ -7,12 +7,33 @@ function randomUUID() {
7
7
  }
8
8
  function partialJSONParse(json) {
9
9
  try {
10
- return PartialJSON.parse(json);
10
+ const parsed = PartialJSON.parse(json);
11
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
12
+ console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
13
+ return {};
11
14
  } catch (error) {
12
15
  return {};
13
16
  }
14
17
  }
15
18
  /**
19
+ * Safely parses a JSON string into a plain object for tool arguments.
20
+ * Handles two failure modes:
21
+ * 1. Malformed JSON (SyntaxError from JSON.parse)
22
+ * 2. Valid JSON that isn't a plain object (e.g. "", [], null, 42, true)
23
+ * Falls back to an empty object for safety in both cases.
24
+ */
25
+ function safeParseToolArgs(raw) {
26
+ try {
27
+ const parsed = JSON.parse(raw);
28
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
29
+ console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
30
+ return {};
31
+ } catch {
32
+ console.warn("[CopilotKit] Failed to parse tool arguments, falling back to empty object");
33
+ return {};
34
+ }
35
+ }
36
+ /**
16
37
  * Returns an exponential backoff function suitable for Phoenix.js
17
38
  * `reconnectAfterMs` and `rejoinAfterMs` options.
18
39
  *
@@ -27,5 +48,5 @@ function phoenixExponentialBackoff(baseMs, maxMs) {
27
48
  }
28
49
 
29
50
  //#endregion
30
- export { partialJSONParse, phoenixExponentialBackoff, randomUUID };
51
+ export { partialJSONParse, phoenixExponentialBackoff, randomUUID, safeParseToolArgs };
31
52
  //# sourceMappingURL=utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":["uuidv4"],"sources":["../src/utils.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport * as PartialJSON from \"partial-json\";\n\nexport function randomUUID() {\n return uuidv4();\n}\n\nexport function partialJSONParse(json: string) {\n try {\n return PartialJSON.parse(json);\n } catch (error) {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n"],"mappings":";;;;AAGA,SAAgB,aAAa;AAC3B,QAAOA,IAAQ;;AAGjB,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;AACF,SAAO,YAAY,MAAM,KAAK;UACvB,OAAO;AACd,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM"}
1
+ {"version":3,"file":"utils.mjs","names":["uuidv4"],"sources":["../src/utils.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport * as PartialJSON from \"partial-json\";\n\nexport function randomUUID() {\n return uuidv4();\n}\n\nexport function partialJSONParse(json: string): unknown {\n try {\n const parsed = PartialJSON.parse(json);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch (error) {\n return {};\n }\n}\n\n/**\n * Safely parses a JSON string into a plain object for tool arguments.\n * Handles two failure modes:\n * 1. Malformed JSON (SyntaxError from JSON.parse)\n * 2. Valid JSON that isn't a plain object (e.g. \"\", [], null, 42, true)\n * Falls back to an empty object for safety in both cases.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n"],"mappings":";;;;AAGA,SAAgB,aAAa;AAC3B,QAAOA,IAAQ;;AAGjB,SAAgB,iBAAiB,MAAuB;AACtD,KAAI;EACF,MAAM,SAAS,YAAY,MAAM,KAAK;AACtC,MACE,OAAO,WAAW,YAClB,WAAW,QACX,CAAC,MAAM,QAAQ,OAAO,CAEtB,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;UACF,OAAO;AACd,SAAO,EAAE;;;;;;;;;;AAWb,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MACE,OAAO,WAAW,YAClB,WAAW,QACX,CAAC,MAAM,QAAQ,OAAO,CAEtB,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkitnext/shared",
3
- "version": "1.53.1-next.1",
3
+ "version": "1.54.0-next.3",
4
4
  "description": "Shared utilities and types for CopilotKit2",
5
5
  "main": "./dist/index.cjs",
6
6
  "types": "./dist/index.d.cts",
@@ -19,16 +19,23 @@
19
19
  },
20
20
  "devDependencies": {
21
21
  "@types/node": "^22.15.3",
22
+ "@valibot/to-json-schema": "^1.5.0",
23
+ "arktype": "^2.1.29",
22
24
  "eslint": "^9.30.0",
23
25
  "tsdown": "^0.20.3",
24
26
  "typescript": "5.8.2",
25
- "@copilotkitnext/eslint-config": "1.53.1-next.1",
26
- "@copilotkitnext/typescript-config": "1.53.1-next.1"
27
+ "valibot": "^1.2.0",
28
+ "vitest": "^4.0.18",
29
+ "zod": "^3.25.75",
30
+ "zod-to-json-schema": "^3.24.6",
31
+ "@copilotkitnext/eslint-config": "1.54.0-next.3",
32
+ "@copilotkitnext/typescript-config": "1.54.0-next.3"
27
33
  },
28
34
  "dependencies": {
29
35
  "@ag-ui/client": "0.0.47",
30
- "uuid": "^11.1.0",
31
- "partial-json": "^0.1.7"
36
+ "@standard-schema/spec": "^1.1.0",
37
+ "partial-json": "^0.1.7",
38
+ "uuid": "^11.1.0"
32
39
  },
33
40
  "engines": {
34
41
  "node": ">=18"
@@ -39,6 +46,8 @@
39
46
  "dev": "tsdown --watch",
40
47
  "lint": "eslint .",
41
48
  "check-types": "tsc --noEmit",
49
+ "test": "vitest run",
50
+ "test:watch": "vitest",
42
51
  "publint": "publint .",
43
52
  "attw": "attw --pack . --profile node16"
44
53
  }
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: "node",
6
+ globals: true,
7
+ include: ["src/**/__tests__/**/*.{test,spec}.ts"],
8
+ reporters: [["default", { summary: false }]],
9
+ silent: true,
10
+ },
11
+ });