@tanstack/ai 0.23.1 → 0.25.0
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/esm/activities/chat/adapter.d.ts +3 -1
- package/dist/esm/activities/chat/adapter.js.map +1 -1
- package/dist/esm/activities/chat/index.d.ts +33 -9
- package/dist/esm/activities/chat/index.js +19 -9
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/messages.js +2 -1
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/chat/middleware/compose.d.ts +14 -14
- package/dist/esm/activities/chat/middleware/compose.js.map +1 -1
- package/dist/esm/activities/chat/middleware/types.d.ts +21 -21
- package/dist/esm/activities/chat/runtime-context-types.d.ts +43 -0
- package/dist/esm/activities/chat/stream/message-updaters.d.ts +2 -2
- package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
- package/dist/esm/activities/chat/stream/processor.d.ts +1 -0
- package/dist/esm/activities/chat/stream/processor.js +35 -12
- package/dist/esm/activities/chat/stream/processor.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-calls.d.ts +15 -5
- package/dist/esm/activities/chat/tools/tool-calls.js +59 -19
- package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-definition.d.ts +12 -8
- package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -1
- package/dist/esm/activities/error-payload.d.ts +26 -0
- package/dist/esm/activities/error-payload.js +12 -1
- package/dist/esm/activities/error-payload.js.map +1 -1
- package/dist/esm/activities/generateAudio/index.js +9 -0
- package/dist/esm/activities/generateAudio/index.js.map +1 -1
- package/dist/esm/activities/generateSpeech/index.js +9 -0
- package/dist/esm/activities/generateSpeech/index.js.map +1 -1
- package/dist/esm/adapter-internals.d.ts +1 -1
- package/dist/esm/adapter-internals.js +3 -2
- package/dist/esm/client.d.ts +1 -1
- package/dist/esm/client.js +3 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/index.js +9 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/tool-registry.d.ts +7 -7
- package/dist/esm/tool-registry.js +1 -1
- package/dist/esm/tool-registry.js.map +1 -1
- package/dist/esm/types.d.ts +56 -59
- package/dist/esm/utilities/ag-ui-wire.js +1 -1
- package/dist/esm/utilities/ag-ui-wire.js.map +1 -1
- package/dist/esm/utilities/chat-params.d.ts +8 -3
- package/dist/esm/utilities/chat-params.js +6 -2
- package/dist/esm/utilities/chat-params.js.map +1 -1
- package/dist/esm/utilities/tool-result.d.ts +21 -0
- package/dist/esm/utilities/tool-result.js +37 -0
- package/dist/esm/utilities/tool-result.js.map +1 -0
- package/dist/esm/utilities/usage.d.ts +31 -0
- package/dist/esm/utilities/usage.js +11 -0
- package/dist/esm/utilities/usage.js.map +1 -0
- package/package.json +2 -2
- package/src/activities/chat/adapter.ts +3 -0
- package/src/activities/chat/index.ts +219 -47
- package/src/activities/chat/messages.ts +2 -1
- package/src/activities/chat/middleware/compose.ts +23 -17
- package/src/activities/chat/middleware/types.ts +21 -21
- package/src/activities/chat/runtime-context-types.ts +68 -0
- package/src/activities/chat/stream/message-updaters.ts +2 -1
- package/src/activities/chat/stream/processor.ts +48 -8
- package/src/activities/chat/tools/tool-calls.ts +138 -43
- package/src/activities/chat/tools/tool-definition.ts +25 -31
- package/src/activities/error-payload.ts +44 -0
- package/src/activities/generateAudio/index.ts +10 -0
- package/src/activities/generateSpeech/index.ts +10 -0
- package/src/adapter-internals.ts +4 -1
- package/src/client.ts +5 -1
- package/src/index.ts +10 -0
- package/src/tool-registry.ts +16 -14
- package/src/types.ts +118 -79
- package/src/utilities/ag-ui-wire.ts +4 -1
- package/src/utilities/chat-params.ts +22 -7
- package/src/utilities/tool-result.ts +60 -0
- package/src/utilities/usage.ts +41 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateSpeech/index.ts"],"sourcesContent":["/**\n * TTS Activity\n *\n * Generates speech audio from text using text-to-speech models.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { streamGenerationResult } from '../stream-generation-result.js'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { TTSAdapter } from './adapter'\nimport type { StreamChunk, TTSResult } from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'tts' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a TTSAdapter via ~types.\n */\nexport type TTSProviderOptions<TAdapter> =\n TAdapter extends TTSAdapter<any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the TTS activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The TTS adapter type\n * @template TStream - Whether to stream the output\n */\nexport interface TTSActivityOptions<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n> {\n /** The TTS adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The text to convert to speech */\n text: string\n /** The voice to use for generation */\n voice?: string\n /** The output audio format */\n format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'\n /** The speed of the generated audio (0.25 to 4.0) */\n speed?: number\n /** Provider-specific options for TTS generation */\n modelOptions?: TTSProviderOptions<TAdapter>\n /**\n * Whether to stream the generation result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<TTSResult>.\n *\n * @default false\n */\n stream?: TStream\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the TTS activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<TTSResult>\n */\nexport type TTSActivityResult<TStream extends boolean = false> =\n TStream extends true ? AsyncIterable<StreamChunk> : Promise<TTSResult>\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * TTS activity - generates speech from text.\n *\n * Uses AI text-to-speech models to create audio from natural language text.\n *\n * @example Generate speech from text\n * ```ts\n * import { generateSpeech } from '@tanstack/ai'\n * import { openaiSpeech } from '@tanstack/ai-openai'\n *\n * const result = await generateSpeech({\n * adapter: openaiSpeech('tts-1-hd'),\n * text: 'Hello, welcome to TanStack AI!',\n * voice: 'nova'\n * })\n *\n * console.log(result.audio) // base64-encoded audio\n * ```\n *\n * @example With format and speed options\n * ```ts\n * const result = await generateSpeech({\n * adapter: openaiSpeech('tts-1'),\n * text: 'This is slower speech.',\n * voice: 'alloy',\n * format: 'wav',\n * speed: 0.8\n * })\n * ```\n */\nexport function generateSpeech<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n>(options: TTSActivityOptions<TAdapter, TStream>): TTSActivityResult<TStream> {\n if (options.stream) {\n return streamGenerationResult(() =>\n runGenerateSpeech(options),\n ) as TTSActivityResult<TStream>\n }\n return runGenerateSpeech(options) as TTSActivityResult<TStream>\n}\n\n/**\n * Run the core TTS generation logic (non-streaming).\n */\nasync function runGenerateSpeech<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n>(options: TTSActivityOptions<TAdapter, boolean>): Promise<TTSResult> {\n const { adapter, stream: _stream, debug: _debug, ...rest } = options\n const model = adapter.model\n const requestId = createId('speech')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n aiEventClient.emit('speech:request:started', {\n requestId,\n provider: adapter.name,\n model,\n text: rest.text,\n voice: rest.voice,\n format: rest.format,\n speed: rest.speed,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateSpeech provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const result = await adapter.generateSpeech({ ...rest, model, logger })\n const duration = Date.now() - startTime\n\n aiEventClient.emit('speech:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n audio: result.audio,\n format: result.format,\n audioDuration: result.duration,\n contentType: result.contentType,\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n\n logger.output(`activity=generateSpeech bytes=${result.audio.length}`, {\n bytes: result.audio.length,\n contentType: result.contentType,\n })\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const err = error as Error\n aiEventClient.emit('speech:request:error', {\n requestId,\n provider: adapter.name,\n model,\n error: { message: err.message, name: err.name },\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n logger.errors('generateSpeech activity failed', {\n error,\n source: 'generateSpeech',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateSpeech() function without executing.\n */\nexport function createSpeechOptions<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n>(\n options: TTSActivityOptions<TAdapter, TStream>,\n): TTSActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type { TTSAdapter, TTSAdapterConfig, AnyTTSAdapter } from './adapter'\nexport { BaseTTSAdapter } from './adapter'\n"],"names":[],"mappings":";;;AAoBO,MAAM,OAAO;AAqEpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AAoCO,SAAS,eAGd,SAA4E;AAC5E,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MAAuB,MAC5B,kBAAkB,OAAO;AAAA,IAAA;AAAA,EAE7B;AACA,SAAO,kBAAkB,OAAO;AAClC;AAKA,eAAe,kBAEb,SAAoE;AACpE,QAAM,EAAE,SAAS,QAAQ,SAAS,OAAO,QAAQ,GAAG,SAAS;AAC7D,QAAM,QAAQ,QAAQ;AACtB,QAAM,YAAY,SAAS,QAAQ;AACnC,QAAM,YAAY,KAAK,IAAA;AACvB,QAAM,SAAyB,mBAAmB,QAAQ,KAAK;AAC/D,QAAM,eACH,QAAiD,YACjD,QAA8B,QAC/B;AAEF,gBAAc,KAAK,0BAA0B;AAAA,IAC3C;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB;AAAA,IACA,MAAM,KAAK;AAAA,IACX,OAAO,KAAK;AAAA,IACZ,QAAQ,KAAK;AAAA,IACb,OAAO,KAAK;AAAA,IACZ,cAAc,KAAK;AAAA,IACnB,WAAW;AAAA,EAAA,CACZ;AAED,SAAO,QAAQ,oCAAoC,YAAY,IAAI;AAAA,IACjE,UAAU;AAAA,IACV;AAAA,EAAA,CACD;AAED,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ,eAAe,EAAE,GAAG,MAAM,OAAO,QAAQ;AACtE,UAAM,WAAW,KAAK,IAAA,IAAQ;AAE9B,kBAAc,KAAK,4BAA4B;AAAA,MAC7C;AAAA,MACA,UAAU,QAAQ;AAAA,MAClB;AAAA,MACA,OAAO,OAAO;AAAA,MACd,QAAQ,OAAO;AAAA,MACf,eAAe,OAAO;AAAA,MACtB,aAAa,OAAO;AAAA,MACpB;AAAA,MACA,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK,IAAA;AAAA,IAAI,CACrB;AAED,WAAO,OAAO,iCAAiC,OAAO,MAAM,MAAM,IAAI;AAAA,MACpE,OAAO,OAAO,MAAM;AAAA,MACpB,aAAa,OAAO;AAAA,IAAA,CACrB;AAED,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,WAAW,KAAK,IAAA,IAAQ;AAC9B,UAAM,MAAM;AACZ,kBAAc,KAAK,wBAAwB;AAAA,MACzC;AAAA,MACA,UAAU,QAAQ;AAAA,MAClB;AAAA,MACA,OAAO,EAAE,SAAS,IAAI,SAAS,MAAM,IAAI,KAAA;AAAA,MACzC;AAAA,MACA,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK,IAAA;AAAA,IAAI,CACrB;AACD,WAAO,OAAO,kCAAkC;AAAA,MAC9C;AAAA,MACA,QAAQ;AAAA,IAAA,CACT;AACD,UAAM;AAAA,EACR;AACF;AASO,SAAS,oBAId,SACuC;AACvC,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateSpeech/index.ts"],"sourcesContent":["/**\n * TTS Activity\n *\n * Generates speech audio from text using text-to-speech models.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { streamGenerationResult } from '../stream-generation-result.js'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { TTSAdapter } from './adapter'\nimport type { StreamChunk, TTSResult } from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'tts' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a TTSAdapter via ~types.\n */\nexport type TTSProviderOptions<TAdapter> =\n TAdapter extends TTSAdapter<any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the TTS activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The TTS adapter type\n * @template TStream - Whether to stream the output\n */\nexport interface TTSActivityOptions<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n> {\n /** The TTS adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The text to convert to speech */\n text: string\n /** The voice to use for generation */\n voice?: string\n /** The output audio format */\n format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'\n /** The speed of the generated audio (0.25 to 4.0) */\n speed?: number\n /** Provider-specific options for TTS generation */\n modelOptions?: TTSProviderOptions<TAdapter>\n /**\n * Whether to stream the generation result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<TTSResult>.\n *\n * @default false\n */\n stream?: TStream\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the TTS activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<TTSResult>\n */\nexport type TTSActivityResult<TStream extends boolean = false> =\n TStream extends true ? AsyncIterable<StreamChunk> : Promise<TTSResult>\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * TTS activity - generates speech from text.\n *\n * Uses AI text-to-speech models to create audio from natural language text.\n *\n * @example Generate speech from text\n * ```ts\n * import { generateSpeech } from '@tanstack/ai'\n * import { openaiSpeech } from '@tanstack/ai-openai'\n *\n * const result = await generateSpeech({\n * adapter: openaiSpeech('tts-1-hd'),\n * text: 'Hello, welcome to TanStack AI!',\n * voice: 'nova'\n * })\n *\n * console.log(result.audio) // base64-encoded audio\n * ```\n *\n * @example With format and speed options\n * ```ts\n * const result = await generateSpeech({\n * adapter: openaiSpeech('tts-1'),\n * text: 'This is slower speech.',\n * voice: 'alloy',\n * format: 'wav',\n * speed: 0.8\n * })\n * ```\n */\nexport function generateSpeech<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n>(options: TTSActivityOptions<TAdapter, TStream>): TTSActivityResult<TStream> {\n if (options.stream) {\n return streamGenerationResult(() =>\n runGenerateSpeech(options),\n ) as TTSActivityResult<TStream>\n }\n return runGenerateSpeech(options) as TTSActivityResult<TStream>\n}\n\n/**\n * Run the core TTS generation logic (non-streaming).\n */\nasync function runGenerateSpeech<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n>(options: TTSActivityOptions<TAdapter, boolean>): Promise<TTSResult> {\n const { adapter, stream: _stream, debug: _debug, ...rest } = options\n const model = adapter.model\n const requestId = createId('speech')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n aiEventClient.emit('speech:request:started', {\n requestId,\n provider: adapter.name,\n model,\n text: rest.text,\n voice: rest.voice,\n format: rest.format,\n speed: rest.speed,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateSpeech provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const result = await adapter.generateSpeech({ ...rest, model, logger })\n const duration = Date.now() - startTime\n\n aiEventClient.emit('speech:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n audio: result.audio,\n format: result.format,\n audioDuration: result.duration,\n contentType: result.contentType,\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n\n if (result.usage) {\n aiEventClient.emit('speech:usage', {\n requestId,\n model,\n usage: result.usage,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n }\n\n logger.output(`activity=generateSpeech bytes=${result.audio.length}`, {\n bytes: result.audio.length,\n contentType: result.contentType,\n })\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const err = error as Error\n aiEventClient.emit('speech:request:error', {\n requestId,\n provider: adapter.name,\n model,\n error: { message: err.message, name: err.name },\n duration,\n modelOptions: rest.modelOptions as Record<string, unknown> | undefined,\n timestamp: Date.now(),\n })\n logger.errors('generateSpeech activity failed', {\n error,\n source: 'generateSpeech',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateSpeech() function without executing.\n */\nexport function createSpeechOptions<\n TAdapter extends TTSAdapter<string, TTSProviderOptions<TAdapter>>,\n TStream extends boolean = false,\n>(\n options: TTSActivityOptions<TAdapter, TStream>,\n): TTSActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type { TTSAdapter, TTSAdapterConfig, AnyTTSAdapter } from './adapter'\nexport { BaseTTSAdapter } from './adapter'\n"],"names":[],"mappings":";;;AAoBO,MAAM,OAAO;AAqEpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AAoCO,SAAS,eAGd,SAA4E;AAC5E,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MAAuB,MAC5B,kBAAkB,OAAO;AAAA,IAAA;AAAA,EAE7B;AACA,SAAO,kBAAkB,OAAO;AAClC;AAKA,eAAe,kBAEb,SAAoE;AACpE,QAAM,EAAE,SAAS,QAAQ,SAAS,OAAO,QAAQ,GAAG,SAAS;AAC7D,QAAM,QAAQ,QAAQ;AACtB,QAAM,YAAY,SAAS,QAAQ;AACnC,QAAM,YAAY,KAAK,IAAA;AACvB,QAAM,SAAyB,mBAAmB,QAAQ,KAAK;AAC/D,QAAM,eACH,QAAiD,YACjD,QAA8B,QAC/B;AAEF,gBAAc,KAAK,0BAA0B;AAAA,IAC3C;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB;AAAA,IACA,MAAM,KAAK;AAAA,IACX,OAAO,KAAK;AAAA,IACZ,QAAQ,KAAK;AAAA,IACb,OAAO,KAAK;AAAA,IACZ,cAAc,KAAK;AAAA,IACnB,WAAW;AAAA,EAAA,CACZ;AAED,SAAO,QAAQ,oCAAoC,YAAY,IAAI;AAAA,IACjE,UAAU;AAAA,IACV;AAAA,EAAA,CACD;AAED,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ,eAAe,EAAE,GAAG,MAAM,OAAO,QAAQ;AACtE,UAAM,WAAW,KAAK,IAAA,IAAQ;AAE9B,kBAAc,KAAK,4BAA4B;AAAA,MAC7C;AAAA,MACA,UAAU,QAAQ;AAAA,MAClB;AAAA,MACA,OAAO,OAAO;AAAA,MACd,QAAQ,OAAO;AAAA,MACf,eAAe,OAAO;AAAA,MACtB,aAAa,OAAO;AAAA,MACpB;AAAA,MACA,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK,IAAA;AAAA,IAAI,CACrB;AAED,QAAI,OAAO,OAAO;AAChB,oBAAc,KAAK,gBAAgB;AAAA,QACjC;AAAA,QACA;AAAA,QACA,OAAO,OAAO;AAAA,QACd,cAAc,KAAK;AAAA,QACnB,WAAW,KAAK,IAAA;AAAA,MAAI,CACrB;AAAA,IACH;AAEA,WAAO,OAAO,iCAAiC,OAAO,MAAM,MAAM,IAAI;AAAA,MACpE,OAAO,OAAO,MAAM;AAAA,MACpB,aAAa,OAAO;AAAA,IAAA,CACrB;AAED,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,WAAW,KAAK,IAAA,IAAQ;AAC9B,UAAM,MAAM;AACZ,kBAAc,KAAK,wBAAwB;AAAA,MACzC;AAAA,MACA,UAAU,QAAQ;AAAA,MAClB;AAAA,MACA,OAAO,EAAE,SAAS,IAAI,SAAS,MAAM,IAAI,KAAA;AAAA,MACzC;AAAA,MACA,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK,IAAA;AAAA,IAAI,CACrB;AACD,WAAO,OAAO,kCAAkC;AAAA,MAC9C;AAAA,MACA,QAAQ;AAAA,IAAA,CACT;AACD,UAAM;AAAA,EACR;AACF;AASO,SAAS,oBAId,SACuC;AACvC,SAAO;AACT;"}
|
|
@@ -2,4 +2,4 @@ export type { ResolvedCategories } from './logger/internal-logger.js';
|
|
|
2
2
|
export { InternalLogger } from './logger/internal-logger.js';
|
|
3
3
|
export type { Logger } from './logger/types.js';
|
|
4
4
|
export { resolveDebugOption } from './logger/resolve.js';
|
|
5
|
-
export { toRunErrorPayload } from './activities/error-payload.js';
|
|
5
|
+
export { toRunErrorPayload, toRunErrorRawEvent, } from './activities/error-payload.js';
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { InternalLogger } from "./logger/internal-logger.js";
|
|
2
2
|
import { resolveDebugOption } from "./logger/resolve.js";
|
|
3
|
-
import { toRunErrorPayload } from "./activities/error-payload.js";
|
|
3
|
+
import { toRunErrorPayload, toRunErrorRawEvent } from "./activities/error-payload.js";
|
|
4
4
|
export {
|
|
5
5
|
InternalLogger,
|
|
6
6
|
resolveDebugOption,
|
|
7
|
-
toRunErrorPayload
|
|
7
|
+
toRunErrorPayload,
|
|
8
|
+
toRunErrorRawEvent
|
|
8
9
|
};
|
|
9
10
|
//# sourceMappingURL=adapter-internals.js.map
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export declare enum EventType {
|
|
|
34
34
|
REASONING_ENCRYPTED_VALUE = "REASONING_ENCRYPTED_VALUE"
|
|
35
35
|
}
|
|
36
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';
|
|
37
|
+
export { convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema, } from './activities/chat/tools/schema-converter.js';
|
|
38
38
|
export { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages, } from './activities/chat/messages.js';
|
|
39
39
|
export { BatchStrategy, CompositeStrategy, defaultJSONParser, ImmediateStrategy, parsePartialJSON, PartialJSONParser, PunctuationStrategy, StreamProcessor, WordBoundaryStrategy, } from './activities/chat/stream/index.js';
|
|
40
40
|
export type { ChunkRecording, ChunkStrategy, InternalToolCallState, JSONParser, ProcessorResult, ProcessorState, StreamProcessorEvents, StreamProcessorOptions, ToolCallState, ToolResultState, } from './activities/chat/stream/index.js';
|
package/dist/esm/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { toolDefinition } from "./activities/chat/tools/tool-definition.js";
|
|
2
|
-
import { convertSchemaToJsonSchema } from "./activities/chat/tools/schema-converter.js";
|
|
2
|
+
import { convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema } from "./activities/chat/tools/schema-converter.js";
|
|
3
3
|
import { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages } from "./activities/chat/messages.js";
|
|
4
4
|
import { uiMessagesToWire } from "./utilities/ag-ui-wire.js";
|
|
5
5
|
import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PunctuationStrategy, WordBoundaryStrategy } from "./activities/chat/stream/strategies.js";
|
|
@@ -54,10 +54,12 @@ export {
|
|
|
54
54
|
convertSchemaToJsonSchema,
|
|
55
55
|
defaultJSONParser,
|
|
56
56
|
generateMessageId,
|
|
57
|
+
isStandardSchema,
|
|
57
58
|
modelMessageToUIMessage,
|
|
58
59
|
modelMessagesToUIMessages,
|
|
59
60
|
normalizeToUIMessage,
|
|
60
61
|
parsePartialJSON,
|
|
62
|
+
parseWithStandardSchema,
|
|
61
63
|
toolDefinition,
|
|
62
64
|
uiMessageToModelMessages,
|
|
63
65
|
uiMessagesToWire
|
package/dist/esm/client.js.map
CHANGED
|
@@ -1 +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 {
|
|
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 {\n convertSchemaToJsonSchema,\n isStandardSchema,\n parseWithStandardSchema,\n} 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/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export { createSpeechOptions } from './activities/generateSpeech/index.js';
|
|
|
8
8
|
export { createTranscriptionOptions } from './activities/generateTranscription/index.js';
|
|
9
9
|
export type { AIAdapter, ImageAdapter, AnyImageAdapter, TextAdapter, AnyTextAdapter, AnySummarizeAdapter, SummarizeAdapter, AnyAudioAdapter, AudioAdapter, AnyTTSAdapter, TTSAdapter, AnyTranscriptionAdapter, TranscriptionAdapter, AnyVideoAdapter, VideoAdapter, } from './activities/index.js';
|
|
10
10
|
export { toolDefinition, type ToolDefinition, type ToolDefinitionInstance, type ToolDefinitionConfig, type ServerTool, type ClientTool, type AnyClientTool, type InferToolName, type InferToolInput, type InferToolOutput, } from './activities/chat/tools/tool-definition.js';
|
|
11
|
-
export { convertSchemaToJsonSchema, StandardSchemaValidationError, } from './activities/chat/tools/schema-converter.js';
|
|
11
|
+
export { convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema, StandardSchemaValidationError, } from './activities/chat/tools/schema-converter.js';
|
|
12
12
|
export { streamToText, toServerSentEventsStream, toServerSentEventsResponse, toHttpStream, toHttpResponse, } from './stream-to-response.js';
|
|
13
13
|
export { ToolCallManager } from './activities/chat/tools/tool-calls.js';
|
|
14
14
|
export type { ProviderTool } from './tools/provider-tool.js';
|
|
@@ -17,6 +17,7 @@ export { maxIterations, untilFinishReason, combineStrategies, } from './activiti
|
|
|
17
17
|
export { createToolRegistry, createFrozenRegistry, type ToolRegistry, } from './tool-registry.js';
|
|
18
18
|
export type { ChatMiddleware, ChatMiddlewareContext, ChatMiddlewarePhase, ChatMiddlewareConfig, StructuredOutputMiddlewareConfig, ToolCallHookContext, BeforeToolCallDecision, AfterToolCallInfo, IterationInfo, ToolPhaseCompleteInfo, UsageInfo, FinishInfo, AbortInfo, ErrorInfo, } from './activities/chat/middleware/index.js';
|
|
19
19
|
export * from './types.js';
|
|
20
|
+
export { buildBaseUsage, type BaseUsageInput } from './utilities/usage.js';
|
|
20
21
|
export type { SystemPrompt, NormalizedSystemPrompt } from './system-prompts.js';
|
|
21
22
|
export { normalizeSystemPrompts } from './system-prompts.js';
|
|
22
23
|
export { detectImageMimeType } from './utils.js';
|
|
@@ -28,6 +29,7 @@ export type { ChunkStrategy, ChunkRecording, InternalToolCallState, ProcessorRes
|
|
|
28
29
|
export { chatParamsFromRequest, chatParamsFromRequestBody, mergeAgentTools, } from './utilities/chat-params.js';
|
|
29
30
|
export { uiMessagesToWire } from './utilities/ag-ui-wire.js';
|
|
30
31
|
export type { WireMessage } from './utilities/ag-ui-wire.js';
|
|
32
|
+
export { isContentPart, isContentPartArray, normalizeToolResult, } from './utilities/tool-result.js';
|
|
31
33
|
export { createModel, extendAdapter } from './extend-adapter.js';
|
|
32
34
|
export type { ExtendedModelDef } from './extend-adapter.js';
|
|
33
35
|
export type { Logger, DebugCategories, DebugConfig, DebugOption, } from './logger/types.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -6,18 +6,20 @@ import { createVideoOptions, generateVideo, getVideoJobStatus } from "./activiti
|
|
|
6
6
|
import { createSpeechOptions, generateSpeech } from "./activities/generateSpeech/index.js";
|
|
7
7
|
import { createTranscriptionOptions, generateTranscription } from "./activities/generateTranscription/index.js";
|
|
8
8
|
import { toolDefinition } from "./activities/chat/tools/tool-definition.js";
|
|
9
|
-
import { StandardSchemaValidationError, convertSchemaToJsonSchema } from "./activities/chat/tools/schema-converter.js";
|
|
9
|
+
import { StandardSchemaValidationError, convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema } from "./activities/chat/tools/schema-converter.js";
|
|
10
10
|
import { streamToText, toHttpResponse, toHttpStream, toServerSentEventsResponse, toServerSentEventsStream } from "./stream-to-response.js";
|
|
11
11
|
import { ToolCallManager } from "./activities/chat/tools/tool-calls.js";
|
|
12
12
|
import { brandProviderTool } from "./tools/provider-tool.js";
|
|
13
13
|
import { combineStrategies, maxIterations, untilFinishReason } from "./activities/chat/agent-loop-strategies.js";
|
|
14
14
|
import { createFrozenRegistry, createToolRegistry } from "./tool-registry.js";
|
|
15
|
+
import { buildBaseUsage } from "./utilities/usage.js";
|
|
15
16
|
import { normalizeSystemPrompts } from "./system-prompts.js";
|
|
16
17
|
import { detectImageMimeType } from "./utils.js";
|
|
17
18
|
import { realtimeToken } from "./realtime/index.js";
|
|
18
19
|
import { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages } from "./activities/chat/messages.js";
|
|
19
20
|
import { chatParamsFromRequest, chatParamsFromRequestBody, mergeAgentTools } from "./utilities/chat-params.js";
|
|
20
21
|
import { uiMessagesToWire } from "./utilities/ag-ui-wire.js";
|
|
22
|
+
import { isContentPart, isContentPartArray, normalizeToolResult } from "./utilities/tool-result.js";
|
|
21
23
|
import { createModel, extendAdapter } from "./extend-adapter.js";
|
|
22
24
|
import { ConsoleLogger } from "./logger/console-logger.js";
|
|
23
25
|
import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PunctuationStrategy, WordBoundaryStrategy } from "./activities/chat/stream/strategies.js";
|
|
@@ -37,6 +39,7 @@ export {
|
|
|
37
39
|
ToolCallManager,
|
|
38
40
|
WordBoundaryStrategy,
|
|
39
41
|
brandProviderTool,
|
|
42
|
+
buildBaseUsage,
|
|
40
43
|
chat,
|
|
41
44
|
chatParamsFromRequest,
|
|
42
45
|
chatParamsFromRequestBody,
|
|
@@ -64,13 +67,18 @@ export {
|
|
|
64
67
|
generateTranscription,
|
|
65
68
|
generateVideo,
|
|
66
69
|
getVideoJobStatus,
|
|
70
|
+
isContentPart,
|
|
71
|
+
isContentPartArray,
|
|
72
|
+
isStandardSchema,
|
|
67
73
|
maxIterations,
|
|
68
74
|
mergeAgentTools,
|
|
69
75
|
modelMessageToUIMessage,
|
|
70
76
|
modelMessagesToUIMessages,
|
|
71
77
|
normalizeSystemPrompts,
|
|
72
78
|
normalizeToUIMessage,
|
|
79
|
+
normalizeToolResult,
|
|
73
80
|
parsePartialJSON,
|
|
81
|
+
parseWithStandardSchema,
|
|
74
82
|
realtimeToken,
|
|
75
83
|
streamToText,
|
|
76
84
|
summarize,
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AnyTool } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* A registry that holds tools and allows dynamic tool management.
|
|
4
4
|
*
|
|
5
5
|
* The registry can be either mutable (allowing additions/removals during execution)
|
|
6
6
|
* or frozen (static tool list, for backward compatibility with tools arrays).
|
|
7
7
|
*/
|
|
8
|
-
export interface ToolRegistry {
|
|
8
|
+
export interface ToolRegistry<TTool extends AnyTool = AnyTool> {
|
|
9
9
|
/**
|
|
10
10
|
* Get all current tools in the registry.
|
|
11
11
|
* Called each agent loop iteration to get the latest tool list.
|
|
12
12
|
*/
|
|
13
|
-
getTools: () =>
|
|
13
|
+
getTools: () => Array<TTool>;
|
|
14
14
|
/**
|
|
15
15
|
* Add a tool to the registry dynamically.
|
|
16
16
|
* For frozen registries, this is a no-op.
|
|
17
17
|
*
|
|
18
18
|
* @param tool - The tool to add
|
|
19
19
|
*/
|
|
20
|
-
add: (tool:
|
|
20
|
+
add: (tool: TTool) => void;
|
|
21
21
|
/**
|
|
22
22
|
* Remove a tool from the registry by name.
|
|
23
23
|
* For frozen registries, this always returns false.
|
|
@@ -38,7 +38,7 @@ export interface ToolRegistry {
|
|
|
38
38
|
* @param name - The name of the tool to get
|
|
39
39
|
* @returns The tool if found, undefined otherwise
|
|
40
40
|
*/
|
|
41
|
-
get: (name: string) =>
|
|
41
|
+
get: (name: string) => TTool | undefined;
|
|
42
42
|
/**
|
|
43
43
|
* Whether this registry is frozen (immutable).
|
|
44
44
|
* Frozen registries don't allow add/remove operations.
|
|
@@ -68,7 +68,7 @@ export interface ToolRegistry {
|
|
|
68
68
|
* registry.add(newTool) // Immediately available to LLM
|
|
69
69
|
* ```
|
|
70
70
|
*/
|
|
71
|
-
export declare function createToolRegistry(initialTools?: Array<
|
|
71
|
+
export declare function createToolRegistry<TTool extends AnyTool = AnyTool>(initialTools?: Array<TTool>): ToolRegistry<TTool>;
|
|
72
72
|
/**
|
|
73
73
|
* Create a frozen (immutable) tool registry from a tools array.
|
|
74
74
|
*
|
|
@@ -78,4 +78,4 @@ export declare function createToolRegistry(initialTools?: Array<Tool>): ToolRegi
|
|
|
78
78
|
* @param tools - The static array of tools
|
|
79
79
|
* @returns A frozen ToolRegistry
|
|
80
80
|
*/
|
|
81
|
-
export declare function createFrozenRegistry(tools?: Array<
|
|
81
|
+
export declare function createFrozenRegistry<TTool extends AnyTool = AnyTool>(tools?: Array<TTool>): ToolRegistry<TTool>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-registry.js","sources":["../../src/tool-registry.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"tool-registry.js","sources":["../../src/tool-registry.ts"],"sourcesContent":["import type { AnyTool } from './types'\n\n/**\n * A registry that holds tools and allows dynamic tool management.\n *\n * The registry can be either mutable (allowing additions/removals during execution)\n * or frozen (static tool list, for backward compatibility with tools arrays).\n */\nexport interface ToolRegistry<TTool extends AnyTool = AnyTool> {\n /**\n * Get all current tools in the registry.\n * Called each agent loop iteration to get the latest tool list.\n */\n getTools: () => Array<TTool>\n\n /**\n * Add a tool to the registry dynamically.\n * For frozen registries, this is a no-op.\n *\n * @param tool - The tool to add\n */\n add: (tool: TTool) => void\n\n /**\n * Remove a tool from the registry by name.\n * For frozen registries, this always returns false.\n *\n * @param name - The name of the tool to remove\n * @returns true if the tool was removed, false if not found or frozen\n */\n remove: (name: string) => boolean\n\n /**\n * Check if a tool exists in the registry.\n *\n * @param name - The name of the tool to check\n */\n has: (name: string) => boolean\n\n /**\n * Get a tool by name.\n *\n * @param name - The name of the tool to get\n * @returns The tool if found, undefined otherwise\n */\n get: (name: string) => TTool | undefined\n\n /**\n * Whether this registry is frozen (immutable).\n * Frozen registries don't allow add/remove operations.\n */\n readonly isFrozen: boolean\n}\n\n/**\n * Create a mutable tool registry for dynamic tool scenarios.\n *\n * Tools can be added and removed during chat execution, and the\n * changes will be reflected in subsequent agent loop iterations.\n *\n * @param initialTools - Optional initial set of tools\n * @returns A mutable ToolRegistry\n *\n * @example\n * ```typescript\n * const registry = createToolRegistry([toolA, toolB])\n *\n * const stream = chat({\n * adapter,\n * messages,\n * toolRegistry: registry,\n * })\n *\n * // Later, during tool execution:\n * registry.add(newTool) // Immediately available to LLM\n * ```\n */\nexport function createToolRegistry<TTool extends AnyTool = AnyTool>(\n initialTools: Array<TTool> = [],\n): ToolRegistry<TTool> {\n const tools = new Map<string, TTool>()\n\n for (const tool of initialTools) {\n tools.set(tool.name, tool)\n }\n\n return {\n getTools: () => Array.from(tools.values()),\n\n add: (tool: TTool) => {\n tools.set(tool.name, tool)\n },\n\n remove: (name: string) => {\n return tools.delete(name)\n },\n\n has: (name: string) => {\n return tools.has(name)\n },\n\n get: (name: string) => {\n return tools.get(name)\n },\n\n isFrozen: false,\n }\n}\n\n/**\n * Create a frozen (immutable) tool registry from a tools array.\n *\n * This is used internally to wrap static `tools` arrays for backward compatibility.\n * Add and remove operations are no-ops on frozen registries.\n *\n * @param tools - The static array of tools\n * @returns A frozen ToolRegistry\n */\nexport function createFrozenRegistry<TTool extends AnyTool = AnyTool>(\n tools: Array<TTool> = [],\n): ToolRegistry<TTool> {\n const toolMap = new Map<string, TTool>()\n\n for (const tool of tools) {\n toolMap.set(tool.name, tool)\n }\n\n const frozenTools = Object.freeze([...tools])\n\n return {\n getTools: () => [...frozenTools],\n\n add: (_tool: TTool) => {\n // No-op for frozen registry\n },\n\n remove: (_name: string) => {\n // No-op for frozen registry\n return false\n },\n\n has: (name: string) => {\n return toolMap.has(name)\n },\n\n get: (name: string) => {\n return toolMap.get(name)\n },\n\n isFrozen: true,\n }\n}\n"],"names":[],"mappings":"AA6EO,SAAS,mBACd,eAA6B,IACR;AACrB,QAAM,4BAAY,IAAA;AAElB,aAAW,QAAQ,cAAc;AAC/B,UAAM,IAAI,KAAK,MAAM,IAAI;AAAA,EAC3B;AAEA,SAAO;AAAA,IACL,UAAU,MAAM,MAAM,KAAK,MAAM,QAAQ;AAAA,IAEzC,KAAK,CAAC,SAAgB;AACpB,YAAM,IAAI,KAAK,MAAM,IAAI;AAAA,IAC3B;AAAA,IAEA,QAAQ,CAAC,SAAiB;AACxB,aAAO,MAAM,OAAO,IAAI;AAAA,IAC1B;AAAA,IAEA,KAAK,CAAC,SAAiB;AACrB,aAAO,MAAM,IAAI,IAAI;AAAA,IACvB;AAAA,IAEA,KAAK,CAAC,SAAiB;AACrB,aAAO,MAAM,IAAI,IAAI;AAAA,IACvB;AAAA,IAEA,UAAU;AAAA,EAAA;AAEd;AAWO,SAAS,qBACd,QAAsB,IACD;AACrB,QAAM,8BAAc,IAAA;AAEpB,aAAW,QAAQ,OAAO;AACxB,YAAQ,IAAI,KAAK,MAAM,IAAI;AAAA,EAC7B;AAEA,QAAM,cAAc,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;AAE5C,SAAO;AAAA,IACL,UAAU,MAAM,CAAC,GAAG,WAAW;AAAA,IAE/B,KAAK,CAAC,UAAiB;AAAA,IAEvB;AAAA,IAEA,QAAQ,CAAC,UAAkB;AAEzB,aAAO;AAAA,IACT;AAAA,IAEA,KAAK,CAAC,SAAiB;AACrB,aAAO,QAAQ,IAAI,IAAI;AAAA,IACzB;AAAA,IAEA,KAAK,CAAC,SAAiB;AACrB,aAAO,QAAQ,IAAI,IAAI;AAAA,IACzB;AAAA,IAEA,UAAU;AAAA,EAAA;AAEd;"}
|
package/dist/esm/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
2
|
import { InternalLogger } from './logger/internal-logger.js';
|
|
3
3
|
import { SystemPrompt } from './system-prompts.js';
|
|
4
|
+
import { CompletionTokensDetails, PromptTokensDetails, ProviderUsageDetails, TokenUsage, UsageCostBreakdown } from '@tanstack/ai-event-client';
|
|
4
5
|
import { BaseEvent as AGUIBaseEvent, CustomEvent as AGUICustomEvent, MessagesSnapshotEvent as AGUIMessagesSnapshotEvent, ReasoningEncryptedValueEvent as AGUIReasoningEncryptedValueEvent, ReasoningEndEvent as AGUIReasoningEndEvent, ReasoningMessageContentEvent as AGUIReasoningMessageContentEvent, ReasoningMessageEndEvent as AGUIReasoningMessageEndEvent, ReasoningMessageStartEvent as AGUIReasoningMessageStartEvent, ReasoningStartEvent as AGUIReasoningStartEvent, RunErrorEvent as AGUIRunErrorEvent, RunFinishedEvent as AGUIRunFinishedEvent, RunStartedEvent as AGUIRunStartedEvent, StateDeltaEvent as AGUIStateDeltaEvent, StateSnapshotEvent as AGUIStateSnapshotEvent, StepFinishedEvent as AGUIStepFinishedEvent, StepStartedEvent as AGUIStepStartedEvent, TextMessageContentEvent as AGUITextMessageContentEvent, TextMessageEndEvent as AGUITextMessageEndEvent, TextMessageStartEvent as AGUITextMessageStartEvent, ToolCallArgsEvent as AGUIToolCallArgsEvent, ToolCallEndEvent as AGUIToolCallEndEvent, ToolCallResultEvent as AGUIToolCallResultEvent, ToolCallStartEvent as AGUIToolCallStartEvent, EventType } from '@ag-ui/core';
|
|
5
6
|
/**
|
|
6
7
|
* Tool call states - track the lifecycle of a tool call
|
|
@@ -10,6 +11,7 @@ export type ToolCallState = 'awaiting-input' | 'input-streaming' | 'input-comple
|
|
|
10
11
|
* Tool result states - track the lifecycle of a tool result
|
|
11
12
|
*/
|
|
12
13
|
export type ToolResultState = 'streaming' | 'complete' | 'error';
|
|
14
|
+
export type ToolOutputState = 'output-available' | 'output-error';
|
|
13
15
|
/**
|
|
14
16
|
* JSON Schema type for defining tool input/output schemas as raw JSON Schema objects.
|
|
15
17
|
* This allows tools to be defined without schema libraries when you have JSON Schema definitions available.
|
|
@@ -255,7 +257,7 @@ export interface ToolCallPart<TMetadata = unknown> {
|
|
|
255
257
|
export interface ToolResultPart {
|
|
256
258
|
type: 'tool-result';
|
|
257
259
|
toolCallId: string;
|
|
258
|
-
content: string
|
|
260
|
+
content: string | Array<ContentPart>;
|
|
259
261
|
state: ToolResultState;
|
|
260
262
|
error?: string;
|
|
261
263
|
}
|
|
@@ -321,11 +323,29 @@ export type InputModalitiesTypes = {
|
|
|
321
323
|
export type ConstrainedModelMessage<TInputModalitiesTypes extends InputModalitiesTypes> = Omit<ModelMessage, 'content'> & {
|
|
322
324
|
content: ConstrainedContent<TInputModalitiesTypes>;
|
|
323
325
|
};
|
|
326
|
+
type IsUnknown<T> = unknown extends T ? [T] extends [unknown] ? true : false : false;
|
|
327
|
+
type RuntimeContextField<TContext> = IsUnknown<TContext> extends true ? {
|
|
328
|
+
/**
|
|
329
|
+
* Runtime context provided by the caller.
|
|
330
|
+
*
|
|
331
|
+
* This is request-local application state for tool and middleware
|
|
332
|
+
* implementations, not the AG-UI `Context[]` protocol field.
|
|
333
|
+
*/
|
|
334
|
+
context?: TContext;
|
|
335
|
+
} : {
|
|
336
|
+
/**
|
|
337
|
+
* Runtime context provided by the caller.
|
|
338
|
+
*
|
|
339
|
+
* This is request-local application state for tool and middleware
|
|
340
|
+
* implementations, not the AG-UI `Context[]` protocol field.
|
|
341
|
+
*/
|
|
342
|
+
context: TContext;
|
|
343
|
+
};
|
|
324
344
|
/**
|
|
325
345
|
* Context passed to tool execute functions, providing capabilities like
|
|
326
346
|
* emitting custom events during execution.
|
|
327
347
|
*/
|
|
328
|
-
export
|
|
348
|
+
export type ToolExecutionContext<TContext = unknown> = RuntimeContextField<TContext> & {
|
|
329
349
|
/** The ID of the tool call being executed */
|
|
330
350
|
toolCallId?: string;
|
|
331
351
|
/**
|
|
@@ -347,7 +367,8 @@ export interface ToolExecutionContext {
|
|
|
347
367
|
* ```
|
|
348
368
|
*/
|
|
349
369
|
emitCustomEvent: (eventName: string, value: Record<string, any>) => void;
|
|
350
|
-
}
|
|
370
|
+
};
|
|
371
|
+
export type ToolExecuteFunction<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TContext = unknown> = undefined extends TContext ? (args: InferSchemaType<TInput>, context?: ToolExecutionContext<TContext>) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput> : (args: InferSchemaType<TInput>, context: ToolExecutionContext<TContext>) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>;
|
|
351
372
|
/**
|
|
352
373
|
* Tool/Function definition for function calling.
|
|
353
374
|
*
|
|
@@ -361,7 +382,7 @@ export interface ToolExecutionContext {
|
|
|
361
382
|
* @see https://docs.anthropic.com/claude/docs/tool-use
|
|
362
383
|
* @see https://standardschema.dev/json-schema
|
|
363
384
|
*/
|
|
364
|
-
export interface Tool<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string> {
|
|
385
|
+
export interface Tool<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string, TContext = unknown> {
|
|
365
386
|
/**
|
|
366
387
|
* Unique name of the tool (used by the model to call it).
|
|
367
388
|
*
|
|
@@ -456,7 +477,7 @@ export interface Tool<TInput extends SchemaInput = SchemaInput, TOutput extends
|
|
|
456
477
|
* return weather; // Can return object or string
|
|
457
478
|
* }
|
|
458
479
|
*/
|
|
459
|
-
execute?:
|
|
480
|
+
execute?: ToolExecuteFunction<TInput, TOutput, TContext> | undefined;
|
|
460
481
|
/** If true, tool execution requires user approval before running. Works with both server and client tools. */
|
|
461
482
|
needsApproval?: boolean;
|
|
462
483
|
/** If true, this tool is lazy and will only be sent to the LLM after being discovered via the lazy tool discovery mechanism. Only meaningful when used with chat(). */
|
|
@@ -464,6 +485,9 @@ export interface Tool<TInput extends SchemaInput = SchemaInput, TOutput extends
|
|
|
464
485
|
/** Additional metadata for adapters or custom extensions */
|
|
465
486
|
metadata?: Record<string, any> | undefined;
|
|
466
487
|
}
|
|
488
|
+
export type AnyTool = Omit<Tool<any, any, any, any>, 'execute'> & {
|
|
489
|
+
execute?: ((args: any, context?: any) => any) | undefined;
|
|
490
|
+
};
|
|
467
491
|
export interface ToolConfig {
|
|
468
492
|
[key: string]: Tool;
|
|
469
493
|
}
|
|
@@ -580,10 +604,15 @@ export type AgentLoopStrategy = (state: AgentLoopState) => boolean;
|
|
|
580
604
|
/**
|
|
581
605
|
* Options passed into the SDK and further piped to the AI provider.
|
|
582
606
|
*/
|
|
583
|
-
export interface TextOptions<TProviderOptionsSuperset extends Record<string, any> = Record<string, any>, TProviderOptionsForModel = TProviderOptionsSuperset> {
|
|
607
|
+
export interface TextOptions<TProviderOptionsSuperset extends Record<string, any> = Record<string, any>, TProviderOptionsForModel = TProviderOptionsSuperset, TContext = unknown> {
|
|
584
608
|
model: string;
|
|
585
609
|
messages: Array<ModelMessage>;
|
|
586
|
-
tools?: Array<
|
|
610
|
+
tools?: Array<AnyTool> | undefined;
|
|
611
|
+
/**
|
|
612
|
+
* Runtime context provided by the caller and passed to middleware and
|
|
613
|
+
* server-side tool implementations.
|
|
614
|
+
*/
|
|
615
|
+
context?: TContext;
|
|
587
616
|
/**
|
|
588
617
|
* System prompts to include with the request.
|
|
589
618
|
*
|
|
@@ -759,37 +788,13 @@ export interface RunStartedEvent extends AGUIRunStartedEvent {
|
|
|
759
788
|
/** Model identifier for multi-model support */
|
|
760
789
|
model?: string;
|
|
761
790
|
}
|
|
791
|
+
export type { CompletionTokensDetails, PromptTokensDetails, ProviderUsageDetails, TokenUsage, UsageCostBreakdown, };
|
|
762
792
|
/**
|
|
763
|
-
*
|
|
764
|
-
*
|
|
765
|
-
*
|
|
766
|
-
* `upstream_inference_prompt_cost`, `upstream_inference_input_cost`) onto these
|
|
767
|
-
* fields at runtime.
|
|
793
|
+
* @deprecated Renamed to {@link TokenUsage}. Kept as an alias for backward
|
|
794
|
+
* compatibility with `@tanstack/ai@0.23` and earlier; will be removed in a
|
|
795
|
+
* future release.
|
|
768
796
|
*/
|
|
769
|
-
export
|
|
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
|
-
}
|
|
797
|
+
export type UsageTotals = TokenUsage;
|
|
793
798
|
/**
|
|
794
799
|
* Emitted when a run completes successfully.
|
|
795
800
|
*
|
|
@@ -801,8 +806,8 @@ export interface RunFinishedEvent extends AGUIRunFinishedEvent {
|
|
|
801
806
|
model?: string;
|
|
802
807
|
/** Why the generation stopped */
|
|
803
808
|
finishReason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null;
|
|
804
|
-
/** Token usage statistics
|
|
805
|
-
usage?:
|
|
809
|
+
/** Token usage statistics with optional detailed breakdowns and provider-reported cost. */
|
|
810
|
+
usage?: TokenUsage;
|
|
806
811
|
}
|
|
807
812
|
/**
|
|
808
813
|
* Emitted when an error occurs during a run.
|
|
@@ -907,7 +912,9 @@ export interface ToolCallEndEvent extends AGUIToolCallEndEvent {
|
|
|
907
912
|
/** Final parsed input arguments (TanStack AI internal) */
|
|
908
913
|
input?: unknown;
|
|
909
914
|
/** Tool execution result (TanStack AI internal) */
|
|
910
|
-
result?: string
|
|
915
|
+
result?: string | Array<ContentPart>;
|
|
916
|
+
/** Tool execution output state (TanStack AI internal) */
|
|
917
|
+
state?: ToolOutputState;
|
|
911
918
|
}
|
|
912
919
|
/**
|
|
913
920
|
* Emitted when a tool call result is available.
|
|
@@ -918,6 +925,8 @@ export interface ToolCallEndEvent extends AGUIToolCallEndEvent {
|
|
|
918
925
|
export interface ToolCallResultEvent extends AGUIToolCallResultEvent {
|
|
919
926
|
/** Model identifier for multi-model support */
|
|
920
927
|
model?: string;
|
|
928
|
+
/** Tool execution output state (TanStack AI internal) */
|
|
929
|
+
state?: ToolOutputState;
|
|
921
930
|
}
|
|
922
931
|
/**
|
|
923
932
|
* Emitted when a thinking/reasoning step starts.
|
|
@@ -1187,11 +1196,7 @@ export interface TextCompletionChunk {
|
|
|
1187
1196
|
content: string;
|
|
1188
1197
|
role?: 'assistant';
|
|
1189
1198
|
finishReason?: 'stop' | 'length' | 'content_filter' | null;
|
|
1190
|
-
usage?:
|
|
1191
|
-
promptTokens: number;
|
|
1192
|
-
completionTokens: number;
|
|
1193
|
-
totalTokens: number;
|
|
1194
|
-
};
|
|
1199
|
+
usage?: TokenUsage;
|
|
1195
1200
|
}
|
|
1196
1201
|
export interface SummarizationOptions<TProviderOptions extends object = Record<string, unknown>> {
|
|
1197
1202
|
model: string;
|
|
@@ -1211,11 +1216,7 @@ export interface SummarizationResult {
|
|
|
1211
1216
|
id: string;
|
|
1212
1217
|
model: string;
|
|
1213
1218
|
summary: string;
|
|
1214
|
-
usage:
|
|
1215
|
-
promptTokens: number;
|
|
1216
|
-
completionTokens: number;
|
|
1217
|
-
totalTokens: number;
|
|
1218
|
-
};
|
|
1219
|
+
usage: TokenUsage;
|
|
1219
1220
|
}
|
|
1220
1221
|
/**
|
|
1221
1222
|
* Options for image generation.
|
|
@@ -1271,11 +1272,7 @@ export interface ImageGenerationResult {
|
|
|
1271
1272
|
/** Array of generated images */
|
|
1272
1273
|
images: Array<GeneratedImage>;
|
|
1273
1274
|
/** Token usage information (if available) */
|
|
1274
|
-
usage?:
|
|
1275
|
-
inputTokens?: number;
|
|
1276
|
-
outputTokens?: number;
|
|
1277
|
-
totalTokens?: number;
|
|
1278
|
-
};
|
|
1275
|
+
usage?: TokenUsage;
|
|
1279
1276
|
}
|
|
1280
1277
|
/**
|
|
1281
1278
|
* Options for audio generation (music, sound effects, etc.).
|
|
@@ -1317,11 +1314,7 @@ export interface AudioGenerationResult {
|
|
|
1317
1314
|
/** The generated audio */
|
|
1318
1315
|
audio: GeneratedAudio;
|
|
1319
1316
|
/** Token usage information (if available) */
|
|
1320
|
-
usage?:
|
|
1321
|
-
inputTokens?: number;
|
|
1322
|
-
outputTokens?: number;
|
|
1323
|
-
totalTokens?: number;
|
|
1324
|
-
};
|
|
1317
|
+
usage?: TokenUsage;
|
|
1325
1318
|
}
|
|
1326
1319
|
/**
|
|
1327
1320
|
* Options for video generation.
|
|
@@ -1425,6 +1418,8 @@ export interface TTSResult {
|
|
|
1425
1418
|
duration?: number;
|
|
1426
1419
|
/** Content type of the audio (e.g., 'audio/mp3') */
|
|
1427
1420
|
contentType?: string;
|
|
1421
|
+
/** Token usage information (if provided by the adapter) */
|
|
1422
|
+
usage?: TokenUsage;
|
|
1428
1423
|
}
|
|
1429
1424
|
/**
|
|
1430
1425
|
* Options for audio transcription.
|
|
@@ -1496,6 +1491,8 @@ export interface TranscriptionResult {
|
|
|
1496
1491
|
segments?: Array<TranscriptionSegment>;
|
|
1497
1492
|
/** Word-level timestamps, if available */
|
|
1498
1493
|
words?: Array<TranscriptionWord>;
|
|
1494
|
+
/** Token usage information (if provided by the adapter) */
|
|
1495
|
+
usage?: TokenUsage;
|
|
1499
1496
|
}
|
|
1500
1497
|
/**
|
|
1501
1498
|
* Default metadata type for adapters that don't define custom metadata.
|
|
@@ -41,7 +41,7 @@ function uiMessagesToWire(messages) {
|
|
|
41
41
|
role: "tool",
|
|
42
42
|
id: deriveToolMessageId(part.toolCallId),
|
|
43
43
|
toolCallId: part.toolCallId,
|
|
44
|
-
content: part.content,
|
|
44
|
+
content: typeof part.content === "string" ? part.content : JSON.stringify(part.content),
|
|
45
45
|
...part.error !== void 0 && { error: part.error }
|
|
46
46
|
});
|
|
47
47
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ag-ui-wire.js","sources":["../../../src/utilities/ag-ui-wire.ts"],"sourcesContent":["import type { ContentPart, MessagePart, UIMessage } from '../types'\n\ntype AGUITextInputContent = { type: 'text'; text: string }\ntype AGUIInputContent =\n | AGUITextInputContent\n | (ContentPart & { type: 'image' | 'audio' | 'video' | 'document' })\n\ntype AGUIToolCallMirror = {\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\ntype AGUIToolMessage = {\n role: 'tool'\n id: string\n toolCallId: string\n content: string\n error?: string\n}\n\ntype AGUIReasoningMessage = {\n role: 'reasoning'\n id: string\n content: string\n}\n\ntype WireAnchorMessage = UIMessage & {\n content?: string | Array<AGUIInputContent>\n toolCalls?: Array<AGUIToolCallMirror>\n}\n\nexport type WireMessage =\n | WireAnchorMessage\n | AGUIToolMessage\n | AGUIReasoningMessage\n\n/**\n * Serialize TanStack `UIMessage`s into the AG-UI `RunAgentInput.messages`\n * wire shape. Each anchor (system/user/assistant) carries the canonical\n * `parts` array verbatim plus AG-UI mirror fields (`content`, `toolCalls`)\n * so AG-UI Zod parsing succeeds. Tool results and thinking parts on\n * assistant messages are additionally emitted as fan-out\n * `{role:'tool',...}` and `{role:'reasoning',...}` entries for strict\n * AG-UI server consumers.\n */\nexport function uiMessagesToWire(\n messages: Array<UIMessage>,\n): Array<WireMessage> {\n const wire: Array<WireMessage> = []\n\n for (const msg of messages) {\n // Defensive: if parts is missing (ModelMessage-shaped input), pass through as-is.\n // UIMessage always has parts; ModelMessage uses content directly.\n const parts: ReadonlyArray<MessagePart> =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- runtime input may be ModelMessage-shaped (no `parts`); cast forces the optional-chain fallback below to remain in scope\n (msg.parts as ReadonlyArray<MessagePart> | undefined) ?? []\n\n if (msg.role === 'system') {\n wire.push({\n ...msg,\n content:\n parts.length > 0\n ? collectText(parts)\n : ((msg as { content?: string }).content ?? ''),\n })\n continue\n }\n\n if (msg.role === 'user') {\n wire.push({\n ...msg,\n content:\n parts.length > 0\n ? collectUserContent(parts)\n : ((msg as { content?: string }).content ?? ''),\n })\n continue\n }\n\n // assistant: emit reasoning fan-outs first, then anchor, then tool fan-outs\n for (const part of parts) {\n if (part.type === 'thinking') {\n wire.push({\n role: 'reasoning',\n id: deriveReasoningId(msg.id, part),\n content: part.content,\n })\n }\n }\n\n const text = collectText(parts)\n const toolCalls = collectToolCalls(parts)\n wire.push({\n ...msg,\n ...(text !== '' && { content: text }),\n ...(toolCalls && { toolCalls }),\n })\n\n for (const part of parts) {\n if (part.type === 'tool-result') {\n wire.push({\n role: 'tool',\n id: deriveToolMessageId(part.toolCallId),\n toolCallId: part.toolCallId,\n content: part.content,\n ...(part.error !== undefined && { error: part.error }),\n })\n }\n }\n }\n\n return wire\n}\n\nfunction collectText(parts: ReadonlyArray<MessagePart>): string {\n // The streamed JSON of a completed structured-output part is the source of\n // truth for multi-turn coherence — emitting it back as assistant content\n // lets the LLM see its own prior structured response. Streaming/errored\n // parts are skipped: they'd ship malformed JSON fragments and confuse the\n // model. `completeStructuredOutputPart` tries hard to populate `raw`\n // (caller → existing buffer → `JSON.stringify(data)`), but the stringify\n // fallback can leave it empty when `data` is unserializable (BigInt,\n // circular). The `p.raw !== ''` guard below is what enforces \"no malformed\n // round-trip\" in that case — without it we'd ship `''` and the model would\n // see an empty assistant turn.\n const out: Array<string> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push(p.content)\n } else if (\n p.type === 'structured-output' &&\n p.status === 'complete' &&\n p.raw !== ''\n ) {\n out.push(p.raw)\n }\n }\n return out.join('')\n}\n\nfunction collectUserContent(\n parts: ReadonlyArray<MessagePart>,\n): string | Array<AGUIInputContent> {\n const hasMultimodal = parts.some(\n (p) =>\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document',\n )\n if (!hasMultimodal) {\n return collectText(parts)\n }\n const out: Array<AGUIInputContent> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push({ type: 'text', text: p.content })\n } else if (\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document'\n ) {\n out.push(p)\n }\n }\n return out\n}\n\nfunction collectToolCalls(\n parts: ReadonlyArray<MessagePart>,\n): Array<AGUIToolCallMirror> | undefined {\n const calls: Array<AGUIToolCallMirror> = []\n for (const p of parts) {\n if (p.type === 'tool-call') {\n calls.push({\n id: p.id,\n type: 'function',\n function: { name: p.name, arguments: p.arguments },\n })\n }\n }\n return calls.length > 0 ? calls : undefined\n}\n\nfunction deriveReasoningId(messageId: string, part: MessagePart): string {\n return `${messageId}-reasoning-${(part as { id?: string }).id ?? hashContent((part as { content: string }).content)}`\n}\n\nfunction deriveToolMessageId(toolCallId: string): string {\n return `tool-${toolCallId}`\n}\n\nfunction hashContent(s: string): string {\n // Cheap deterministic id suffix; collisions are tolerable since\n // reasoning ids only matter for AG-UI server consumers, not for our\n // own server's dedup logic (which keys on toolCallId, not reasoning id).\n let h = 0\n for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0\n return Math.abs(h).toString(36)\n}\n"],"names":[],"mappings":"AA8CO,SAAS,iBACd,UACoB;AACpB,QAAM,OAA2B,CAAA;AAEjC,aAAW,OAAO,UAAU;AAG1B,UAAM;AAAA;AAAA,MAEH,IAAI,SAAoD,CAAA;AAAA;AAE3D,QAAI,IAAI,SAAS,UAAU;AACzB,WAAK,KAAK;AAAA,QACR,GAAG;AAAA,QACH,SACE,MAAM,SAAS,IACX,YAAY,KAAK,IACf,IAA6B,WAAW;AAAA,MAAA,CACjD;AACD;AAAA,IACF;AAEA,QAAI,IAAI,SAAS,QAAQ;AACvB,WAAK,KAAK;AAAA,QACR,GAAG;AAAA,QACH,SACE,MAAM,SAAS,IACX,mBAAmB,KAAK,IACtB,IAA6B,WAAW;AAAA,MAAA,CACjD;AACD;AAAA,IACF;AAGA,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,YAAY;AAC5B,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,IAAI,kBAAkB,IAAI,IAAI,IAAI;AAAA,UAClC,SAAS,KAAK;AAAA,QAAA,CACf;AAAA,MACH;AAAA,IACF;AAEA,UAAM,OAAO,YAAY,KAAK;AAC9B,UAAM,YAAY,iBAAiB,KAAK;AACxC,SAAK,KAAK;AAAA,MACR,GAAG;AAAA,MACH,GAAI,SAAS,MAAM,EAAE,SAAS,KAAA;AAAA,MAC9B,GAAI,aAAa,EAAE,UAAA;AAAA,IAAU,CAC9B;AAED,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,eAAe;AAC/B,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,IAAI,oBAAoB,KAAK,UAAU;AAAA,UACvC,YAAY,KAAK;AAAA,UACjB,
|
|
1
|
+
{"version":3,"file":"ag-ui-wire.js","sources":["../../../src/utilities/ag-ui-wire.ts"],"sourcesContent":["import type { ContentPart, MessagePart, UIMessage } from '../types'\n\ntype AGUITextInputContent = { type: 'text'; text: string }\ntype AGUIInputContent =\n | AGUITextInputContent\n | (ContentPart & { type: 'image' | 'audio' | 'video' | 'document' })\n\ntype AGUIToolCallMirror = {\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\ntype AGUIToolMessage = {\n role: 'tool'\n id: string\n toolCallId: string\n content: string\n error?: string\n}\n\ntype AGUIReasoningMessage = {\n role: 'reasoning'\n id: string\n content: string\n}\n\ntype WireAnchorMessage = UIMessage & {\n content?: string | Array<AGUIInputContent>\n toolCalls?: Array<AGUIToolCallMirror>\n}\n\nexport type WireMessage =\n | WireAnchorMessage\n | AGUIToolMessage\n | AGUIReasoningMessage\n\n/**\n * Serialize TanStack `UIMessage`s into the AG-UI `RunAgentInput.messages`\n * wire shape. Each anchor (system/user/assistant) carries the canonical\n * `parts` array verbatim plus AG-UI mirror fields (`content`, `toolCalls`)\n * so AG-UI Zod parsing succeeds. Tool results and thinking parts on\n * assistant messages are additionally emitted as fan-out\n * `{role:'tool',...}` and `{role:'reasoning',...}` entries for strict\n * AG-UI server consumers.\n */\nexport function uiMessagesToWire(\n messages: Array<UIMessage>,\n): Array<WireMessage> {\n const wire: Array<WireMessage> = []\n\n for (const msg of messages) {\n // Defensive: if parts is missing (ModelMessage-shaped input), pass through as-is.\n // UIMessage always has parts; ModelMessage uses content directly.\n const parts: ReadonlyArray<MessagePart> =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- runtime input may be ModelMessage-shaped (no `parts`); cast forces the optional-chain fallback below to remain in scope\n (msg.parts as ReadonlyArray<MessagePart> | undefined) ?? []\n\n if (msg.role === 'system') {\n wire.push({\n ...msg,\n content:\n parts.length > 0\n ? collectText(parts)\n : ((msg as { content?: string }).content ?? ''),\n })\n continue\n }\n\n if (msg.role === 'user') {\n wire.push({\n ...msg,\n content:\n parts.length > 0\n ? collectUserContent(parts)\n : ((msg as { content?: string }).content ?? ''),\n })\n continue\n }\n\n // assistant: emit reasoning fan-outs first, then anchor, then tool fan-outs\n for (const part of parts) {\n if (part.type === 'thinking') {\n wire.push({\n role: 'reasoning',\n id: deriveReasoningId(msg.id, part),\n content: part.content,\n })\n }\n }\n\n const text = collectText(parts)\n const toolCalls = collectToolCalls(parts)\n wire.push({\n ...msg,\n ...(text !== '' && { content: text }),\n ...(toolCalls && { toolCalls }),\n })\n\n for (const part of parts) {\n if (part.type === 'tool-result') {\n wire.push({\n role: 'tool',\n id: deriveToolMessageId(part.toolCallId),\n toolCallId: part.toolCallId,\n content:\n typeof part.content === 'string'\n ? part.content\n : JSON.stringify(part.content),\n ...(part.error !== undefined && { error: part.error }),\n })\n }\n }\n }\n\n return wire\n}\n\nfunction collectText(parts: ReadonlyArray<MessagePart>): string {\n // The streamed JSON of a completed structured-output part is the source of\n // truth for multi-turn coherence — emitting it back as assistant content\n // lets the LLM see its own prior structured response. Streaming/errored\n // parts are skipped: they'd ship malformed JSON fragments and confuse the\n // model. `completeStructuredOutputPart` tries hard to populate `raw`\n // (caller → existing buffer → `JSON.stringify(data)`), but the stringify\n // fallback can leave it empty when `data` is unserializable (BigInt,\n // circular). The `p.raw !== ''` guard below is what enforces \"no malformed\n // round-trip\" in that case — without it we'd ship `''` and the model would\n // see an empty assistant turn.\n const out: Array<string> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push(p.content)\n } else if (\n p.type === 'structured-output' &&\n p.status === 'complete' &&\n p.raw !== ''\n ) {\n out.push(p.raw)\n }\n }\n return out.join('')\n}\n\nfunction collectUserContent(\n parts: ReadonlyArray<MessagePart>,\n): string | Array<AGUIInputContent> {\n const hasMultimodal = parts.some(\n (p) =>\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document',\n )\n if (!hasMultimodal) {\n return collectText(parts)\n }\n const out: Array<AGUIInputContent> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push({ type: 'text', text: p.content })\n } else if (\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document'\n ) {\n out.push(p)\n }\n }\n return out\n}\n\nfunction collectToolCalls(\n parts: ReadonlyArray<MessagePart>,\n): Array<AGUIToolCallMirror> | undefined {\n const calls: Array<AGUIToolCallMirror> = []\n for (const p of parts) {\n if (p.type === 'tool-call') {\n calls.push({\n id: p.id,\n type: 'function',\n function: { name: p.name, arguments: p.arguments },\n })\n }\n }\n return calls.length > 0 ? calls : undefined\n}\n\nfunction deriveReasoningId(messageId: string, part: MessagePart): string {\n return `${messageId}-reasoning-${(part as { id?: string }).id ?? hashContent((part as { content: string }).content)}`\n}\n\nfunction deriveToolMessageId(toolCallId: string): string {\n return `tool-${toolCallId}`\n}\n\nfunction hashContent(s: string): string {\n // Cheap deterministic id suffix; collisions are tolerable since\n // reasoning ids only matter for AG-UI server consumers, not for our\n // own server's dedup logic (which keys on toolCallId, not reasoning id).\n let h = 0\n for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0\n return Math.abs(h).toString(36)\n}\n"],"names":[],"mappings":"AA8CO,SAAS,iBACd,UACoB;AACpB,QAAM,OAA2B,CAAA;AAEjC,aAAW,OAAO,UAAU;AAG1B,UAAM;AAAA;AAAA,MAEH,IAAI,SAAoD,CAAA;AAAA;AAE3D,QAAI,IAAI,SAAS,UAAU;AACzB,WAAK,KAAK;AAAA,QACR,GAAG;AAAA,QACH,SACE,MAAM,SAAS,IACX,YAAY,KAAK,IACf,IAA6B,WAAW;AAAA,MAAA,CACjD;AACD;AAAA,IACF;AAEA,QAAI,IAAI,SAAS,QAAQ;AACvB,WAAK,KAAK;AAAA,QACR,GAAG;AAAA,QACH,SACE,MAAM,SAAS,IACX,mBAAmB,KAAK,IACtB,IAA6B,WAAW;AAAA,MAAA,CACjD;AACD;AAAA,IACF;AAGA,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,YAAY;AAC5B,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,IAAI,kBAAkB,IAAI,IAAI,IAAI;AAAA,UAClC,SAAS,KAAK;AAAA,QAAA,CACf;AAAA,MACH;AAAA,IACF;AAEA,UAAM,OAAO,YAAY,KAAK;AAC9B,UAAM,YAAY,iBAAiB,KAAK;AACxC,SAAK,KAAK;AAAA,MACR,GAAG;AAAA,MACH,GAAI,SAAS,MAAM,EAAE,SAAS,KAAA;AAAA,MAC9B,GAAI,aAAa,EAAE,UAAA;AAAA,IAAU,CAC9B;AAED,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,eAAe;AAC/B,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,IAAI,oBAAoB,KAAK,UAAU;AAAA,UACvC,YAAY,KAAK;AAAA,UACjB,SACE,OAAO,KAAK,YAAY,WACpB,KAAK,UACL,KAAK,UAAU,KAAK,OAAO;AAAA,UACjC,GAAI,KAAK,UAAU,UAAa,EAAE,OAAO,KAAK,MAAA;AAAA,QAAM,CACrD;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,YAAY,OAA2C;AAW9D,QAAM,MAAqB,CAAA;AAC3B,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,QAAQ;AACrB,UAAI,KAAK,EAAE,OAAO;AAAA,IACpB,WACE,EAAE,SAAS,uBACX,EAAE,WAAW,cACb,EAAE,QAAQ,IACV;AACA,UAAI,KAAK,EAAE,GAAG;AAAA,IAChB;AAAA,EACF;AACA,SAAO,IAAI,KAAK,EAAE;AACpB;AAEA,SAAS,mBACP,OACkC;AAClC,QAAM,gBAAgB,MAAM;AAAA,IAC1B,CAAC,MACC,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS;AAAA,EAAA;AAEf,MAAI,CAAC,eAAe;AAClB,WAAO,YAAY,KAAK;AAAA,EAC1B;AACA,QAAM,MAA+B,CAAA;AACrC,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,QAAQ;AACrB,UAAI,KAAK,EAAE,MAAM,QAAQ,MAAM,EAAE,SAAS;AAAA,IAC5C,WACE,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS,YACX;AACA,UAAI,KAAK,CAAC;AAAA,IACZ;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,iBACP,OACuC;AACvC,QAAM,QAAmC,CAAA;AACzC,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,aAAa;AAC1B,YAAM,KAAK;AAAA,QACT,IAAI,EAAE;AAAA,QACN,MAAM;AAAA,QACN,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,EAAE,UAAA;AAAA,MAAU,CAClD;AAAA,IACH;AAAA,EACF;AACA,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;AAEA,SAAS,kBAAkB,WAAmB,MAA2B;AACvE,SAAO,GAAG,SAAS,cAAe,KAAyB,MAAM,YAAa,KAA6B,OAAO,CAAC;AACrH;AAEA,SAAS,oBAAoB,YAA4B;AACvD,SAAO,QAAQ,UAAU;AAC3B;AAEA,SAAS,YAAY,GAAmB;AAItC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,IAAK,KAAK,IAAI,KAAK,EAAE,WAAW,CAAC,IAAK;AACpE,SAAO,KAAK,IAAI,CAAC,EAAE,SAAS,EAAE;AAChC;"}
|