@tanstack/ai 0.22.1 → 0.23.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.
- package/README.md +1 -1
- package/dist/esm/activities/chat/middleware/types.d.ts +8 -11
- package/dist/esm/activities/chat/tools/schema-converter.js +10 -3
- package/dist/esm/activities/chat/tools/schema-converter.js.map +1 -1
- package/dist/esm/client.d.ts +44 -0
- package/dist/esm/client.js +65 -0
- package/dist/esm/client.js.map +1 -0
- package/dist/esm/types.d.ts +33 -6
- package/package.json +7 -2
- package/src/activities/chat/middleware/types.ts +8 -13
- package/src/activities/chat/tools/schema-converter.ts +32 -14
- package/src/client.ts +132 -0
- package/src/types.ts +35 -6
package/README.md
CHANGED
|
@@ -186,7 +186,7 @@ Official adapters include:
|
|
|
186
186
|
|
|
187
187
|
| Package | Use it for |
|
|
188
188
|
| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
|
|
189
|
-
| [`@tanstack/ai-openrouter`](https://tanstack.com/ai/latest/docs/adapters/openrouter) | 300+ models through one OpenRouter API
|
|
189
|
+
| [`@tanstack/ai-openrouter`](https://tanstack.com/ai/latest/docs/adapters/openrouter) | 300+ models through one OpenRouter API, with per-request cost tracking |
|
|
190
190
|
| [`@tanstack/ai-openai`](https://tanstack.com/ai/latest/docs/adapters/openai) | OpenAI chat, image, video, speech, transcription, realtime, and provider tools |
|
|
191
191
|
| [`@tanstack/ai-anthropic`](https://tanstack.com/ai/latest/docs/adapters/anthropic) | Anthropic Claude chat, thinking, tools, and structured outputs |
|
|
192
192
|
| [`@tanstack/ai-gemini`](https://tanstack.com/ai/latest/docs/adapters/gemini) | Google Gemini chat, image, speech, and audio generation |
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { JSONSchema, ModelMessage, StreamChunk, Tool, ToolCall } from '../../../types.js';
|
|
1
|
+
import { JSONSchema, ModelMessage, StreamChunk, Tool, ToolCall, UsageTotals } from '../../../types.js';
|
|
2
2
|
import { SystemPrompt } from '../../../system-prompts.js';
|
|
3
3
|
/**
|
|
4
4
|
* Phase of the chat middleware lifecycle.
|
|
@@ -203,11 +203,12 @@ export interface ToolPhaseCompleteInfo {
|
|
|
203
203
|
/**
|
|
204
204
|
* Token usage statistics passed to the onUsage hook.
|
|
205
205
|
* Extracted from the RUN_FINISHED chunk when usage data is present.
|
|
206
|
+
*
|
|
207
|
+
* Includes optional provider-reported `cost`/`costDetails` (see {@link UsageTotals}).
|
|
208
|
+
* Kept as an interface extending `UsageTotals` to preserve declaration merging for
|
|
209
|
+
* this publicly exported type.
|
|
206
210
|
*/
|
|
207
|
-
export interface UsageInfo {
|
|
208
|
-
promptTokens: number;
|
|
209
|
-
completionTokens: number;
|
|
210
|
-
totalTokens: number;
|
|
211
|
+
export interface UsageInfo extends UsageTotals {
|
|
211
212
|
}
|
|
212
213
|
/**
|
|
213
214
|
* Information passed to onFinish.
|
|
@@ -219,12 +220,8 @@ export interface FinishInfo {
|
|
|
219
220
|
duration: number;
|
|
220
221
|
/** Final accumulated text content */
|
|
221
222
|
content: string;
|
|
222
|
-
/** Final usage totals, if available */
|
|
223
|
-
usage?:
|
|
224
|
-
promptTokens: number;
|
|
225
|
-
completionTokens: number;
|
|
226
|
-
totalTokens: number;
|
|
227
|
-
} | undefined;
|
|
223
|
+
/** Final usage totals, if available (optionally including provider-reported cost) */
|
|
224
|
+
usage?: UsageTotals | undefined;
|
|
228
225
|
}
|
|
229
226
|
/**
|
|
230
227
|
* Information passed to onAbort.
|
|
@@ -6,12 +6,19 @@ function toJsonSchema(obj) {
|
|
|
6
6
|
}
|
|
7
7
|
return result;
|
|
8
8
|
}
|
|
9
|
+
function isPropertyCarrier(schema) {
|
|
10
|
+
return (typeof schema === "object" || typeof schema === "function") && schema !== null;
|
|
11
|
+
}
|
|
9
12
|
function isStandardJSONSchema(schema) {
|
|
10
|
-
|
|
11
|
-
|
|
13
|
+
if (!isPropertyCarrier(schema) || !("~standard" in schema)) return false;
|
|
14
|
+
const standard = schema["~standard"];
|
|
15
|
+
if (typeof standard !== "object" || standard === null || !("version" in standard) || standard.version !== 1 || !("jsonSchema" in standard) || typeof standard.jsonSchema !== "object" || standard.jsonSchema === null || !("input" in standard.jsonSchema)) {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
return typeof standard.jsonSchema.input === "function";
|
|
12
19
|
}
|
|
13
20
|
function isStandardSchema(schema) {
|
|
14
|
-
return
|
|
21
|
+
return isPropertyCarrier(schema) && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "version" in schema["~standard"] && schema["~standard"].version === 1 && "validate" in schema["~standard"] && typeof schema["~standard"].validate === "function";
|
|
15
22
|
}
|
|
16
23
|
function makeStructuredOutputCompatible(schema, originalRequired = []) {
|
|
17
24
|
const result = { ...schema };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-converter.js","sources":["../../../../../src/activities/chat/tools/schema-converter.ts"],"sourcesContent":["import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from '@standard-schema/spec'\nimport type { JSONSchema, SchemaInput } from '../../../types'\n\n/**\n * Build a JSONSchema object from any plain key/value source. The `JSONSchema`\n * interface's `[key: string]: any` index signature makes every property\n * assignable through bracket access without a type cast — copying keys here\n * lets us narrow either `Record<string, unknown>` (returned by\n * `~standard.jsonSchema.input()`) or a `JSONSchema` (from the SchemaInput\n * pass-through arm) into the typed view used by the rest of this module.\n *\n * Accepts `object` so callers don't need a cast when narrowing from union\n * types like `SchemaInput`.\n */\nfunction toJsonSchema(obj: object): JSONSchema {\n const result: JSONSchema = {}\n for (const [key, value] of Object.entries(obj)) {\n if (key === '$schema') continue // not needed by LLM providers\n result[key] = value\n }\n return result\n}\n\n/**\n * Check if a value is a Standard JSON Schema compliant schema.\n * Standard JSON Schema compliant libraries (Zod v4+, ArkType, Valibot with toStandardJsonSchema, etc.)\n * implement the '~standard' property with jsonSchema converter methods.\n */\nexport function isStandardJSONSchema(\n schema: unknown,\n): schema is StandardJSONSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof (schema as StandardJSONSchemaV1)['~standard'] === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime guard for caller-provided unknown; type assertion narrows but doesn't validate the wire payload\n (schema as StandardJSONSchemaV1)['~standard'].version === 1 &&\n typeof (schema as StandardJSONSchemaV1)['~standard'].jsonSchema ===\n 'object' &&\n typeof (schema as StandardJSONSchemaV1)['~standard'].jsonSchema.input ===\n 'function'\n )\n}\n\n/**\n * Check if a value is a Standard Schema compliant schema (for validation).\n * Standard Schema compliant libraries implement the '~standard' property with a validate function.\n */\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof schema['~standard'] === 'object' &&\n schema['~standard'] !== null &&\n 'version' in schema['~standard'] &&\n schema['~standard'].version === 1 &&\n 'validate' in schema['~standard'] &&\n typeof schema['~standard'].validate === 'function'\n )\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nfunction makeStructuredOutputCompatible(\n schema: JSONSchema,\n originalRequired: Array<string> = [],\n): JSONSchema {\n const result: JSONSchema = { ...schema }\n\n // Handle object types\n if (result.type === 'object' && result.properties) {\n const properties: Record<string, JSONSchema> = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n\n // Transform each property\n for (const propName of allPropertyNames) {\n const prop = properties[propName]\n if (!prop) continue\n const wasOptional = !originalRequired.includes(propName)\n\n // Recursively transform nested objects/arrays\n if (prop.type === 'object' && prop.properties) {\n const transformed = makeStructuredOutputCompatible(\n prop,\n prop.required || [],\n )\n properties[propName] = wasOptional\n ? { ...transformed, type: ['object', 'null'] }\n : transformed\n } else if (prop.type === 'array' && prop.items) {\n const items = Array.isArray(prop.items) ? prop.items[0] : prop.items\n const transformed: JSONSchema = {\n ...prop,\n items: items\n ? makeStructuredOutputCompatible(items, items.required || [])\n : prop.items,\n }\n properties[propName] = wasOptional\n ? { ...transformed, type: ['array', 'null'] }\n : transformed\n } else if (wasOptional) {\n // Make optional fields nullable by adding null to the type\n if (prop.type && !Array.isArray(prop.type)) {\n properties[propName] = {\n ...prop,\n type: [prop.type, 'null'],\n }\n } else if (Array.isArray(prop.type) && !prop.type.includes('null')) {\n properties[propName] = {\n ...prop,\n type: [...prop.type, 'null'],\n }\n }\n }\n }\n\n result.properties = properties\n // ALL properties must be required for OpenAI structured output\n result.required = allPropertyNames\n // additionalProperties must be false\n result.additionalProperties = false\n }\n\n // Handle array types with object items\n if (result.type === 'array' && result.items) {\n const items = Array.isArray(result.items) ? result.items[0] : result.items\n if (items) {\n result.items = makeStructuredOutputCompatible(items, items.required || [])\n }\n }\n\n return result\n}\n\n/**\n * Options for schema conversion\n */\nexport interface ConvertSchemaOptions {\n /**\n * When true, transforms the schema to be compatible with OpenAI's structured output requirements:\n * - All properties are added to the `required` array\n * - Optional fields get null added to their type union\n * - additionalProperties is set to false for all objects\n *\n * @default false\n */\n forStructuredOutput?: boolean\n}\n\n/**\n * Converts a Standard JSON Schema compliant schema or plain JSONSchema to JSON Schema format\n * compatible with LLM providers.\n *\n * Supports any schema library that implements the Standard JSON Schema spec (v1):\n * - Zod v4+ (natively supports StandardJSONSchemaV1)\n * - ArkType (natively supports StandardJSONSchemaV1)\n * - Valibot (via `toStandardJsonSchema()` from `@valibot/to-json-schema`)\n *\n * If the input is already a plain JSONSchema object, it is returned as-is.\n *\n * @param schema - Standard JSON Schema compliant schema or plain JSONSchema object to convert\n * @param options - Conversion options\n * @returns JSON Schema object that can be sent to LLM providers\n *\n * @example\n * ```typescript\n * // Using Zod v4+ (natively supports Standard JSON Schema)\n * import * as z from 'zod';\n *\n * const zodSchema = z.object({\n * location: z.string().describe('City name'),\n * unit: z.enum(['celsius', 'fahrenheit']).optional()\n * });\n *\n * const jsonSchema = convertSchemaToJsonSchema(zodSchema);\n *\n * @example\n * // Using ArkType (natively supports Standard JSON Schema)\n * import { type } from 'arktype';\n *\n * const arkSchema = type({\n * location: 'string',\n * unit: \"'celsius' | 'fahrenheit'\"\n * });\n *\n * const jsonSchema = convertSchemaToJsonSchema(arkSchema);\n *\n * @example\n * // Using Valibot (via toStandardJsonSchema)\n * import * as v from 'valibot';\n * import { toStandardJsonSchema } from '@valibot/to-json-schema';\n *\n * const valibotSchema = toStandardJsonSchema(v.object({\n * location: v.string(),\n * unit: v.optional(v.picklist(['celsius', 'fahrenheit']))\n * }));\n *\n * const jsonSchema = convertSchemaToJsonSchema(valibotSchema);\n *\n * @example\n * // Using JSONSchema directly (passes through unchanged)\n * const rawSchema = {\n * type: 'object',\n * properties: { location: { type: 'string' } },\n * required: ['location']\n * };\n * const result = convertSchemaToJsonSchema(rawSchema);\n * ```\n */\nexport function convertSchemaToJsonSchema(\n schema: SchemaInput | undefined,\n options: ConvertSchemaOptions = {},\n): JSONSchema | undefined {\n if (!schema) return undefined\n\n const { forStructuredOutput = false } = options\n\n // If it's a Standard JSON Schema compliant schema, use the standard interface\n if (isStandardJSONSchema(schema)) {\n const jsonSchema = schema['~standard'].jsonSchema.input({\n target: 'draft-07',\n })\n\n // Rebuild structurally so the typed JSONSchema view is acquired without\n // a `Record<string, unknown> as JSONSchema` cast; `toJsonSchema()` also\n // drops the `$schema` key which LLM providers don't need.\n let result: JSONSchema = toJsonSchema(jsonSchema)\n\n // Ensure object schemas always have type: \"object\"\n // If it has properties (even empty), it should be an object type\n if ('properties' in result && !result.type) {\n result.type = 'object'\n }\n\n // Ensure properties exists for object types (even if empty)\n if (result.type === 'object' && !('properties' in result)) {\n result.properties = {}\n }\n\n // Ensure required exists for object types (even if empty array)\n if (result.type === 'object' && !('required' in result)) {\n result.required = []\n }\n\n // Apply structured output transformation if requested\n if (forStructuredOutput) {\n result = makeStructuredOutputCompatible(result, result.required || [])\n }\n\n return result\n }\n\n // Detect Standard Schema validators (Zod, ArkType, Valibot, …) that don't\n // expose a `~standard.jsonSchema` converter. These would otherwise fall\n // through to the JSONSchema pass-through below and ship `{ '~standard': … }`\n // straight to the LLM provider, producing an opaque downstream error. Fail\n // fast with actionable guidance instead.\n if (isStandardSchema(schema)) {\n throw new Error(\n 'Schema is a Standard Schema validator but does not expose a JSON Schema ' +\n 'converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, ' +\n 'or wrap a Valibot schema with `toStandardJsonSchema()` from ' +\n '`@valibot/to-json-schema` before passing it as `outputSchema`.',\n )\n }\n\n // If it's not a Standard JSON Schema, assume it's already a JSONSchema and pass through\n // Still apply structured output transformation if requested\n\n // At this branch, `schema` is the plain `JSONSchema` arm of `SchemaInput`\n // (the two `~standard` arms were handled above). When no transformation\n // is requested we pass the schema through by reference to preserve\n // identity for callers that compare via `===`.\n if (typeof schema !== 'object') {\n // The SchemaInput union is object-shaped on every arm; if we ever hit a\n // non-object here, propagate it untouched and let the downstream\n // provider error loudly rather than silently widen.\n return schema\n }\n\n if (forStructuredOutput) {\n // Build a typed view structurally so we don't need a SchemaInput→JSONSchema\n // cast on the transformation path.\n const typedView = toJsonSchema(schema)\n return makeStructuredOutputCompatible(typedView, typedView.required || [])\n }\n\n return schema\n}\n\n/**\n * Validates data against a Standard Schema compliant schema.\n *\n * @param schema - Standard Schema compliant schema\n * @param data - Data to validate\n * @returns Validation result with success status, data or issues\n */\nexport async function validateWithStandardSchema<T>(\n schema: unknown,\n data: unknown,\n): Promise<\n | { success: true; data: T }\n | {\n success: false\n issues: Array<{ message: string; path?: Array<string> | undefined }>\n }\n> {\n if (!isStandardSchema(schema)) {\n // If it's not a Standard Schema, just return the data as-is\n return { success: true, data: data as T }\n }\n\n const result = await schema['~standard'].validate(data)\n\n if (!result.issues) {\n return { success: true, data: result.value as T }\n }\n\n return {\n success: false,\n issues: result.issues.map((issue) => ({\n message: issue.message || 'Validation failed',\n path: issue.path?.map(String),\n })),\n }\n}\n\n/**\n * Error thrown when Standard Schema validation fails. Carries the original\n * `issues` array so consumers (middleware `onError`, callers catching from\n * `chat({ outputSchema })`) can programmatically inspect each failure.\n */\nexport class StandardSchemaValidationError extends Error {\n override readonly name = 'StandardSchemaValidationError'\n readonly issues: ReadonlyArray<StandardSchemaV1.Issue>\n\n constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n super(\n `Validation failed: ${issues\n .map((i) => i.message || 'Validation failed')\n .join(', ')}`,\n )\n this.issues = issues\n }\n}\n\n/**\n * Synchronously validates data against a Standard Schema compliant schema.\n * Note: Some Standard Schema implementations may only support async validation.\n * In those cases, this function will throw.\n *\n * @param schema - Standard Schema compliant schema\n * @param data - Data to validate\n * @returns Parsed/validated data\n * @throws StandardSchemaValidationError if validation fails; Error if the\n * schema only supports async validation.\n */\nexport function parseWithStandardSchema<T>(schema: unknown, data: unknown): T {\n if (!isStandardSchema(schema)) {\n // If it's not a Standard Schema, just return the data as-is\n return data as T\n }\n\n const result = schema['~standard'].validate(data)\n\n // Handle async result (Promise)\n if (result instanceof Promise) {\n throw new Error(\n 'Schema validation returned a Promise. Use validateWithStandardSchema for async validation.',\n )\n }\n // Standard Schema validation returns { value } for success or { issues } for failure\n if (!result.issues) {\n return result.value as T\n }\n\n throw new StandardSchemaValidationError(result.issues)\n}\n"],"names":[],"mappings":"AAiBA,SAAS,aAAa,KAAyB;AAC7C,QAAM,SAAqB,CAAA;AAC3B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC9C,QAAI,QAAQ,UAAW;AACvB,WAAO,GAAG,IAAI;AAAA,EAChB;AACA,SAAO;AACT;AAOO,SAAS,qBACd,QACgC;AAChC,SACE,OAAO,WAAW,YAClB,WAAW,QACX,eAAe,UACf,OAAQ,OAAgC,WAAW,MAAM;AAAA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AAGA,QAAI,qBAAqB;AACvB,eAAS,+BAA+B,QAAQ,OAAO,YAAY,CAAA,CAAE;AAAA,IACvE;AAEA,WAAO;AAAA,EACT;AAOA,MAAI,iBAAiB,MAAM,GAAG;AAC5B,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAKJ;AASA,MAAI,OAAO,WAAW,UAAU;AAI9B,WAAO;AAAA,EACT;AAEA,MAAI,qBAAqB;AAGvB,UAAM,YAAY,aAAa,MAAM;AACrC,WAAO,+BAA+B,WAAW,UAAU,YAAY,CAAA,CAAE;AAAA,EAC3E;AAEA,SAAO;AACT;AA4CO,MAAM,sCAAsC,MAAM;AAAA,EACrC,OAAO;AAAA,EAChB;AAAA,EAET,YAAY,QAA+C;AACzD;AAAA,MACE,sBAAsB,OACnB,IAAI,CAAC,MAAM,EAAE,WAAW,mBAAmB,EAC3C,KAAK,IAAI,CAAC;AAAA,IAAA;AAEf,SAAK,SAAS;AAAA,EAChB;AACF;AAaO,SAAS,wBAA2B,QAAiB,MAAkB;AAC5E,MAAI,CAAC,iBAAiB,MAAM,GAAG;AAE7B,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,OAAO,WAAW,EAAE,SAAS,IAAI;AAGhD,MAAI,kBAAkB,SAAS;AAC7B,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEA,MAAI,CAAC,OAAO,QAAQ;AAClB,WAAO,OAAO;AAAA,EAChB;AAEA,QAAM,IAAI,8BAA8B,OAAO,MAAM;AACvD;"}
|
|
1
|
+
{"version":3,"file":"schema-converter.js","sources":["../../../../../src/activities/chat/tools/schema-converter.ts"],"sourcesContent":["import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from '@standard-schema/spec'\nimport type { JSONSchema, SchemaInput } from '../../../types'\n\n/**\n * Build a JSONSchema object from any plain key/value source. The `JSONSchema`\n * interface's `[key: string]: any` index signature makes every property\n * assignable through bracket access without a type cast — copying keys here\n * lets us narrow either `Record<string, unknown>` (returned by\n * `~standard.jsonSchema.input()`) or a `JSONSchema` (from the SchemaInput\n * pass-through arm) into the typed view used by the rest of this module.\n *\n * Accepts `object` so callers don't need a cast when narrowing from union\n * types like `SchemaInput`.\n */\nfunction toJsonSchema(obj: object): JSONSchema {\n const result: JSONSchema = {}\n for (const [key, value] of Object.entries(obj)) {\n if (key === '$schema') continue // not needed by LLM providers\n result[key] = value\n }\n return result\n}\n\n/**\n * Whether a value can carry a `~standard` property. Most schema libraries\n * (Zod, Valibot) return plain objects, but ArkType's `type()` returns a\n * *callable function* with `~standard` attached — so `typeof` must accept\n * both `'object'` and `'function'` or ArkType schemas are missed entirely\n * (issue #276).\n */\nfunction isPropertyCarrier(schema: unknown): schema is Record<string, unknown> {\n return (\n (typeof schema === 'object' || typeof schema === 'function') &&\n schema !== null\n )\n}\n\n/**\n * Check if a value is a Standard JSON Schema compliant schema.\n * Standard JSON Schema compliant libraries (Zod v4+, ArkType, Valibot with toStandardJsonSchema, etc.)\n * implement the '~standard' property with jsonSchema converter methods.\n */\nexport function isStandardJSONSchema(\n schema: unknown,\n): schema is StandardJSONSchemaV1 {\n if (!isPropertyCarrier(schema) || !('~standard' in schema)) return false\n\n const standard = schema['~standard']\n if (\n typeof standard !== 'object' ||\n standard === null ||\n !('version' in standard) ||\n standard.version !== 1 ||\n !('jsonSchema' in standard) ||\n typeof standard.jsonSchema !== 'object' ||\n standard.jsonSchema === null ||\n !('input' in standard.jsonSchema)\n ) {\n return false\n }\n\n return typeof standard.jsonSchema.input === 'function'\n}\n\n/**\n * Check if a value is a Standard Schema compliant schema (for validation).\n * Standard Schema compliant libraries implement the '~standard' property with a validate function.\n */\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n isPropertyCarrier(schema) &&\n '~standard' in schema &&\n typeof schema['~standard'] === 'object' &&\n schema['~standard'] !== null &&\n 'version' in schema['~standard'] &&\n schema['~standard'].version === 1 &&\n 'validate' in schema['~standard'] &&\n typeof schema['~standard'].validate === 'function'\n )\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nfunction makeStructuredOutputCompatible(\n schema: JSONSchema,\n originalRequired: Array<string> = [],\n): JSONSchema {\n const result: JSONSchema = { ...schema }\n\n // Handle object types\n if (result.type === 'object' && result.properties) {\n const properties: Record<string, JSONSchema> = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n\n // Transform each property\n for (const propName of allPropertyNames) {\n const prop = properties[propName]\n if (!prop) continue\n const wasOptional = !originalRequired.includes(propName)\n\n // Recursively transform nested objects/arrays\n if (prop.type === 'object' && prop.properties) {\n const transformed = makeStructuredOutputCompatible(\n prop,\n prop.required || [],\n )\n properties[propName] = wasOptional\n ? { ...transformed, type: ['object', 'null'] }\n : transformed\n } else if (prop.type === 'array' && prop.items) {\n const items = Array.isArray(prop.items) ? prop.items[0] : prop.items\n const transformed: JSONSchema = {\n ...prop,\n items: items\n ? makeStructuredOutputCompatible(items, items.required || [])\n : prop.items,\n }\n properties[propName] = wasOptional\n ? { ...transformed, type: ['array', 'null'] }\n : transformed\n } else if (wasOptional) {\n // Make optional fields nullable by adding null to the type\n if (prop.type && !Array.isArray(prop.type)) {\n properties[propName] = {\n ...prop,\n type: [prop.type, 'null'],\n }\n } else if (Array.isArray(prop.type) && !prop.type.includes('null')) {\n properties[propName] = {\n ...prop,\n type: [...prop.type, 'null'],\n }\n }\n }\n }\n\n result.properties = properties\n // ALL properties must be required for OpenAI structured output\n result.required = allPropertyNames\n // additionalProperties must be false\n result.additionalProperties = false\n }\n\n // Handle array types with object items\n if (result.type === 'array' && result.items) {\n const items = Array.isArray(result.items) ? result.items[0] : result.items\n if (items) {\n result.items = makeStructuredOutputCompatible(items, items.required || [])\n }\n }\n\n return result\n}\n\n/**\n * Options for schema conversion\n */\nexport interface ConvertSchemaOptions {\n /**\n * When true, transforms the schema to be compatible with OpenAI's structured output requirements:\n * - All properties are added to the `required` array\n * - Optional fields get null added to their type union\n * - additionalProperties is set to false for all objects\n *\n * @default false\n */\n forStructuredOutput?: boolean\n}\n\n/**\n * Converts a Standard JSON Schema compliant schema or plain JSONSchema to JSON Schema format\n * compatible with LLM providers.\n *\n * Supports any schema library that implements the Standard JSON Schema spec (v1):\n * - Zod v4+ (natively supports StandardJSONSchemaV1)\n * - ArkType (natively supports StandardJSONSchemaV1)\n * - Valibot (via `toStandardJsonSchema()` from `@valibot/to-json-schema`)\n *\n * If the input is already a plain JSONSchema object, it is returned as-is.\n *\n * @param schema - Standard JSON Schema compliant schema or plain JSONSchema object to convert\n * @param options - Conversion options\n * @returns JSON Schema object that can be sent to LLM providers\n *\n * @example\n * ```typescript\n * // Using Zod v4+ (natively supports Standard JSON Schema)\n * import * as z from 'zod';\n *\n * const zodSchema = z.object({\n * location: z.string().describe('City name'),\n * unit: z.enum(['celsius', 'fahrenheit']).optional()\n * });\n *\n * const jsonSchema = convertSchemaToJsonSchema(zodSchema);\n *\n * @example\n * // Using ArkType (natively supports Standard JSON Schema)\n * import { type } from 'arktype';\n *\n * const arkSchema = type({\n * location: 'string',\n * unit: \"'celsius' | 'fahrenheit'\"\n * });\n *\n * const jsonSchema = convertSchemaToJsonSchema(arkSchema);\n *\n * @example\n * // Using Valibot (via toStandardJsonSchema)\n * import * as v from 'valibot';\n * import { toStandardJsonSchema } from '@valibot/to-json-schema';\n *\n * const valibotSchema = toStandardJsonSchema(v.object({\n * location: v.string(),\n * unit: v.optional(v.picklist(['celsius', 'fahrenheit']))\n * }));\n *\n * const jsonSchema = convertSchemaToJsonSchema(valibotSchema);\n *\n * @example\n * // Using JSONSchema directly (passes through unchanged)\n * const rawSchema = {\n * type: 'object',\n * properties: { location: { type: 'string' } },\n * required: ['location']\n * };\n * const result = convertSchemaToJsonSchema(rawSchema);\n * ```\n */\nexport function convertSchemaToJsonSchema(\n schema: SchemaInput | undefined,\n options: ConvertSchemaOptions = {},\n): JSONSchema | undefined {\n if (!schema) return undefined\n\n const { forStructuredOutput = false } = options\n\n // If it's a Standard JSON Schema compliant schema, use the standard interface\n if (isStandardJSONSchema(schema)) {\n const jsonSchema = schema['~standard'].jsonSchema.input({\n target: 'draft-07',\n })\n\n // Rebuild structurally so the typed JSONSchema view is acquired without\n // a `Record<string, unknown> as JSONSchema` cast; `toJsonSchema()` also\n // drops the `$schema` key which LLM providers don't need.\n let result: JSONSchema = toJsonSchema(jsonSchema)\n\n // Ensure object schemas always have type: \"object\"\n // If it has properties (even empty), it should be an object type\n if ('properties' in result && !result.type) {\n result.type = 'object'\n }\n\n // Ensure properties exists for object types (even if empty)\n if (result.type === 'object' && !('properties' in result)) {\n result.properties = {}\n }\n\n // Ensure required exists for object types (even if empty array)\n if (result.type === 'object' && !('required' in result)) {\n result.required = []\n }\n\n // Apply structured output transformation if requested\n if (forStructuredOutput) {\n result = makeStructuredOutputCompatible(result, result.required || [])\n }\n\n return result\n }\n\n // Detect Standard Schema validators (Zod, ArkType, Valibot, …) that don't\n // expose a `~standard.jsonSchema` converter. These would otherwise fall\n // through to the JSONSchema pass-through below and ship `{ '~standard': … }`\n // straight to the LLM provider, producing an opaque downstream error. Fail\n // fast with actionable guidance instead.\n if (isStandardSchema(schema)) {\n throw new Error(\n 'Schema is a Standard Schema validator but does not expose a JSON Schema ' +\n 'converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, ' +\n 'or wrap a Valibot schema with `toStandardJsonSchema()` from ' +\n '`@valibot/to-json-schema` before passing it as `outputSchema`.',\n )\n }\n\n // If it's not a Standard JSON Schema, assume it's already a JSONSchema and pass through\n // Still apply structured output transformation if requested\n\n // At this branch, `schema` is the plain `JSONSchema` arm of `SchemaInput`\n // (the two `~standard` arms were handled above). When no transformation\n // is requested we pass the schema through by reference to preserve\n // identity for callers that compare via `===`.\n if (typeof schema !== 'object') {\n // The SchemaInput union is object-shaped on every arm; if we ever hit a\n // non-object here, propagate it untouched and let the downstream\n // provider error loudly rather than silently widen.\n return schema\n }\n\n if (forStructuredOutput) {\n // Build a typed view structurally so we don't need a SchemaInput→JSONSchema\n // cast on the transformation path.\n const typedView = toJsonSchema(schema)\n return makeStructuredOutputCompatible(typedView, typedView.required || [])\n }\n\n return schema\n}\n\n/**\n * Validates data against a Standard Schema compliant schema.\n *\n * @param schema - Standard Schema compliant schema\n * @param data - Data to validate\n * @returns Validation result with success status, data or issues\n */\nexport async function validateWithStandardSchema<T>(\n schema: unknown,\n data: unknown,\n): Promise<\n | { success: true; data: T }\n | {\n success: false\n issues: Array<{ message: string; path?: Array<string> | undefined }>\n }\n> {\n if (!isStandardSchema(schema)) {\n // If it's not a Standard Schema, just return the data as-is\n return { success: true, data: data as T }\n }\n\n const result = await schema['~standard'].validate(data)\n\n if (!result.issues) {\n return { success: true, data: result.value as T }\n }\n\n return {\n success: false,\n issues: result.issues.map((issue) => ({\n message: issue.message || 'Validation failed',\n path: issue.path?.map(String),\n })),\n }\n}\n\n/**\n * Error thrown when Standard Schema validation fails. Carries the original\n * `issues` array so consumers (middleware `onError`, callers catching from\n * `chat({ outputSchema })`) can programmatically inspect each failure.\n */\nexport class StandardSchemaValidationError extends Error {\n override readonly name = 'StandardSchemaValidationError'\n readonly issues: ReadonlyArray<StandardSchemaV1.Issue>\n\n constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n super(\n `Validation failed: ${issues\n .map((i) => i.message || 'Validation failed')\n .join(', ')}`,\n )\n this.issues = issues\n }\n}\n\n/**\n * Synchronously validates data against a Standard Schema compliant schema.\n * Note: Some Standard Schema implementations may only support async validation.\n * In those cases, this function will throw.\n *\n * @param schema - Standard Schema compliant schema\n * @param data - Data to validate\n * @returns Parsed/validated data\n * @throws StandardSchemaValidationError if validation fails; Error if the\n * schema only supports async validation.\n */\nexport function parseWithStandardSchema<T>(schema: unknown, data: unknown): T {\n if (!isStandardSchema(schema)) {\n // If it's not a Standard Schema, just return the data as-is\n return data as T\n }\n\n const result = schema['~standard'].validate(data)\n\n // Handle async result (Promise)\n if (result instanceof Promise) {\n throw new Error(\n 'Schema validation returned a Promise. Use validateWithStandardSchema for async validation.',\n )\n }\n // Standard Schema validation returns { value } for success or { issues } for failure\n if (!result.issues) {\n return result.value as T\n }\n\n throw new StandardSchemaValidationError(result.issues)\n}\n"],"names":[],"mappings":"AAiBA,SAAS,aAAa,KAAyB;AAC7C,QAAM,SAAqB,CAAA;AAC3B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC9C,QAAI,QAAQ,UAAW;AACvB,WAAO,GAAG,IAAI;AAAA,EAChB;AACA,SAAO;AACT;AASA,SAAS,kBAAkB,QAAoD;AAC7E,UACG,OAAO,WAAW,YAAY,OAAO,WAAW,eACjD,WAAW;AAEf;AAOO,SAAS,qBACd,QACgC;AAChC,MAAI,CAAC,kBAAkB,MAAM,KAAK,EAAE,eAAe,QAAS,QAAO;AAEnE,QAAM,WAAW,OAAO,WAAW;AACnC,MACE,OAAO,aAAa,YACpB,aAAa,QACb,EAAE,aAAa,aACf,SAAS,YAAY,KACrB,EAAE,gBAAgB,aAClB,OAAO,SAAS,eAAe,YAC/B,SAAS,eAAe,QACxB,EAAE,WAAW,SAAS,aACtB;AACA,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,SAAS,WAAW,UAAU;AAC9C;AAMO,SAAS,iBAAiB,QAA6C;AAC5E,SACE,kBAAkB,MAAM,KACxB,eAAe,UACf,OAAO,OAAO,WAAW,MAAM,YAC/B,OAAO,WAAW,MAAM,QACxB,aAAa,OAAO,WAAW,KAC/B,OAAO,WAAW,EAAE,YAAY,KAChC,cAAc,OAAO,WAAW,KAChC,OAAO,OAAO,WAAW,EAAE,aAAa;AAE5C;AAaA,SAAS,+BACP,QACA,mBAAkC,IACtB;AACZ,QAAM,SAAqB,EAAE,GAAG,OAAA;A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AAY,QAA+C;AACzD;AAAA,MACE,sBAAsB,OACnB,IAAI,CAAC,MAAM,EAAE,WAAW,mBAAmB,EAC3C,KAAK,IAAI,CAAC;AAAA,IAAA;AAEf,SAAK,SAAS;AAAA,EAChB;AACF;AAaO,SAAS,wBAA2B,QAAiB,MAAkB;AAC5E,MAAI,CAAC,iBAAiB,MAAM,GAAG;AAE7B,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,OAAO,WAAW,EAAE,SAAS,IAAI;AAGhD,MAAI,kBAAkB,SAAS;AAC7B,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEA,MAAI,CAAC,OAAO,QAAQ;AAClB,WAAO,OAAO;AAAA,EAChB;AAEA,QAAM,IAAI,8BAA8B,OAAO,MAAM;AACvD;"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export declare enum EventType {
|
|
2
|
+
TEXT_MESSAGE_START = "TEXT_MESSAGE_START",
|
|
3
|
+
TEXT_MESSAGE_CONTENT = "TEXT_MESSAGE_CONTENT",
|
|
4
|
+
TEXT_MESSAGE_END = "TEXT_MESSAGE_END",
|
|
5
|
+
TEXT_MESSAGE_CHUNK = "TEXT_MESSAGE_CHUNK",
|
|
6
|
+
TOOL_CALL_START = "TOOL_CALL_START",
|
|
7
|
+
TOOL_CALL_ARGS = "TOOL_CALL_ARGS",
|
|
8
|
+
TOOL_CALL_END = "TOOL_CALL_END",
|
|
9
|
+
TOOL_CALL_CHUNK = "TOOL_CALL_CHUNK",
|
|
10
|
+
TOOL_CALL_RESULT = "TOOL_CALL_RESULT",
|
|
11
|
+
THINKING_START = "THINKING_START",
|
|
12
|
+
THINKING_END = "THINKING_END",
|
|
13
|
+
THINKING_TEXT_MESSAGE_START = "THINKING_TEXT_MESSAGE_START",
|
|
14
|
+
THINKING_TEXT_MESSAGE_CONTENT = "THINKING_TEXT_MESSAGE_CONTENT",
|
|
15
|
+
THINKING_TEXT_MESSAGE_END = "THINKING_TEXT_MESSAGE_END",
|
|
16
|
+
STATE_SNAPSHOT = "STATE_SNAPSHOT",
|
|
17
|
+
STATE_DELTA = "STATE_DELTA",
|
|
18
|
+
MESSAGES_SNAPSHOT = "MESSAGES_SNAPSHOT",
|
|
19
|
+
ACTIVITY_SNAPSHOT = "ACTIVITY_SNAPSHOT",
|
|
20
|
+
ACTIVITY_DELTA = "ACTIVITY_DELTA",
|
|
21
|
+
RAW = "RAW",
|
|
22
|
+
CUSTOM = "CUSTOM",
|
|
23
|
+
RUN_STARTED = "RUN_STARTED",
|
|
24
|
+
RUN_FINISHED = "RUN_FINISHED",
|
|
25
|
+
RUN_ERROR = "RUN_ERROR",
|
|
26
|
+
STEP_STARTED = "STEP_STARTED",
|
|
27
|
+
STEP_FINISHED = "STEP_FINISHED",
|
|
28
|
+
REASONING_START = "REASONING_START",
|
|
29
|
+
REASONING_MESSAGE_START = "REASONING_MESSAGE_START",
|
|
30
|
+
REASONING_MESSAGE_CONTENT = "REASONING_MESSAGE_CONTENT",
|
|
31
|
+
REASONING_MESSAGE_END = "REASONING_MESSAGE_END",
|
|
32
|
+
REASONING_MESSAGE_CHUNK = "REASONING_MESSAGE_CHUNK",
|
|
33
|
+
REASONING_END = "REASONING_END",
|
|
34
|
+
REASONING_ENCRYPTED_VALUE = "REASONING_ENCRYPTED_VALUE"
|
|
35
|
+
}
|
|
36
|
+
export { toolDefinition, type AnyClientTool, type ClientTool, type InferToolInput, type InferToolName, type InferToolOutput, type ToolDefinition, type ToolDefinitionConfig, type ToolDefinitionInstance, } from './activities/chat/tools/tool-definition.js';
|
|
37
|
+
export { convertSchemaToJsonSchema } from './activities/chat/tools/schema-converter.js';
|
|
38
|
+
export { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages, } from './activities/chat/messages.js';
|
|
39
|
+
export { BatchStrategy, CompositeStrategy, defaultJSONParser, ImmediateStrategy, parsePartialJSON, PartialJSONParser, PunctuationStrategy, StreamProcessor, WordBoundaryStrategy, } from './activities/chat/stream/index.js';
|
|
40
|
+
export type { ChunkRecording, ChunkStrategy, InternalToolCallState, JSONParser, ProcessorResult, ProcessorState, StreamProcessorEvents, StreamProcessorOptions, ToolCallState, ToolResultState, } from './activities/chat/stream/index.js';
|
|
41
|
+
export { uiMessagesToWire } from './utilities/ag-ui-wire.js';
|
|
42
|
+
export type { WireMessage } from './utilities/ag-ui-wire.js';
|
|
43
|
+
export type { AudioPart, ContentPart, ContentPartDataSource, ContentPartSource, ContentPartUrlSource, CustomEvent, DocumentPart, ImagePart, MessagePart, ModelMessage, RunErrorEvent, RunFinishedEvent, SchemaInput, StreamChunk, StructuredOutputPart, TextPart, ThinkingPart, ToolCall, ToolCallPart, ToolResultPart, UIMessage, VideoPart, InferSchemaType, } from './types.js';
|
|
44
|
+
export type { AudioVisualization, RealtimeError, RealtimeErrorCode, RealtimeEvent, RealtimeEventHandler, RealtimeEventPayloads, RealtimeMessage, RealtimeMessagePart, RealtimeMode, RealtimeSessionConfig, RealtimeStatus, RealtimeToken, RealtimeAudioPart, RealtimeImagePart, RealtimeTextPart, RealtimeToolCallPart, RealtimeToolResultPart, VADConfig, } from './realtime/types.js';
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { toolDefinition } from "./activities/chat/tools/tool-definition.js";
|
|
2
|
+
import { convertSchemaToJsonSchema } from "./activities/chat/tools/schema-converter.js";
|
|
3
|
+
import { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages } from "./activities/chat/messages.js";
|
|
4
|
+
import { uiMessagesToWire } from "./utilities/ag-ui-wire.js";
|
|
5
|
+
import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PunctuationStrategy, WordBoundaryStrategy } from "./activities/chat/stream/strategies.js";
|
|
6
|
+
import { PartialJSONParser, defaultJSONParser, parsePartialJSON } from "./activities/chat/stream/json-parser.js";
|
|
7
|
+
import { StreamProcessor } from "./activities/chat/stream/processor.js";
|
|
8
|
+
var EventType = /* @__PURE__ */ ((EventType2) => {
|
|
9
|
+
EventType2["TEXT_MESSAGE_START"] = "TEXT_MESSAGE_START";
|
|
10
|
+
EventType2["TEXT_MESSAGE_CONTENT"] = "TEXT_MESSAGE_CONTENT";
|
|
11
|
+
EventType2["TEXT_MESSAGE_END"] = "TEXT_MESSAGE_END";
|
|
12
|
+
EventType2["TEXT_MESSAGE_CHUNK"] = "TEXT_MESSAGE_CHUNK";
|
|
13
|
+
EventType2["TOOL_CALL_START"] = "TOOL_CALL_START";
|
|
14
|
+
EventType2["TOOL_CALL_ARGS"] = "TOOL_CALL_ARGS";
|
|
15
|
+
EventType2["TOOL_CALL_END"] = "TOOL_CALL_END";
|
|
16
|
+
EventType2["TOOL_CALL_CHUNK"] = "TOOL_CALL_CHUNK";
|
|
17
|
+
EventType2["TOOL_CALL_RESULT"] = "TOOL_CALL_RESULT";
|
|
18
|
+
EventType2["THINKING_START"] = "THINKING_START";
|
|
19
|
+
EventType2["THINKING_END"] = "THINKING_END";
|
|
20
|
+
EventType2["THINKING_TEXT_MESSAGE_START"] = "THINKING_TEXT_MESSAGE_START";
|
|
21
|
+
EventType2["THINKING_TEXT_MESSAGE_CONTENT"] = "THINKING_TEXT_MESSAGE_CONTENT";
|
|
22
|
+
EventType2["THINKING_TEXT_MESSAGE_END"] = "THINKING_TEXT_MESSAGE_END";
|
|
23
|
+
EventType2["STATE_SNAPSHOT"] = "STATE_SNAPSHOT";
|
|
24
|
+
EventType2["STATE_DELTA"] = "STATE_DELTA";
|
|
25
|
+
EventType2["MESSAGES_SNAPSHOT"] = "MESSAGES_SNAPSHOT";
|
|
26
|
+
EventType2["ACTIVITY_SNAPSHOT"] = "ACTIVITY_SNAPSHOT";
|
|
27
|
+
EventType2["ACTIVITY_DELTA"] = "ACTIVITY_DELTA";
|
|
28
|
+
EventType2["RAW"] = "RAW";
|
|
29
|
+
EventType2["CUSTOM"] = "CUSTOM";
|
|
30
|
+
EventType2["RUN_STARTED"] = "RUN_STARTED";
|
|
31
|
+
EventType2["RUN_FINISHED"] = "RUN_FINISHED";
|
|
32
|
+
EventType2["RUN_ERROR"] = "RUN_ERROR";
|
|
33
|
+
EventType2["STEP_STARTED"] = "STEP_STARTED";
|
|
34
|
+
EventType2["STEP_FINISHED"] = "STEP_FINISHED";
|
|
35
|
+
EventType2["REASONING_START"] = "REASONING_START";
|
|
36
|
+
EventType2["REASONING_MESSAGE_START"] = "REASONING_MESSAGE_START";
|
|
37
|
+
EventType2["REASONING_MESSAGE_CONTENT"] = "REASONING_MESSAGE_CONTENT";
|
|
38
|
+
EventType2["REASONING_MESSAGE_END"] = "REASONING_MESSAGE_END";
|
|
39
|
+
EventType2["REASONING_MESSAGE_CHUNK"] = "REASONING_MESSAGE_CHUNK";
|
|
40
|
+
EventType2["REASONING_END"] = "REASONING_END";
|
|
41
|
+
EventType2["REASONING_ENCRYPTED_VALUE"] = "REASONING_ENCRYPTED_VALUE";
|
|
42
|
+
return EventType2;
|
|
43
|
+
})(EventType || {});
|
|
44
|
+
export {
|
|
45
|
+
BatchStrategy,
|
|
46
|
+
CompositeStrategy,
|
|
47
|
+
EventType,
|
|
48
|
+
ImmediateStrategy,
|
|
49
|
+
PartialJSONParser,
|
|
50
|
+
PunctuationStrategy,
|
|
51
|
+
StreamProcessor,
|
|
52
|
+
WordBoundaryStrategy,
|
|
53
|
+
convertMessagesToModelMessages,
|
|
54
|
+
convertSchemaToJsonSchema,
|
|
55
|
+
defaultJSONParser,
|
|
56
|
+
generateMessageId,
|
|
57
|
+
modelMessageToUIMessage,
|
|
58
|
+
modelMessagesToUIMessages,
|
|
59
|
+
normalizeToUIMessage,
|
|
60
|
+
parsePartialJSON,
|
|
61
|
+
toolDefinition,
|
|
62
|
+
uiMessageToModelMessages,
|
|
63
|
+
uiMessagesToWire
|
|
64
|
+
};
|
|
65
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["export enum EventType {\n TEXT_MESSAGE_START = 'TEXT_MESSAGE_START',\n TEXT_MESSAGE_CONTENT = 'TEXT_MESSAGE_CONTENT',\n TEXT_MESSAGE_END = 'TEXT_MESSAGE_END',\n TEXT_MESSAGE_CHUNK = 'TEXT_MESSAGE_CHUNK',\n TOOL_CALL_START = 'TOOL_CALL_START',\n TOOL_CALL_ARGS = 'TOOL_CALL_ARGS',\n TOOL_CALL_END = 'TOOL_CALL_END',\n TOOL_CALL_CHUNK = 'TOOL_CALL_CHUNK',\n TOOL_CALL_RESULT = 'TOOL_CALL_RESULT',\n THINKING_START = 'THINKING_START',\n THINKING_END = 'THINKING_END',\n THINKING_TEXT_MESSAGE_START = 'THINKING_TEXT_MESSAGE_START',\n THINKING_TEXT_MESSAGE_CONTENT = 'THINKING_TEXT_MESSAGE_CONTENT',\n THINKING_TEXT_MESSAGE_END = 'THINKING_TEXT_MESSAGE_END',\n STATE_SNAPSHOT = 'STATE_SNAPSHOT',\n STATE_DELTA = 'STATE_DELTA',\n MESSAGES_SNAPSHOT = 'MESSAGES_SNAPSHOT',\n ACTIVITY_SNAPSHOT = 'ACTIVITY_SNAPSHOT',\n ACTIVITY_DELTA = 'ACTIVITY_DELTA',\n RAW = 'RAW',\n CUSTOM = 'CUSTOM',\n RUN_STARTED = 'RUN_STARTED',\n RUN_FINISHED = 'RUN_FINISHED',\n RUN_ERROR = 'RUN_ERROR',\n STEP_STARTED = 'STEP_STARTED',\n STEP_FINISHED = 'STEP_FINISHED',\n REASONING_START = 'REASONING_START',\n REASONING_MESSAGE_START = 'REASONING_MESSAGE_START',\n REASONING_MESSAGE_CONTENT = 'REASONING_MESSAGE_CONTENT',\n REASONING_MESSAGE_END = 'REASONING_MESSAGE_END',\n REASONING_MESSAGE_CHUNK = 'REASONING_MESSAGE_CHUNK',\n REASONING_END = 'REASONING_END',\n REASONING_ENCRYPTED_VALUE = 'REASONING_ENCRYPTED_VALUE',\n}\n\nexport {\n toolDefinition,\n type AnyClientTool,\n type ClientTool,\n type InferToolInput,\n type InferToolName,\n type InferToolOutput,\n type ToolDefinition,\n type ToolDefinitionConfig,\n type ToolDefinitionInstance,\n} from './activities/chat/tools/tool-definition'\n\nexport { convertSchemaToJsonSchema } from './activities/chat/tools/schema-converter'\n\nexport {\n convertMessagesToModelMessages,\n generateMessageId,\n modelMessageToUIMessage,\n modelMessagesToUIMessages,\n normalizeToUIMessage,\n uiMessageToModelMessages,\n} from './activities/chat/messages'\n\nexport {\n BatchStrategy,\n CompositeStrategy,\n defaultJSONParser,\n ImmediateStrategy,\n parsePartialJSON,\n PartialJSONParser,\n PunctuationStrategy,\n StreamProcessor,\n WordBoundaryStrategy,\n} from './activities/chat/stream/index'\nexport type {\n ChunkRecording,\n ChunkStrategy,\n InternalToolCallState,\n JSONParser,\n ProcessorResult,\n ProcessorState,\n StreamProcessorEvents,\n StreamProcessorOptions,\n ToolCallState,\n ToolResultState,\n} from './activities/chat/stream/index'\n\nexport { uiMessagesToWire } from './utilities/ag-ui-wire'\nexport type { WireMessage } from './utilities/ag-ui-wire'\n\nexport type {\n AudioPart,\n ContentPart,\n ContentPartDataSource,\n ContentPartSource,\n ContentPartUrlSource,\n CustomEvent,\n DocumentPart,\n ImagePart,\n MessagePart,\n ModelMessage,\n RunErrorEvent,\n RunFinishedEvent,\n SchemaInput,\n StreamChunk,\n StructuredOutputPart,\n TextPart,\n ThinkingPart,\n ToolCall,\n ToolCallPart,\n ToolResultPart,\n UIMessage,\n VideoPart,\n InferSchemaType,\n} from './types'\n\nexport type {\n AudioVisualization,\n RealtimeError,\n RealtimeErrorCode,\n RealtimeEvent,\n RealtimeEventHandler,\n RealtimeEventPayloads,\n RealtimeMessage,\n RealtimeMessagePart,\n RealtimeMode,\n RealtimeSessionConfig,\n RealtimeStatus,\n RealtimeToken,\n RealtimeAudioPart,\n RealtimeImagePart,\n RealtimeTextPart,\n RealtimeToolCallPart,\n RealtimeToolResultPart,\n VADConfig,\n} from './realtime/types'\n"],"names":["EventType"],"mappings":";;;;;;;AAAO,IAAK,8BAAAA,eAAL;AACLA,aAAA,oBAAA,IAAqB;AACrBA,aAAA,sBAAA,IAAuB;AACvBA,aAAA,kBAAA,IAAmB;AACnBA,aAAA,oBAAA,IAAqB;AACrBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,eAAA,IAAgB;AAChBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,kBAAA,IAAmB;AACnBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,cAAA,IAAe;AACfA,aAAA,6BAAA,IAA8B;AAC9BA,aAAA,+BAAA,IAAgC;AAChCA,aAAA,2BAAA,IAA4B;AAC5BA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,aAAA,IAAc;AACdA,aAAA,mBAAA,IAAoB;AACpBA,aAAA,mBAAA,IAAoB;AACpBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,KAAA,IAAM;AACNA,aAAA,QAAA,IAAS;AACTA,aAAA,aAAA,IAAc;AACdA,aAAA,cAAA,IAAe;AACfA,aAAA,WAAA,IAAY;AACZA,aAAA,cAAA,IAAe;AACfA,aAAA,eAAA,IAAgB;AAChBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,yBAAA,IAA0B;AAC1BA,aAAA,2BAAA,IAA4B;AAC5BA,aAAA,uBAAA,IAAwB;AACxBA,aAAA,yBAAA,IAA0B;AAC1BA,aAAA,eAAA,IAAgB;AAChBA,aAAA,2BAAA,IAA4B;AAjClB,SAAAA;AAAA,GAAA,aAAA,CAAA,CAAA;"}
|
package/dist/esm/types.d.ts
CHANGED
|
@@ -759,6 +759,37 @@ export interface RunStartedEvent extends AGUIRunStartedEvent {
|
|
|
759
759
|
/** Model identifier for multi-model support */
|
|
760
760
|
model?: string;
|
|
761
761
|
}
|
|
762
|
+
/**
|
|
763
|
+
* Provider-reported cost breakdown for a single request, normalized onto a
|
|
764
|
+
* canonical shape so consumer code is portable across gateways. Each adapter's
|
|
765
|
+
* extractor maps its provider-specific wire keys (e.g. OpenRouter's
|
|
766
|
+
* `upstream_inference_prompt_cost`, `upstream_inference_input_cost`) onto these
|
|
767
|
+
* fields at runtime.
|
|
768
|
+
*/
|
|
769
|
+
export interface UsageCostBreakdown {
|
|
770
|
+
/** Total cost the gateway paid the upstream provider. */
|
|
771
|
+
upstreamCost?: number;
|
|
772
|
+
/** Upstream cost for input (prompt) tokens. */
|
|
773
|
+
upstreamInputCost?: number;
|
|
774
|
+
/** Upstream cost for output (completion) tokens. */
|
|
775
|
+
upstreamOutputCost?: number;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Token usage totals for a run, optionally including provider-reported cost.
|
|
779
|
+
*
|
|
780
|
+
* `cost` and `costDetails` are populated only by adapters whose provider returns
|
|
781
|
+
* authoritative per-request cost (e.g. OpenRouter). They are absent for adapters
|
|
782
|
+
* that do not report cost, so consumers must treat them as optional.
|
|
783
|
+
*/
|
|
784
|
+
export interface UsageTotals {
|
|
785
|
+
promptTokens: number;
|
|
786
|
+
completionTokens: number;
|
|
787
|
+
totalTokens: number;
|
|
788
|
+
/** Provider-reported cost for the request, when available. */
|
|
789
|
+
cost?: number;
|
|
790
|
+
/** Provider-reported cost breakdown, when available. */
|
|
791
|
+
costDetails?: UsageCostBreakdown;
|
|
792
|
+
}
|
|
762
793
|
/**
|
|
763
794
|
* Emitted when a run completes successfully.
|
|
764
795
|
*
|
|
@@ -770,12 +801,8 @@ export interface RunFinishedEvent extends AGUIRunFinishedEvent {
|
|
|
770
801
|
model?: string;
|
|
771
802
|
/** Why the generation stopped */
|
|
772
803
|
finishReason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null;
|
|
773
|
-
/** Token usage statistics */
|
|
774
|
-
usage?:
|
|
775
|
-
promptTokens: number;
|
|
776
|
-
completionTokens: number;
|
|
777
|
-
totalTokens: number;
|
|
778
|
-
};
|
|
804
|
+
/** Token usage statistics, optionally including provider-reported cost. */
|
|
805
|
+
usage?: UsageTotals;
|
|
779
806
|
}
|
|
780
807
|
/**
|
|
781
808
|
* Emitted when an error occurs during a run.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.1",
|
|
4
4
|
"description": "Type-safe TypeScript AI SDK for streaming chat, tool calling, agents, structured outputs, and multimodal generation.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -17,6 +17,10 @@
|
|
|
17
17
|
"types": "./dist/esm/index.d.ts",
|
|
18
18
|
"import": "./dist/esm/index.js"
|
|
19
19
|
},
|
|
20
|
+
"./client": {
|
|
21
|
+
"types": "./dist/esm/client.d.ts",
|
|
22
|
+
"import": "./dist/esm/client.js"
|
|
23
|
+
},
|
|
20
24
|
"./adapters": {
|
|
21
25
|
"types": "./dist/esm/activities/index.d.ts",
|
|
22
26
|
"import": "./dist/esm/activities/index.js"
|
|
@@ -64,7 +68,7 @@
|
|
|
64
68
|
"@ag-ui/core": "^0.0.52",
|
|
65
69
|
"@standard-schema/spec": "^1.1.0",
|
|
66
70
|
"partial-json": "^0.1.7",
|
|
67
|
-
"@tanstack/ai-event-client": "0.4.
|
|
71
|
+
"@tanstack/ai-event-client": "0.4.2"
|
|
68
72
|
},
|
|
69
73
|
"peerDependencies": {
|
|
70
74
|
"@opentelemetry/api": ">=1.9.0"
|
|
@@ -77,6 +81,7 @@
|
|
|
77
81
|
"devDependencies": {
|
|
78
82
|
"@opentelemetry/api": "^1.9.0",
|
|
79
83
|
"@vitest/coverage-v8": "4.0.14",
|
|
84
|
+
"arktype": "^2.1.28",
|
|
80
85
|
"zod": "^4.2.0"
|
|
81
86
|
},
|
|
82
87
|
"scripts": {
|
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
StreamChunk,
|
|
5
5
|
Tool,
|
|
6
6
|
ToolCall,
|
|
7
|
+
UsageTotals,
|
|
7
8
|
} from '../../../types'
|
|
8
9
|
import type { SystemPrompt } from '../../../system-prompts'
|
|
9
10
|
|
|
@@ -264,12 +265,12 @@ export interface ToolPhaseCompleteInfo {
|
|
|
264
265
|
/**
|
|
265
266
|
* Token usage statistics passed to the onUsage hook.
|
|
266
267
|
* Extracted from the RUN_FINISHED chunk when usage data is present.
|
|
268
|
+
*
|
|
269
|
+
* Includes optional provider-reported `cost`/`costDetails` (see {@link UsageTotals}).
|
|
270
|
+
* Kept as an interface extending `UsageTotals` to preserve declaration merging for
|
|
271
|
+
* this publicly exported type.
|
|
267
272
|
*/
|
|
268
|
-
export interface UsageInfo {
|
|
269
|
-
promptTokens: number
|
|
270
|
-
completionTokens: number
|
|
271
|
-
totalTokens: number
|
|
272
|
-
}
|
|
273
|
+
export interface UsageInfo extends UsageTotals {}
|
|
273
274
|
|
|
274
275
|
// ===========================
|
|
275
276
|
// Terminal Hook Info
|
|
@@ -285,14 +286,8 @@ export interface FinishInfo {
|
|
|
285
286
|
duration: number
|
|
286
287
|
/** Final accumulated text content */
|
|
287
288
|
content: string
|
|
288
|
-
/** Final usage totals, if available */
|
|
289
|
-
usage?:
|
|
290
|
-
| {
|
|
291
|
-
promptTokens: number
|
|
292
|
-
completionTokens: number
|
|
293
|
-
totalTokens: number
|
|
294
|
-
}
|
|
295
|
-
| undefined
|
|
289
|
+
/** Final usage totals, if available (optionally including provider-reported cost) */
|
|
290
|
+
usage?: UsageTotals | undefined
|
|
296
291
|
}
|
|
297
292
|
|
|
298
293
|
/**
|
|
@@ -24,6 +24,20 @@ function toJsonSchema(obj: object): JSONSchema {
|
|
|
24
24
|
return result
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Whether a value can carry a `~standard` property. Most schema libraries
|
|
29
|
+
* (Zod, Valibot) return plain objects, but ArkType's `type()` returns a
|
|
30
|
+
* *callable function* with `~standard` attached — so `typeof` must accept
|
|
31
|
+
* both `'object'` and `'function'` or ArkType schemas are missed entirely
|
|
32
|
+
* (issue #276).
|
|
33
|
+
*/
|
|
34
|
+
function isPropertyCarrier(schema: unknown): schema is Record<string, unknown> {
|
|
35
|
+
return (
|
|
36
|
+
(typeof schema === 'object' || typeof schema === 'function') &&
|
|
37
|
+
schema !== null
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
|
|
27
41
|
/**
|
|
28
42
|
* Check if a value is a Standard JSON Schema compliant schema.
|
|
29
43
|
* Standard JSON Schema compliant libraries (Zod v4+, ArkType, Valibot with toStandardJsonSchema, etc.)
|
|
@@ -32,18 +46,23 @@ function toJsonSchema(obj: object): JSONSchema {
|
|
|
32
46
|
export function isStandardJSONSchema(
|
|
33
47
|
schema: unknown,
|
|
34
48
|
): schema is StandardJSONSchemaV1 {
|
|
35
|
-
return
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
typeof
|
|
40
|
-
|
|
41
|
-
(
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
typeof
|
|
45
|
-
|
|
46
|
-
|
|
49
|
+
if (!isPropertyCarrier(schema) || !('~standard' in schema)) return false
|
|
50
|
+
|
|
51
|
+
const standard = schema['~standard']
|
|
52
|
+
if (
|
|
53
|
+
typeof standard !== 'object' ||
|
|
54
|
+
standard === null ||
|
|
55
|
+
!('version' in standard) ||
|
|
56
|
+
standard.version !== 1 ||
|
|
57
|
+
!('jsonSchema' in standard) ||
|
|
58
|
+
typeof standard.jsonSchema !== 'object' ||
|
|
59
|
+
standard.jsonSchema === null ||
|
|
60
|
+
!('input' in standard.jsonSchema)
|
|
61
|
+
) {
|
|
62
|
+
return false
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return typeof standard.jsonSchema.input === 'function'
|
|
47
66
|
}
|
|
48
67
|
|
|
49
68
|
/**
|
|
@@ -52,8 +71,7 @@ export function isStandardJSONSchema(
|
|
|
52
71
|
*/
|
|
53
72
|
export function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {
|
|
54
73
|
return (
|
|
55
|
-
|
|
56
|
-
schema !== null &&
|
|
74
|
+
isPropertyCarrier(schema) &&
|
|
57
75
|
'~standard' in schema &&
|
|
58
76
|
typeof schema['~standard'] === 'object' &&
|
|
59
77
|
schema['~standard'] !== null &&
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
export enum EventType {
|
|
2
|
+
TEXT_MESSAGE_START = 'TEXT_MESSAGE_START',
|
|
3
|
+
TEXT_MESSAGE_CONTENT = 'TEXT_MESSAGE_CONTENT',
|
|
4
|
+
TEXT_MESSAGE_END = 'TEXT_MESSAGE_END',
|
|
5
|
+
TEXT_MESSAGE_CHUNK = 'TEXT_MESSAGE_CHUNK',
|
|
6
|
+
TOOL_CALL_START = 'TOOL_CALL_START',
|
|
7
|
+
TOOL_CALL_ARGS = 'TOOL_CALL_ARGS',
|
|
8
|
+
TOOL_CALL_END = 'TOOL_CALL_END',
|
|
9
|
+
TOOL_CALL_CHUNK = 'TOOL_CALL_CHUNK',
|
|
10
|
+
TOOL_CALL_RESULT = 'TOOL_CALL_RESULT',
|
|
11
|
+
THINKING_START = 'THINKING_START',
|
|
12
|
+
THINKING_END = 'THINKING_END',
|
|
13
|
+
THINKING_TEXT_MESSAGE_START = 'THINKING_TEXT_MESSAGE_START',
|
|
14
|
+
THINKING_TEXT_MESSAGE_CONTENT = 'THINKING_TEXT_MESSAGE_CONTENT',
|
|
15
|
+
THINKING_TEXT_MESSAGE_END = 'THINKING_TEXT_MESSAGE_END',
|
|
16
|
+
STATE_SNAPSHOT = 'STATE_SNAPSHOT',
|
|
17
|
+
STATE_DELTA = 'STATE_DELTA',
|
|
18
|
+
MESSAGES_SNAPSHOT = 'MESSAGES_SNAPSHOT',
|
|
19
|
+
ACTIVITY_SNAPSHOT = 'ACTIVITY_SNAPSHOT',
|
|
20
|
+
ACTIVITY_DELTA = 'ACTIVITY_DELTA',
|
|
21
|
+
RAW = 'RAW',
|
|
22
|
+
CUSTOM = 'CUSTOM',
|
|
23
|
+
RUN_STARTED = 'RUN_STARTED',
|
|
24
|
+
RUN_FINISHED = 'RUN_FINISHED',
|
|
25
|
+
RUN_ERROR = 'RUN_ERROR',
|
|
26
|
+
STEP_STARTED = 'STEP_STARTED',
|
|
27
|
+
STEP_FINISHED = 'STEP_FINISHED',
|
|
28
|
+
REASONING_START = 'REASONING_START',
|
|
29
|
+
REASONING_MESSAGE_START = 'REASONING_MESSAGE_START',
|
|
30
|
+
REASONING_MESSAGE_CONTENT = 'REASONING_MESSAGE_CONTENT',
|
|
31
|
+
REASONING_MESSAGE_END = 'REASONING_MESSAGE_END',
|
|
32
|
+
REASONING_MESSAGE_CHUNK = 'REASONING_MESSAGE_CHUNK',
|
|
33
|
+
REASONING_END = 'REASONING_END',
|
|
34
|
+
REASONING_ENCRYPTED_VALUE = 'REASONING_ENCRYPTED_VALUE',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export {
|
|
38
|
+
toolDefinition,
|
|
39
|
+
type AnyClientTool,
|
|
40
|
+
type ClientTool,
|
|
41
|
+
type InferToolInput,
|
|
42
|
+
type InferToolName,
|
|
43
|
+
type InferToolOutput,
|
|
44
|
+
type ToolDefinition,
|
|
45
|
+
type ToolDefinitionConfig,
|
|
46
|
+
type ToolDefinitionInstance,
|
|
47
|
+
} from './activities/chat/tools/tool-definition'
|
|
48
|
+
|
|
49
|
+
export { convertSchemaToJsonSchema } from './activities/chat/tools/schema-converter'
|
|
50
|
+
|
|
51
|
+
export {
|
|
52
|
+
convertMessagesToModelMessages,
|
|
53
|
+
generateMessageId,
|
|
54
|
+
modelMessageToUIMessage,
|
|
55
|
+
modelMessagesToUIMessages,
|
|
56
|
+
normalizeToUIMessage,
|
|
57
|
+
uiMessageToModelMessages,
|
|
58
|
+
} from './activities/chat/messages'
|
|
59
|
+
|
|
60
|
+
export {
|
|
61
|
+
BatchStrategy,
|
|
62
|
+
CompositeStrategy,
|
|
63
|
+
defaultJSONParser,
|
|
64
|
+
ImmediateStrategy,
|
|
65
|
+
parsePartialJSON,
|
|
66
|
+
PartialJSONParser,
|
|
67
|
+
PunctuationStrategy,
|
|
68
|
+
StreamProcessor,
|
|
69
|
+
WordBoundaryStrategy,
|
|
70
|
+
} from './activities/chat/stream/index'
|
|
71
|
+
export type {
|
|
72
|
+
ChunkRecording,
|
|
73
|
+
ChunkStrategy,
|
|
74
|
+
InternalToolCallState,
|
|
75
|
+
JSONParser,
|
|
76
|
+
ProcessorResult,
|
|
77
|
+
ProcessorState,
|
|
78
|
+
StreamProcessorEvents,
|
|
79
|
+
StreamProcessorOptions,
|
|
80
|
+
ToolCallState,
|
|
81
|
+
ToolResultState,
|
|
82
|
+
} from './activities/chat/stream/index'
|
|
83
|
+
|
|
84
|
+
export { uiMessagesToWire } from './utilities/ag-ui-wire'
|
|
85
|
+
export type { WireMessage } from './utilities/ag-ui-wire'
|
|
86
|
+
|
|
87
|
+
export type {
|
|
88
|
+
AudioPart,
|
|
89
|
+
ContentPart,
|
|
90
|
+
ContentPartDataSource,
|
|
91
|
+
ContentPartSource,
|
|
92
|
+
ContentPartUrlSource,
|
|
93
|
+
CustomEvent,
|
|
94
|
+
DocumentPart,
|
|
95
|
+
ImagePart,
|
|
96
|
+
MessagePart,
|
|
97
|
+
ModelMessage,
|
|
98
|
+
RunErrorEvent,
|
|
99
|
+
RunFinishedEvent,
|
|
100
|
+
SchemaInput,
|
|
101
|
+
StreamChunk,
|
|
102
|
+
StructuredOutputPart,
|
|
103
|
+
TextPart,
|
|
104
|
+
ThinkingPart,
|
|
105
|
+
ToolCall,
|
|
106
|
+
ToolCallPart,
|
|
107
|
+
ToolResultPart,
|
|
108
|
+
UIMessage,
|
|
109
|
+
VideoPart,
|
|
110
|
+
InferSchemaType,
|
|
111
|
+
} from './types'
|
|
112
|
+
|
|
113
|
+
export type {
|
|
114
|
+
AudioVisualization,
|
|
115
|
+
RealtimeError,
|
|
116
|
+
RealtimeErrorCode,
|
|
117
|
+
RealtimeEvent,
|
|
118
|
+
RealtimeEventHandler,
|
|
119
|
+
RealtimeEventPayloads,
|
|
120
|
+
RealtimeMessage,
|
|
121
|
+
RealtimeMessagePart,
|
|
122
|
+
RealtimeMode,
|
|
123
|
+
RealtimeSessionConfig,
|
|
124
|
+
RealtimeStatus,
|
|
125
|
+
RealtimeToken,
|
|
126
|
+
RealtimeAudioPart,
|
|
127
|
+
RealtimeImagePart,
|
|
128
|
+
RealtimeTextPart,
|
|
129
|
+
RealtimeToolCallPart,
|
|
130
|
+
RealtimeToolResultPart,
|
|
131
|
+
VADConfig,
|
|
132
|
+
} from './realtime/types'
|
package/src/types.ts
CHANGED
|
@@ -925,6 +925,39 @@ export interface RunStartedEvent extends AGUIRunStartedEvent {
|
|
|
925
925
|
model?: string
|
|
926
926
|
}
|
|
927
927
|
|
|
928
|
+
/**
|
|
929
|
+
* Provider-reported cost breakdown for a single request, normalized onto a
|
|
930
|
+
* canonical shape so consumer code is portable across gateways. Each adapter's
|
|
931
|
+
* extractor maps its provider-specific wire keys (e.g. OpenRouter's
|
|
932
|
+
* `upstream_inference_prompt_cost`, `upstream_inference_input_cost`) onto these
|
|
933
|
+
* fields at runtime.
|
|
934
|
+
*/
|
|
935
|
+
export interface UsageCostBreakdown {
|
|
936
|
+
/** Total cost the gateway paid the upstream provider. */
|
|
937
|
+
upstreamCost?: number
|
|
938
|
+
/** Upstream cost for input (prompt) tokens. */
|
|
939
|
+
upstreamInputCost?: number
|
|
940
|
+
/** Upstream cost for output (completion) tokens. */
|
|
941
|
+
upstreamOutputCost?: number
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Token usage totals for a run, optionally including provider-reported cost.
|
|
946
|
+
*
|
|
947
|
+
* `cost` and `costDetails` are populated only by adapters whose provider returns
|
|
948
|
+
* authoritative per-request cost (e.g. OpenRouter). They are absent for adapters
|
|
949
|
+
* that do not report cost, so consumers must treat them as optional.
|
|
950
|
+
*/
|
|
951
|
+
export interface UsageTotals {
|
|
952
|
+
promptTokens: number
|
|
953
|
+
completionTokens: number
|
|
954
|
+
totalTokens: number
|
|
955
|
+
/** Provider-reported cost for the request, when available. */
|
|
956
|
+
cost?: number
|
|
957
|
+
/** Provider-reported cost breakdown, when available. */
|
|
958
|
+
costDetails?: UsageCostBreakdown
|
|
959
|
+
}
|
|
960
|
+
|
|
928
961
|
/**
|
|
929
962
|
* Emitted when a run completes successfully.
|
|
930
963
|
*
|
|
@@ -936,12 +969,8 @@ export interface RunFinishedEvent extends AGUIRunFinishedEvent {
|
|
|
936
969
|
model?: string
|
|
937
970
|
/** Why the generation stopped */
|
|
938
971
|
finishReason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null
|
|
939
|
-
/** Token usage statistics */
|
|
940
|
-
usage?:
|
|
941
|
-
promptTokens: number
|
|
942
|
-
completionTokens: number
|
|
943
|
-
totalTokens: number
|
|
944
|
-
}
|
|
972
|
+
/** Token usage statistics, optionally including provider-reported cost. */
|
|
973
|
+
usage?: UsageTotals
|
|
945
974
|
}
|
|
946
975
|
|
|
947
976
|
/**
|