@tanstack/ai 0.12.0 → 0.13.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 +6 -1
- package/dist/esm/activities/chat/adapter.js.map +1 -1
- package/dist/esm/activities/chat/index.d.ts +8 -0
- package/dist/esm/activities/chat/index.js +78 -17
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/middleware/compose.d.ts +3 -1
- package/dist/esm/activities/chat/middleware/compose.js +79 -1
- package/dist/esm/activities/chat/middleware/compose.js.map +1 -1
- package/dist/esm/activities/generateImage/index.d.ts +7 -0
- package/dist/esm/activities/generateImage/index.js +19 -3
- package/dist/esm/activities/generateImage/index.js.map +1 -1
- package/dist/esm/activities/generateSpeech/index.d.ts +7 -0
- package/dist/esm/activities/generateSpeech/index.js +21 -3
- package/dist/esm/activities/generateSpeech/index.js.map +1 -1
- package/dist/esm/activities/generateTranscription/index.d.ts +7 -0
- package/dist/esm/activities/generateTranscription/index.js +32 -13
- package/dist/esm/activities/generateTranscription/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/index.d.ts +7 -0
- package/dist/esm/activities/generateVideo/index.js +49 -7
- package/dist/esm/activities/generateVideo/index.js.map +1 -1
- package/dist/esm/activities/summarize/index.d.ts +7 -0
- package/dist/esm/activities/summarize/index.js +54 -19
- package/dist/esm/activities/summarize/index.js.map +1 -1
- package/dist/esm/adapter-internals.d.ts +3 -0
- package/dist/esm/adapter-internals.js +7 -0
- package/dist/esm/adapter-internals.js.map +1 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/logger/console-logger.d.ts +11 -0
- package/dist/esm/logger/console-logger.js +27 -0
- package/dist/esm/logger/console-logger.js.map +1 -0
- package/dist/esm/logger/internal-logger.d.ts +33 -0
- package/dist/esm/logger/internal-logger.js +69 -0
- package/dist/esm/logger/internal-logger.js.map +1 -0
- package/dist/esm/logger/resolve.d.ts +14 -0
- package/dist/esm/logger/resolve.js +54 -0
- package/dist/esm/logger/resolve.js.map +1 -0
- package/dist/esm/logger/types.d.ts +75 -0
- package/dist/esm/types.d.ts +34 -0
- package/package.json +6 -2
- package/skills/ai-core/SKILL.md +5 -3
- package/skills/ai-core/debug-logging/SKILL.md +263 -0
- package/src/activities/chat/adapter.ts +6 -1
- package/src/activities/chat/index.ts +104 -22
- package/src/activities/chat/middleware/compose.ts +84 -1
- package/src/activities/generateImage/index.ts +29 -3
- package/src/activities/generateSpeech/index.ts +35 -3
- package/src/activities/generateTranscription/index.ts +45 -13
- package/src/activities/generateVideo/index.ts +65 -6
- package/src/activities/summarize/index.ts +66 -20
- package/src/adapter-internals.ts +7 -0
- package/src/index.ts +9 -0
- package/src/logger/console-logger.ts +49 -0
- package/src/logger/internal-logger.ts +107 -0
- package/src/logger/resolve.ts +72 -0
- package/src/logger/types.ts +78 -0
- package/src/types.ts +36 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport type { VideoAdapter } from './adapter'\nimport type {\n StreamChunk,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'video' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a VideoAdapter via ~types.\n */\nexport type VideoProviderOptions<TAdapter> =\n TAdapter extends VideoAdapter<any, any, any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n/**\n * Extract the size type for a VideoAdapter's model via ~types.\n */\nexport type VideoSizeForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<infer TModel, any, any, infer TSizeMap>\n ? TModel extends keyof TSizeMap\n ? TSizeMap[TModel]\n : string\n : string\n\n// ===========================\n// Activity Options Types\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n// ===========================\n\n/**\n * Base options shared by all video activity operations.\n * The model is extracted from the adapter's model property.\n */\ninterface VideoActivityBaseOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n}\n\n/**\n * Options for creating a new video generation job.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The video adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoCreateOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = VideoActivityBaseOptions<TAdapter> & {\n /** Request type - create a new job (default if not specified) */\n request?: 'create'\n /** Text description of the desired video */\n prompt: string\n /** Video size — format depends on the provider (e.g., \"16:9\", \"1280x720\") */\n size?: VideoSizeForAdapter<TAdapter>\n /** Video duration in seconds */\n duration?: number\n /**\n * Whether to stream the video generation lifecycle.\n * When true, returns an AsyncIterable<StreamChunk> that handles the full\n * job lifecycle: create job, poll for status, yield updates, and yield final result.\n * When false or not provided, returns a Promise<VideoJobResult>.\n *\n * @default false\n */\n stream?: TStream\n /** Polling interval in milliseconds (stream mode only). @default 2000 */\n pollingInterval?: number\n /** Maximum time to wait before timing out in milliseconds (stream mode only). @default 600000 */\n maxDuration?: number\n /** Custom run ID (stream mode only) */\n runId?: string\n} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * // Start a video generation job\n * const { jobId } = await generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park'\n * })\n *\n * console.log('Job started:', jobId)\n * ```\n *\n * @example Stream the full video generation lifecycle\n * ```ts\n * import { generateVideo, toServerSentEventsResponse } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const stream = generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park',\n * stream: true,\n * pollingInterval: 3000,\n * })\n *\n * return toServerSentEventsResponse(stream)\n * ```\n */\nexport function generateVideo<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoActivityResult<'create', TStream> {\n if (options.stream) {\n return runStreamingVideoGeneration(\n options as VideoCreateOptions<TAdapter, true>,\n ) as VideoActivityResult<'create', TStream>\n }\n\n return runCreateVideoJob(options) as VideoActivityResult<'create', TStream>\n}\n\n/**\n * Internal implementation of non-streaming video job creation.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\n\n return adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n })\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n\n const threadId = createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n try {\n // Create the video generation job\n const jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n })\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n } as StreamChunk\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: {\n jobId: jobResult.jobId,\n status: 'completed',\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: any) {\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId,\n message: error.message || 'Video generation failed',\n code: error.code,\n error: {\n message: error.message || 'Video generation failed',\n code: error.code,\n },\n timestamp: Date.now(),\n } as StreamChunk\n }\n}\n\n/**\n * Get video job status - returns the current status, progress, and URL if available.\n *\n * This function combines status checking and URL retrieval. If the job is completed,\n * it will automatically fetch and include the video URL.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Check job status\n * ```ts\n * import { getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const result = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId: 'job-123'\n * })\n *\n * console.log('Status:', result.status)\n * console.log('Progress:', result.progress)\n * if (result.url) {\n * console.log('Video URL:', result.url)\n * }\n * ```\n */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: {\n adapter: TAdapter & { kind: typeof kind }\n jobId: string\n}): Promise<{\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n error?: string\n}> {\n const { adapter, jobId } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\n\n aiEventClient.emit('video:request:started', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n timestamp: startTime,\n })\n\n // Get status first\n const statusResult = await adapter.getVideoStatus(jobId)\n\n // If completed, also get the URL\n if (statusResult.status === 'completed') {\n try {\n const urlResult = await adapter.getVideoUrl(jobId)\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to get video URL'\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: 'failed',\n progress: statusResult.progress,\n error: errorMessage,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n // Provider reported completed but result fetch failed — treat as failed\n return {\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\n }\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // Return status for non-completed jobs\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateVideo() function without executing.\n */\nexport function createVideoOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoCreateOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n VideoAdapter,\n VideoAdapterConfig,\n AnyVideoAdapter,\n} from './adapter'\nexport { BaseVideoAdapter } from './adapter'\n"],"names":[],"mappings":";AAuBO,MAAM,OAAO;AA2BpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AAwKO,SAAS,cAId,SACwC;AACxC,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MACL;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO,kBAAkB,OAAO;AAClC;AAKA,eAAe,kBAEb,SAAyE;AACzE,QAAM,EAAE,SAAS,QAAQ,MAAM,UAAU,iBAAiB;AAC1D,QAAM,QAAQ,QAAQ;AAEtB,SAAO,QAAQ,eAAe;AAAA,IAC5B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACH;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAMA,gBAAgB,4BAEd,SAAyE;AACzE,QAAM,EAAE,SAAS,QAAQ,MAAM,UAAU,iBAAiB;AAC1D,QAAM,QAAQ,QAAQ;AACtB,QAAM,QAAQ,QAAQ,SAAS,SAAS,KAAK;AAC7C,QAAM,kBAAkB,QAAQ,mBAAmB;A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B;AAAA,QAC5C;AAAA,QACA,UAAU,QAAQ;AAAA,QAClB,OAAO,QAAQ;AAAA,QACf,aAAa;AAAA,QACb;AAAA,QACA,QAAQ;AAAA,QACR,UAAU,aAAa;AAAA,QACvB,OAAO;AAAA,QACP,UAAU,KAAK,IAAA,IAAQ;AAAA,QACvB,WAAW,KAAK,IAAA;AAAA,MAAI,CACrB;AAED,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,UAAU,aAAa;AAAA,QACvB,OAAO;AAAA,MAAA;AAAA,IAEX;AAAA,EACF;AAEA,gBAAc,KAAK,2BAA2B;AAAA,IAC5C;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB,OAAO,QAAQ;AAAA,IACf,aAAa;AAAA,IACb;AAAA,IACA,QAAQ,aAAa;AAAA,IACrB,UAAU,aAAa;AAAA,IACvB,OAAO,aAAa;AAAA,IACpB,UAAU,KAAK,IAAA,IAAQ;AAAA,IACvB,WAAW,KAAK,IAAA;AAAA,EAAI,CACrB;AAGD,SAAO;AAAA,IACL,QAAQ,aAAa;AAAA,IACrB,UAAU,aAAa;AAAA,IACvB,OAAO,aAAa;AAAA,EAAA;AAExB;AASO,SAAS,mBAId,SACuC;AACvC,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { VideoAdapter } from './adapter'\nimport type {\n StreamChunk,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'video' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a VideoAdapter via ~types.\n */\nexport type VideoProviderOptions<TAdapter> =\n TAdapter extends VideoAdapter<any, any, any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n/**\n * Extract the size type for a VideoAdapter's model via ~types.\n */\nexport type VideoSizeForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<infer TModel, any, any, infer TSizeMap>\n ? TModel extends keyof TSizeMap\n ? TSizeMap[TModel]\n : string\n : string\n\n// ===========================\n// Activity Options Types\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n// ===========================\n\n/**\n * Base options shared by all video activity operations.\n * The model is extracted from the adapter's model property.\n */\ninterface VideoActivityBaseOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n}\n\n/**\n * Options for creating a new video generation job.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The video adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoCreateOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = VideoActivityBaseOptions<TAdapter> & {\n /** Request type - create a new job (default if not specified) */\n request?: 'create'\n /** Text description of the desired video */\n prompt: string\n /** Video size — format depends on the provider (e.g., \"16:9\", \"1280x720\") */\n size?: VideoSizeForAdapter<TAdapter>\n /** Video duration in seconds */\n duration?: number\n /**\n * Whether to stream the video generation lifecycle.\n * When true, returns an AsyncIterable<StreamChunk> that handles the full\n * job lifecycle: create job, poll for status, yield updates, and yield final result.\n * When false or not provided, returns a Promise<VideoJobResult>.\n *\n * @default false\n */\n stream?: TStream\n /** Polling interval in milliseconds (stream mode only). @default 2000 */\n pollingInterval?: number\n /** Maximum time to wait before timing out in milliseconds (stream mode only). @default 600000 */\n maxDuration?: number\n /** Custom run ID (stream mode only) */\n runId?: string\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} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * // Start a video generation job\n * const { jobId } = await generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park'\n * })\n *\n * console.log('Job started:', jobId)\n * ```\n *\n * @example Stream the full video generation lifecycle\n * ```ts\n * import { generateVideo, toServerSentEventsResponse } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const stream = generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park',\n * stream: true,\n * pollingInterval: 3000,\n * })\n *\n * return toServerSentEventsResponse(stream)\n * ```\n */\nexport function generateVideo<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoActivityResult<'create', TStream> {\n if (options.stream) {\n return runStreamingVideoGeneration(\n options as VideoCreateOptions<TAdapter, true>,\n ) as VideoActivityResult<'create', TStream>\n }\n\n return runCreateVideoJob(options) as VideoActivityResult<'create', TStream>\n}\n\n/**\n * Internal implementation of non-streaming video job creation.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\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 logger.request(`activity=generateVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const result = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n logger.output(`activity=generateVideo jobId=${result.jobId}`, {\n jobId: result.jobId,\n model: result.model,\n })\n return result\n } catch (error) {\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n throw error\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\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 const threadId = createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n try {\n // Create the video generation job\n const jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n } as StreamChunk\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n logger.output(\n `activity=generateVideo jobId=${jobResult.jobId} status=completed`,\n {\n jobId: jobResult.jobId,\n url: urlResult.url,\n },\n )\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: {\n jobId: jobResult.jobId,\n status: 'completed',\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: any) {\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId,\n message: error.message || 'Video generation failed',\n code: error.code,\n error: {\n message: error.message || 'Video generation failed',\n code: error.code,\n },\n timestamp: Date.now(),\n } as StreamChunk\n }\n}\n\n/**\n * Get video job status - returns the current status, progress, and URL if available.\n *\n * This function combines status checking and URL retrieval. If the job is completed,\n * it will automatically fetch and include the video URL.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Check job status\n * ```ts\n * import { getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const result = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId: 'job-123'\n * })\n *\n * console.log('Status:', result.status)\n * console.log('Progress:', result.progress)\n * if (result.url) {\n * console.log('Video URL:', result.url)\n * }\n * ```\n */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: {\n adapter: TAdapter & { kind: typeof kind }\n jobId: string\n}): Promise<{\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n error?: string\n}> {\n const { adapter, jobId } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\n\n aiEventClient.emit('video:request:started', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n timestamp: startTime,\n })\n\n // Get status first\n const statusResult = await adapter.getVideoStatus(jobId)\n\n // If completed, also get the URL\n if (statusResult.status === 'completed') {\n try {\n const urlResult = await adapter.getVideoUrl(jobId)\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to get video URL'\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: 'failed',\n progress: statusResult.progress,\n error: errorMessage,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n // Provider reported completed but result fetch failed — treat as failed\n return {\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\n }\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // Return status for non-completed jobs\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateVideo() function without executing.\n */\nexport function createVideoOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoCreateOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n VideoAdapter,\n VideoAdapterConfig,\n AnyVideoAdapter,\n} from './adapter'\nexport { BaseVideoAdapter } from './adapter'\n"],"names":[],"mappings":";;AA0BO,MAAM,OAAO;AA2BpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AA8KO,SAAS,cAId,SACwC;AACxC,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MACL;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO,kBAAkB,OAAO;AAClC;AAKA,eAAe,kBAEb,SAAyE;AACzE,QAAM,EAAE,SAAS,QAAQ,MAAM,UAAU,iBAAiB;AAC1D,QAAM,QAAQ,QAAQ;AACtB,QAAM,SAAyB,mBAAmB,QAAQ,KAAK;AAC/D,QAAM,eACH,QAAiD,YACjD,QAA8B,QAC/B;AAEF,SAAO,QAAQ,mCAAmC,YAAY,IAAI;AAAA,IAChE,UAAU;AAAA,IACV;AAAA,EAAA,CACD;AAED,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ,eAAe;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA,CACD;AACD,WAAO,OAAO,gCAAgC,OAAO,KAAK,IAAI;AAAA,MAC5D,OAAO,OAAO;AAAA,MACd,OAAO,OAAO;AAAA,IAAA,CACf;AACD,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO,OAAO,iCAAiC;AAAA,MAC7C;AAAA,MACA,QAAQ;AAAA,IAAA,CACT;AACD,UAAM;AAAA,EACR;AACF;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAMA,gBAAgB,4BAEd,SAAyE;AACzE,QAAM,EAAE,SAAS,Q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AAa;AAAA,EAAA;AAExB;AASO,SAAS,mBAId,SACuC;AACvC,SAAO;AACT;"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DebugOption } from '../../logger/types.js';
|
|
1
2
|
import { SummarizeAdapter } from './adapter.js';
|
|
2
3
|
import { StreamChunk, SummarizationResult } from '../../types.js';
|
|
3
4
|
/** The adapter kind this activity handles */
|
|
@@ -34,6 +35,12 @@ export interface SummarizeActivityOptions<TAdapter extends SummarizeAdapter<stri
|
|
|
34
35
|
* @default false
|
|
35
36
|
*/
|
|
36
37
|
stream?: TStream;
|
|
38
|
+
/**
|
|
39
|
+
* Enable debug logging. Pass `true` to enable all categories, `false` to
|
|
40
|
+
* silence everything including errors, or a `DebugConfig` object for granular
|
|
41
|
+
* control and/or a custom `Logger`.
|
|
42
|
+
*/
|
|
43
|
+
debug?: DebugOption;
|
|
37
44
|
}
|
|
38
45
|
/**
|
|
39
46
|
* Result type for the summarize activity.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { aiEventClient } from "@tanstack/ai-event-client";
|
|
2
2
|
import { streamGenerationResult } from "../stream-generation-result.js";
|
|
3
|
+
import { resolveDebugOption } from "../../logger/resolve.js";
|
|
3
4
|
const kind = "summarize";
|
|
4
5
|
function createId(prefix) {
|
|
5
6
|
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
@@ -21,6 +22,7 @@ async function runSummarize(options) {
|
|
|
21
22
|
const requestId = createId("summarize");
|
|
22
23
|
const inputLength = text.length;
|
|
23
24
|
const startTime = Date.now();
|
|
25
|
+
const logger = resolveDebugOption(options.debug);
|
|
24
26
|
aiEventClient.emit("summarize:request:started", {
|
|
25
27
|
requestId,
|
|
26
28
|
provider: adapter.name,
|
|
@@ -28,42 +30,75 @@ async function runSummarize(options) {
|
|
|
28
30
|
inputLength,
|
|
29
31
|
timestamp: startTime
|
|
30
32
|
});
|
|
33
|
+
logger.request(`activity=summarize provider=${adapter.name}`, {
|
|
34
|
+
provider: adapter.name,
|
|
35
|
+
model,
|
|
36
|
+
inputLength
|
|
37
|
+
});
|
|
31
38
|
const summarizeOptions = {
|
|
32
39
|
model,
|
|
33
40
|
text,
|
|
34
41
|
maxLength,
|
|
35
42
|
style,
|
|
36
|
-
focus
|
|
43
|
+
focus,
|
|
44
|
+
logger
|
|
37
45
|
};
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
46
|
+
try {
|
|
47
|
+
const result = await adapter.summarize(summarizeOptions);
|
|
48
|
+
const duration = Date.now() - startTime;
|
|
49
|
+
const outputLength = result.summary.length;
|
|
50
|
+
aiEventClient.emit("summarize:request:completed", {
|
|
51
|
+
requestId,
|
|
52
|
+
provider: adapter.name,
|
|
53
|
+
model,
|
|
54
|
+
inputLength,
|
|
55
|
+
outputLength,
|
|
56
|
+
duration,
|
|
57
|
+
timestamp: Date.now()
|
|
58
|
+
});
|
|
59
|
+
logger.output(`activity=summarize length=${outputLength}`, {
|
|
60
|
+
hasSummary: !!result.summary,
|
|
61
|
+
outputLength
|
|
62
|
+
});
|
|
63
|
+
return result;
|
|
64
|
+
} catch (error) {
|
|
65
|
+
logger.errors("summarize activity failed", {
|
|
66
|
+
error,
|
|
67
|
+
source: "summarize"
|
|
68
|
+
});
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
51
71
|
}
|
|
52
72
|
async function* runStreamingSummarize(options) {
|
|
53
73
|
const { adapter, text, maxLength, style, focus } = options;
|
|
54
74
|
const model = adapter.model;
|
|
75
|
+
const logger = resolveDebugOption(options.debug);
|
|
76
|
+
logger.request(`activity=summarize provider=${adapter.name}`, {
|
|
77
|
+
provider: adapter.name,
|
|
78
|
+
model,
|
|
79
|
+
stream: true
|
|
80
|
+
});
|
|
55
81
|
const summarizeOptions = {
|
|
56
82
|
model,
|
|
57
83
|
text,
|
|
58
84
|
maxLength,
|
|
59
85
|
style,
|
|
60
|
-
focus
|
|
86
|
+
focus,
|
|
87
|
+
logger
|
|
61
88
|
};
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
89
|
+
try {
|
|
90
|
+
if (adapter.summarizeStream) {
|
|
91
|
+
yield* adapter.summarizeStream(summarizeOptions);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
yield* streamGenerationResult(() => adapter.summarize(summarizeOptions));
|
|
95
|
+
} catch (error) {
|
|
96
|
+
logger.errors("summarize activity failed", {
|
|
97
|
+
error,
|
|
98
|
+
source: "summarize"
|
|
99
|
+
});
|
|
100
|
+
throw error;
|
|
65
101
|
}
|
|
66
|
-
yield* streamGenerationResult(() => adapter.summarize(summarizeOptions));
|
|
67
102
|
}
|
|
68
103
|
function createSummarizeOptions(options) {
|
|
69
104
|
return options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/activities/summarize/index.ts"],"sourcesContent":["/**\n * Summarize Activity\n *\n * Generates summaries from text input.\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 type { SummarizeAdapter } from './adapter'\nimport type {\n StreamChunk,\n SummarizationOptions,\n SummarizationResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'summarize' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/** Extract provider options from a SummarizeAdapter via ~types */\nexport type SummarizeProviderOptions<TAdapter> =\n TAdapter extends SummarizeAdapter<any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the summarize activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The summarize adapter type\n * @template TStream - Whether to stream the output\n */\nexport interface SummarizeActivityOptions<\n TAdapter extends SummarizeAdapter<string, object>,\n TStream extends boolean = false,\n> {\n /** The summarize adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The text to summarize */\n text: string\n /** Maximum length of the summary (in words or characters, provider-dependent) */\n maxLength?: number\n /** Style of summary to generate */\n style?: 'bullet-points' | 'paragraph' | 'concise'\n /** Topics or aspects to focus on in the summary */\n focus?: Array<string>\n /** Provider-specific options */\n modelOptions?: SummarizeProviderOptions<TAdapter>\n /**\n * Whether to stream the summarization result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming output.\n * When false or not provided, returns a Promise<SummarizationResult>.\n *\n * @default false\n */\n stream?: TStream\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the summarize activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<SummarizationResult>\n */\nexport type SummarizeActivityResult<TStream extends boolean> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<SummarizationResult>\n\n// ===========================\n// Helper Functions\n// ===========================\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 * Summarize activity - generates summaries from text.\n *\n * Supports both streaming and non-streaming modes.\n *\n * @example Basic summarization\n * ```ts\n * import { summarize } from '@tanstack/ai'\n * import { openaiSummarize } from '@tanstack/ai-openai'\n *\n * const result = await summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long article text here...'\n * })\n *\n * console.log(result.summary)\n * ```\n *\n * @example Summarization with style\n * ```ts\n * const result = await summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long article text here...',\n * style: 'bullet-points',\n * maxLength: 100\n * })\n * ```\n *\n * @example Focused summarization\n * ```ts\n * const result = await summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long technical document...',\n * focus: ['key findings', 'methodology']\n * })\n * ```\n *\n * @example Streaming summarization\n * ```ts\n * for await (const chunk of summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long article text here...',\n * stream: true\n * })) {\n * if (chunk.type === 'content') {\n * process.stdout.write(chunk.delta)\n * }\n * }\n * ```\n */\nexport function summarize<\n TAdapter extends SummarizeAdapter<string, object>,\n TStream extends boolean = false,\n>(\n options: SummarizeActivityOptions<TAdapter, TStream>,\n): SummarizeActivityResult<TStream> {\n const { stream } = options\n\n if (stream) {\n return runStreamingSummarize(\n options as unknown as SummarizeActivityOptions<\n SummarizeAdapter<string, object>,\n true\n >,\n ) as SummarizeActivityResult<TStream>\n }\n\n return runSummarize(\n options as unknown as SummarizeActivityOptions<\n SummarizeAdapter<string, object>,\n false\n >,\n ) as SummarizeActivityResult<TStream>\n}\n\n/**\n * Run non-streaming summarization\n */\nasync function runSummarize(\n options: SummarizeActivityOptions<SummarizeAdapter<string, object>, false>,\n): Promise<SummarizationResult> {\n const { adapter, text, maxLength, style, focus } = options\n const model = adapter.model\n const requestId = createId('summarize')\n const inputLength = text.length\n const startTime = Date.now()\n\n aiEventClient.emit('summarize:request:started', {\n requestId,\n provider: adapter.name,\n model,\n inputLength,\n timestamp: startTime,\n })\n\n const summarizeOptions: SummarizationOptions = {\n model,\n text,\n maxLength,\n style,\n focus,\n }\n\n const result = await adapter.summarize(summarizeOptions)\n\n const duration = Date.now() - startTime\n const outputLength = result.summary.length\n\n aiEventClient.emit('summarize:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n inputLength,\n outputLength,\n duration,\n timestamp: Date.now(),\n })\n\n return result\n}\n\n/**\n * Run streaming summarization\n * Uses the adapter's native streaming if available, otherwise falls back\n * to non-streaming and yields the result as a single chunk.\n */\nasync function* runStreamingSummarize(\n options: SummarizeActivityOptions<SummarizeAdapter<string, object>, true>,\n): AsyncIterable<StreamChunk> {\n const { adapter, text, maxLength, style, focus } = options\n const model = adapter.model\n\n const summarizeOptions: SummarizationOptions = {\n model,\n text,\n maxLength,\n style,\n focus,\n }\n\n // Use real streaming if the adapter supports it\n if (adapter.summarizeStream) {\n yield* adapter.summarizeStream(summarizeOptions)\n return\n }\n\n // Fall back to non-streaming — wrap result with streamGenerationResult\n yield* streamGenerationResult(() => adapter.summarize(summarizeOptions))\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the summarize() function without executing.\n */\nexport function createSummarizeOptions<\n TAdapter extends SummarizeAdapter<string, object>,\n TStream extends boolean = false,\n>(\n options: SummarizeActivityOptions<TAdapter, TStream>,\n): SummarizeActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n SummarizeAdapter,\n SummarizeAdapterConfig,\n AnySummarizeAdapter,\n} from './adapter'\nexport { BaseSummarizeAdapter } from './adapter'\n"],"names":[],"mappings":";;AAqBO,MAAM,OAAO;AAmEpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AAwDO,SAAS,UAId,SACkC;AAClC,QAAM,EAAE,WAAW;AAEnB,MAAI,QAAQ;AACV,WAAO;AAAA,MACL;AAAA,IAAA;AAAA,EAKJ;AAEA,SAAO;AAAA,IACL;AAAA,EAAA;AAKJ;AAKA,eAAe,aACb,SAC8B;AAC9B,QAAM,EAAE,SAAS,MAAM,WAAW,OAAO,UAAU;AACnD,QAAM,QAAQ,QAAQ;AACtB,QAAM,YAAY,SAAS,WAAW;AACtC,QAAM,cAAc,KAAK;AACzB,QAAM,YAAY,KAAK,IAAA;AAEvB,gBAAc,KAAK,6BAA6B;AAAA,IAC9C;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB;AAAA,IACA;AAAA,IACA,WAAW;AAAA,EAAA,CACZ;AAED,QAAM,mBAAyC;AAAA,IAC7C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,QAAM,SAAS,MAAM,QAAQ,UAAU,gBAAgB;AAEvD,QAAM,WAAW,KAAK,IAAA,IAAQ;AAC9B,QAAM,eAAe,OAAO,QAAQ;AAEpC,gBAAc,KAAK,+BAA+B;AAAA,IAChD;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,KAAK,IAAA;AAAA,EAAI,CACrB;AAED,SAAO;AACT;AAOA,gBAAgB,sBACd,SAC4B;AAC5B,QAAM,EAAE,SAAS,MAAM,WAAW,OAAO,UAAU;AACnD,QAAM,QAAQ,QAAQ;AAEtB,QAAM,mBAAyC;AAAA,IAC7C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAIF,MAAI,QAAQ,iBAAiB;AAC3B,WAAO,QAAQ,gBAAgB,gBAAgB;AAC/C;AAAA,EACF;AAGA,SAAO,uBAAuB,MAAM,QAAQ,UAAU,gBAAgB,CAAC;AACzE;AASO,SAAS,uBAId,SAC6C;AAC7C,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/activities/summarize/index.ts"],"sourcesContent":["/**\n * Summarize Activity\n *\n * Generates summaries from text input.\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 { SummarizeAdapter } from './adapter'\nimport type {\n StreamChunk,\n SummarizationOptions,\n SummarizationResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'summarize' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/** Extract provider options from a SummarizeAdapter via ~types */\nexport type SummarizeProviderOptions<TAdapter> =\n TAdapter extends SummarizeAdapter<any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the summarize activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The summarize adapter type\n * @template TStream - Whether to stream the output\n */\nexport interface SummarizeActivityOptions<\n TAdapter extends SummarizeAdapter<string, object>,\n TStream extends boolean = false,\n> {\n /** The summarize adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The text to summarize */\n text: string\n /** Maximum length of the summary (in words or characters, provider-dependent) */\n maxLength?: number\n /** Style of summary to generate */\n style?: 'bullet-points' | 'paragraph' | 'concise'\n /** Topics or aspects to focus on in the summary */\n focus?: Array<string>\n /** Provider-specific options */\n modelOptions?: SummarizeProviderOptions<TAdapter>\n /**\n * Whether to stream the summarization result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming output.\n * When false or not provided, returns a Promise<SummarizationResult>.\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 summarize activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<SummarizationResult>\n */\nexport type SummarizeActivityResult<TStream extends boolean> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<SummarizationResult>\n\n// ===========================\n// Helper Functions\n// ===========================\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 * Summarize activity - generates summaries from text.\n *\n * Supports both streaming and non-streaming modes.\n *\n * @example Basic summarization\n * ```ts\n * import { summarize } from '@tanstack/ai'\n * import { openaiSummarize } from '@tanstack/ai-openai'\n *\n * const result = await summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long article text here...'\n * })\n *\n * console.log(result.summary)\n * ```\n *\n * @example Summarization with style\n * ```ts\n * const result = await summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long article text here...',\n * style: 'bullet-points',\n * maxLength: 100\n * })\n * ```\n *\n * @example Focused summarization\n * ```ts\n * const result = await summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long technical document...',\n * focus: ['key findings', 'methodology']\n * })\n * ```\n *\n * @example Streaming summarization\n * ```ts\n * for await (const chunk of summarize({\n * adapter: openaiSummarize('gpt-4o-mini'),\n * text: 'Long article text here...',\n * stream: true\n * })) {\n * if (chunk.type === 'content') {\n * process.stdout.write(chunk.delta)\n * }\n * }\n * ```\n */\nexport function summarize<\n TAdapter extends SummarizeAdapter<string, object>,\n TStream extends boolean = false,\n>(\n options: SummarizeActivityOptions<TAdapter, TStream>,\n): SummarizeActivityResult<TStream> {\n const { stream } = options\n\n if (stream) {\n return runStreamingSummarize(\n options as unknown as SummarizeActivityOptions<\n SummarizeAdapter<string, object>,\n true\n >,\n ) as SummarizeActivityResult<TStream>\n }\n\n return runSummarize(\n options as unknown as SummarizeActivityOptions<\n SummarizeAdapter<string, object>,\n false\n >,\n ) as SummarizeActivityResult<TStream>\n}\n\n/**\n * Run non-streaming summarization\n */\nasync function runSummarize(\n options: SummarizeActivityOptions<SummarizeAdapter<string, object>, false>,\n): Promise<SummarizationResult> {\n const { adapter, text, maxLength, style, focus } = options\n const model = adapter.model\n const requestId = createId('summarize')\n const inputLength = text.length\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n\n aiEventClient.emit('summarize:request:started', {\n requestId,\n provider: adapter.name,\n model,\n inputLength,\n timestamp: startTime,\n })\n\n logger.request(`activity=summarize provider=${adapter.name}`, {\n provider: adapter.name,\n model,\n inputLength,\n })\n\n const summarizeOptions: SummarizationOptions = {\n model,\n text,\n maxLength,\n style,\n focus,\n logger,\n }\n\n try {\n const result = await adapter.summarize(summarizeOptions)\n\n const duration = Date.now() - startTime\n const outputLength = result.summary.length\n\n aiEventClient.emit('summarize:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n inputLength,\n outputLength,\n duration,\n timestamp: Date.now(),\n })\n\n logger.output(`activity=summarize length=${outputLength}`, {\n hasSummary: !!result.summary,\n outputLength,\n })\n\n return result\n } catch (error) {\n logger.errors('summarize activity failed', {\n error,\n source: 'summarize',\n })\n throw error\n }\n}\n\n/**\n * Run streaming summarization\n * Uses the adapter's native streaming if available, otherwise falls back\n * to non-streaming and yields the result as a single chunk.\n */\nasync function* runStreamingSummarize(\n options: SummarizeActivityOptions<SummarizeAdapter<string, object>, true>,\n): AsyncIterable<StreamChunk> {\n const { adapter, text, maxLength, style, focus } = options\n const model = adapter.model\n const logger: InternalLogger = resolveDebugOption(options.debug)\n\n logger.request(`activity=summarize provider=${adapter.name}`, {\n provider: adapter.name,\n model,\n stream: true,\n })\n\n const summarizeOptions: SummarizationOptions = {\n model,\n text,\n maxLength,\n style,\n focus,\n logger,\n }\n\n try {\n // Use real streaming if the adapter supports it\n if (adapter.summarizeStream) {\n yield* adapter.summarizeStream(summarizeOptions)\n return\n }\n\n // Fall back to non-streaming — wrap result with streamGenerationResult\n yield* streamGenerationResult(() => adapter.summarize(summarizeOptions))\n } catch (error) {\n logger.errors('summarize activity failed', {\n error,\n source: 'summarize',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the summarize() function without executing.\n */\nexport function createSummarizeOptions<\n TAdapter extends SummarizeAdapter<string, object>,\n TStream extends boolean = false,\n>(\n options: SummarizeActivityOptions<TAdapter, TStream>,\n): SummarizeActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n SummarizeAdapter,\n SummarizeAdapterConfig,\n AnySummarizeAdapter,\n} from './adapter'\nexport { BaseSummarizeAdapter } from './adapter'\n"],"names":[],"mappings":";;;AAwBO,MAAM,OAAO;AAyEpB,SAAS,SAAS,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AAED,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO,OAAO,6BAA6B;AAAA,MACzC;AAAA,MACA,QAAQ;AAAA,IAAA,CACT;AACD,UAAM;AAAA,EACR;AACF;AAOA,gBAAgB,sBACd,SAC4B;AAC5B,QAAM,EAAE,SAAS,MAAM,WAAW,OAAO,UAAU;AACnD,QAAM,QAAQ,QAAQ;AACtB,QAAM,SAAyB,mBAAmB,QAAQ,KAAK;AAE/D,SAAO,QAAQ,+BAA+B,QAAQ,IAAI,IAAI;AAAA,IAC5D,UAAU,QAAQ;AAAA,IAClB;AAAA,IACA,QAAQ;AAAA,EAAA,CACT;AAED,QAAM,mBAAyC;AAAA,IAC7C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,MAAI;AAEF,QAAI,QAAQ,iBAAiB;AAC3B,aAAO,QAAQ,gBAAgB,gBAAgB;AAC/C;AAAA,IACF;AAGA,WAAO,uBAAuB,MAAM,QAAQ,UAAU,gBAAgB,CAAC;AAAA,EACzE,SAAS,OAAO;AACd,WAAO,OAAO,6BAA6B;AAAA,MACzC;AAAA,MACA,QAAQ;AAAA,IAAA,CACT;AACD,UAAM;AAAA,EACR;AACF;AASO,SAAS,uBAId,SAC6C;AAC7C,SAAO;AACT;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter-internals.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -23,3 +23,5 @@ export { StreamProcessor, createReplayStream, ImmediateStrategy, PunctuationStra
|
|
|
23
23
|
export type { ChunkStrategy, ChunkRecording, InternalToolCallState, ProcessorResult, ProcessorState, StreamProcessorEvents, StreamProcessorOptions, ToolCallState, ToolResultState, JSONParser, } from './activities/chat/stream/index.js';
|
|
24
24
|
export { createModel, extendAdapter } from './extend-adapter.js';
|
|
25
25
|
export type { ExtendedModelDef } from './extend-adapter.js';
|
|
26
|
+
export type { Logger, DebugCategories, DebugConfig, DebugOption, } from './logger/types.js';
|
|
27
|
+
export { ConsoleLogger } from './logger/console-logger.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -14,6 +14,7 @@ import { detectImageMimeType } from "./utils.js";
|
|
|
14
14
|
import { realtimeToken } from "./realtime/index.js";
|
|
15
15
|
import { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages } from "./activities/chat/messages.js";
|
|
16
16
|
import { createModel, extendAdapter } from "./extend-adapter.js";
|
|
17
|
+
import { ConsoleLogger } from "./logger/console-logger.js";
|
|
17
18
|
import { StreamProcessor, createReplayStream } from "./activities/chat/stream/processor.js";
|
|
18
19
|
import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PunctuationStrategy, WordBoundaryStrategy } from "./activities/chat/stream/strategies.js";
|
|
19
20
|
import { PartialJSONParser, defaultJSONParser, parsePartialJSON } from "./activities/chat/stream/json-parser.js";
|
|
@@ -21,6 +22,7 @@ import { EventType } from "@ag-ui/core";
|
|
|
21
22
|
export {
|
|
22
23
|
BatchStrategy,
|
|
23
24
|
CompositeStrategy,
|
|
25
|
+
ConsoleLogger,
|
|
24
26
|
EventType,
|
|
25
27
|
ImmediateStrategy,
|
|
26
28
|
PartialJSONParser,
|
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":";;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Logger } from './types.js';
|
|
2
|
+
export declare class ConsoleLogger implements Logger {
|
|
3
|
+
/** Log a debug-level message; forwards to `console.debug`. */
|
|
4
|
+
debug(message: string, meta?: Record<string, unknown>): void;
|
|
5
|
+
/** Log an info-level message; forwards to `console.info`. */
|
|
6
|
+
info(message: string, meta?: Record<string, unknown>): void;
|
|
7
|
+
/** Log a warning-level message; forwards to `console.warn`. */
|
|
8
|
+
warn(message: string, meta?: Record<string, unknown>): void;
|
|
9
|
+
/** Log an error-level message; forwards to `console.error`. */
|
|
10
|
+
error(message: string, meta?: Record<string, unknown>): void;
|
|
11
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const DIR_OPTIONS = { depth: null, colors: true };
|
|
2
|
+
class ConsoleLogger {
|
|
3
|
+
/** Log a debug-level message; forwards to `console.debug`. */
|
|
4
|
+
debug(message, meta) {
|
|
5
|
+
console.debug(message);
|
|
6
|
+
if (meta !== void 0) console.dir(meta, DIR_OPTIONS);
|
|
7
|
+
}
|
|
8
|
+
/** Log an info-level message; forwards to `console.info`. */
|
|
9
|
+
info(message, meta) {
|
|
10
|
+
console.info(message);
|
|
11
|
+
if (meta !== void 0) console.dir(meta, DIR_OPTIONS);
|
|
12
|
+
}
|
|
13
|
+
/** Log a warning-level message; forwards to `console.warn`. */
|
|
14
|
+
warn(message, meta) {
|
|
15
|
+
console.warn(message);
|
|
16
|
+
if (meta !== void 0) console.dir(meta, DIR_OPTIONS);
|
|
17
|
+
}
|
|
18
|
+
/** Log an error-level message; forwards to `console.error`. */
|
|
19
|
+
error(message, meta) {
|
|
20
|
+
console.error(message);
|
|
21
|
+
if (meta !== void 0) console.dir(meta, DIR_OPTIONS);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export {
|
|
25
|
+
ConsoleLogger
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=console-logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"console-logger.js","sources":["../../../src/logger/console-logger.ts"],"sourcesContent":["import type { Logger } from './types'\n\n/**\n * Default `Logger` implementation that routes each level to the matching\n * `console` method:\n *\n * - `debug` → `console.debug`\n * - `info` → `console.info`\n * - `warn` → `console.warn`\n * - `error` → `console.error`\n *\n * When a `meta` object is supplied, the message is logged first and the meta\n * object is then printed via `console.dir(meta, { depth: null, colors: true })`\n * so deeply nested structures (e.g. provider chunk payloads with `usage`,\n * `output`, `reasoning`, `tools`) render in full instead of truncating to\n * `[Object]` / `[Array]`. On Node this produces a depth-unlimited inspect\n * dump; browsers present the object as an interactive tree (extra options\n * are ignored).\n *\n * This is the logger used when `debug` is enabled on any activity and no\n * custom `logger` is supplied via `debug: { logger }`.\n */\nconst DIR_OPTIONS = { depth: null, colors: true } as const\n\nexport class ConsoleLogger implements Logger {\n /** Log a debug-level message; forwards to `console.debug`. */\n debug(message: string, meta?: Record<string, unknown>): void {\n console.debug(message)\n if (meta !== undefined) console.dir(meta, DIR_OPTIONS)\n }\n\n /** Log an info-level message; forwards to `console.info`. */\n info(message: string, meta?: Record<string, unknown>): void {\n console.info(message)\n if (meta !== undefined) console.dir(meta, DIR_OPTIONS)\n }\n\n /** Log a warning-level message; forwards to `console.warn`. */\n warn(message: string, meta?: Record<string, unknown>): void {\n console.warn(message)\n if (meta !== undefined) console.dir(meta, DIR_OPTIONS)\n }\n\n /** Log an error-level message; forwards to `console.error`. */\n error(message: string, meta?: Record<string, unknown>): void {\n console.error(message)\n if (meta !== undefined) console.dir(meta, DIR_OPTIONS)\n }\n}\n"],"names":[],"mappings":"AAsBA,MAAM,cAAc,EAAE,OAAO,MAAM,QAAQ,KAAA;AAEpC,MAAM,cAAgC;AAAA;AAAA,EAE3C,MAAM,SAAiB,MAAsC;AAC3D,YAAQ,MAAM,OAAO;AACrB,QAAI,SAAS,OAAW,SAAQ,IAAI,MAAM,WAAW;AAAA,EACvD;AAAA;AAAA,EAGA,KAAK,SAAiB,MAAsC;AAC1D,YAAQ,KAAK,OAAO;AACpB,QAAI,SAAS,OAAW,SAAQ,IAAI,MAAM,WAAW;AAAA,EACvD;AAAA;AAAA,EAGA,KAAK,SAAiB,MAAsC;AAC1D,YAAQ,KAAK,OAAO;AACpB,QAAI,SAAS,OAAW,SAAQ,IAAI,MAAM,WAAW;AAAA,EACvD;AAAA;AAAA,EAGA,MAAM,SAAiB,MAAsC;AAC3D,YAAQ,MAAM,OAAO;AACrB,QAAI,SAAS,OAAW,SAAQ,IAAI,MAAM,WAAW;AAAA,EACvD;AACF;"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { DebugCategories, Logger } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Fully-resolved categories map. Every flag is a definite boolean (never
|
|
4
|
+
* undefined), produced by `resolveDebugOption` from a `DebugOption`.
|
|
5
|
+
*/
|
|
6
|
+
export type ResolvedCategories = Required<DebugCategories>;
|
|
7
|
+
export declare class InternalLogger {
|
|
8
|
+
private readonly logger;
|
|
9
|
+
private readonly categories;
|
|
10
|
+
constructor(logger: Logger, categories: ResolvedCategories);
|
|
11
|
+
/** Whether a category is enabled. Cheap, safe to call on hot paths. */
|
|
12
|
+
isEnabled(category: keyof ResolvedCategories): boolean;
|
|
13
|
+
private emit;
|
|
14
|
+
/** Log a raw chunk/frame received from a provider SDK. */
|
|
15
|
+
provider(message: string, meta?: Record<string, unknown>): void;
|
|
16
|
+
/** Log a chunk/result yielded to the consumer after middleware. */
|
|
17
|
+
output(message: string, meta?: Record<string, unknown>): void;
|
|
18
|
+
/** Log inputs/outputs around a middleware hook invocation. Chat-only. */
|
|
19
|
+
middleware(message: string, meta?: Record<string, unknown>): void;
|
|
20
|
+
/** Log before/after a tool-call execution. Chat-only. */
|
|
21
|
+
tools(message: string, meta?: Record<string, unknown>): void;
|
|
22
|
+
/** Log an agent-loop iteration marker or phase transition. Chat-only. */
|
|
23
|
+
agentLoop(message: string, meta?: Record<string, unknown>): void;
|
|
24
|
+
/** Log a config transform returned by a middleware `onConfig` hook. Chat-only. */
|
|
25
|
+
config(message: string, meta?: Record<string, unknown>): void;
|
|
26
|
+
/**
|
|
27
|
+
* Log a caught error. Defaults to on even when `debug` is unspecified.
|
|
28
|
+
* Uses the underlying logger's `error` level.
|
|
29
|
+
*/
|
|
30
|
+
errors(message: string, meta?: Record<string, unknown>): void;
|
|
31
|
+
/** Log outgoing request metadata before an adapter SDK call. */
|
|
32
|
+
request(message: string, meta?: Record<string, unknown>): void;
|
|
33
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
const CATEGORY_EMOJI = {
|
|
2
|
+
request: "📤",
|
|
3
|
+
provider: "📥",
|
|
4
|
+
output: "📨",
|
|
5
|
+
middleware: "🧩",
|
|
6
|
+
tools: "🔧",
|
|
7
|
+
agentLoop: "🔁",
|
|
8
|
+
config: "⚙️",
|
|
9
|
+
errors: "❌"
|
|
10
|
+
};
|
|
11
|
+
class InternalLogger {
|
|
12
|
+
constructor(logger, categories) {
|
|
13
|
+
this.logger = logger;
|
|
14
|
+
this.categories = categories;
|
|
15
|
+
}
|
|
16
|
+
/** Whether a category is enabled. Cheap, safe to call on hot paths. */
|
|
17
|
+
isEnabled(category) {
|
|
18
|
+
return this.categories[category];
|
|
19
|
+
}
|
|
20
|
+
emit(level, category, message, meta) {
|
|
21
|
+
if (!this.categories[category]) return;
|
|
22
|
+
const emoji = CATEGORY_EMOJI[category];
|
|
23
|
+
const prefixed = `${emoji} [tanstack-ai:${category}] ${emoji} ${message}`;
|
|
24
|
+
try {
|
|
25
|
+
if (level === "error") this.logger.error(prefixed, meta);
|
|
26
|
+
else this.logger.debug(prefixed, meta);
|
|
27
|
+
} catch {
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Log a raw chunk/frame received from a provider SDK. */
|
|
31
|
+
provider(message, meta) {
|
|
32
|
+
this.emit("debug", "provider", message, meta);
|
|
33
|
+
}
|
|
34
|
+
/** Log a chunk/result yielded to the consumer after middleware. */
|
|
35
|
+
output(message, meta) {
|
|
36
|
+
this.emit("debug", "output", message, meta);
|
|
37
|
+
}
|
|
38
|
+
/** Log inputs/outputs around a middleware hook invocation. Chat-only. */
|
|
39
|
+
middleware(message, meta) {
|
|
40
|
+
this.emit("debug", "middleware", message, meta);
|
|
41
|
+
}
|
|
42
|
+
/** Log before/after a tool-call execution. Chat-only. */
|
|
43
|
+
tools(message, meta) {
|
|
44
|
+
this.emit("debug", "tools", message, meta);
|
|
45
|
+
}
|
|
46
|
+
/** Log an agent-loop iteration marker or phase transition. Chat-only. */
|
|
47
|
+
agentLoop(message, meta) {
|
|
48
|
+
this.emit("debug", "agentLoop", message, meta);
|
|
49
|
+
}
|
|
50
|
+
/** Log a config transform returned by a middleware `onConfig` hook. Chat-only. */
|
|
51
|
+
config(message, meta) {
|
|
52
|
+
this.emit("debug", "config", message, meta);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Log a caught error. Defaults to on even when `debug` is unspecified.
|
|
56
|
+
* Uses the underlying logger's `error` level.
|
|
57
|
+
*/
|
|
58
|
+
errors(message, meta) {
|
|
59
|
+
this.emit("error", "errors", message, meta);
|
|
60
|
+
}
|
|
61
|
+
/** Log outgoing request metadata before an adapter SDK call. */
|
|
62
|
+
request(message, meta) {
|
|
63
|
+
this.emit("debug", "request", message, meta);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export {
|
|
67
|
+
InternalLogger
|
|
68
|
+
};
|
|
69
|
+
//# sourceMappingURL=internal-logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-logger.js","sources":["../../../src/logger/internal-logger.ts"],"sourcesContent":["import type { DebugCategories, Logger } from './types'\n\n/**\n * Fully-resolved categories map. Every flag is a definite boolean (never\n * undefined), produced by `resolveDebugOption` from a `DebugOption`.\n */\nexport type ResolvedCategories = Required<DebugCategories>\n\n/**\n * Package-internal logger wrapper used by every activity and adapter in\n * `@tanstack/ai`. Wraps a user-supplied (or default `ConsoleLogger`) `Logger`\n * plus a fully-resolved per-category map. Each category has a dedicated\n * method that no-ops when its flag is `false`, or prepends a\n * `[tanstack-ai:<category>] ` prefix and calls the underlying logger's\n * `error` (for the `errors` category) or `debug` (for everything else).\n *\n * Not exported from the package root. Adapter packages consume it via the\n * `@tanstack/ai/adapter-internals` subpath export.\n */\n/**\n * Emoji marker per category — bracketing the `[tanstack-ai:<cat>]` tag on\n * both sides makes it trivial to visually pick out a category when scanning\n * dense streaming logs.\n */\nconst CATEGORY_EMOJI: Record<keyof ResolvedCategories, string> = {\n request: '📤',\n provider: '📥',\n output: '📨',\n middleware: '🧩',\n tools: '🔧',\n agentLoop: '🔁',\n config: '⚙️',\n errors: '❌',\n}\n\nexport class InternalLogger {\n constructor(\n private readonly logger: Logger,\n private readonly categories: ResolvedCategories,\n ) {}\n\n /** Whether a category is enabled. Cheap, safe to call on hot paths. */\n isEnabled(category: keyof ResolvedCategories): boolean {\n return this.categories[category]\n }\n\n private emit(\n level: 'debug' | 'error',\n category: keyof ResolvedCategories,\n message: string,\n meta?: Record<string, unknown>,\n ): void {\n if (!this.categories[category]) return\n const emoji = CATEGORY_EMOJI[category]\n const prefixed = `${emoji} [tanstack-ai:${category}] ${emoji} ${message}`\n try {\n if (level === 'error') this.logger.error(prefixed, meta)\n else this.logger.debug(prefixed, meta)\n } catch {\n // User-supplied logger threw; swallow so we never mask the original\n // error that triggered this log call.\n }\n }\n\n /** Log a raw chunk/frame received from a provider SDK. */\n provider(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'provider', message, meta)\n }\n\n /** Log a chunk/result yielded to the consumer after middleware. */\n output(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'output', message, meta)\n }\n\n /** Log inputs/outputs around a middleware hook invocation. Chat-only. */\n middleware(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'middleware', message, meta)\n }\n\n /** Log before/after a tool-call execution. Chat-only. */\n tools(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'tools', message, meta)\n }\n\n /** Log an agent-loop iteration marker or phase transition. Chat-only. */\n agentLoop(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'agentLoop', message, meta)\n }\n\n /** Log a config transform returned by a middleware `onConfig` hook. Chat-only. */\n config(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'config', message, meta)\n }\n\n /**\n * Log a caught error. Defaults to on even when `debug` is unspecified.\n * Uses the underlying logger's `error` level.\n */\n errors(message: string, meta?: Record<string, unknown>): void {\n this.emit('error', 'errors', message, meta)\n }\n\n /** Log outgoing request metadata before an adapter SDK call. */\n request(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'request', message, meta)\n }\n}\n"],"names":[],"mappings":"AAwBA,MAAM,iBAA2D;AAAA,EAC/D,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AACV;AAEO,MAAM,eAAe;AAAA,EAC1B,YACmB,QACA,YACjB;AAFiB,SAAA,SAAA;AACA,SAAA,aAAA;AAAA,EAChB;AAAA;AAAA,EAGH,UAAU,UAA6C;AACrD,WAAO,KAAK,WAAW,QAAQ;AAAA,EACjC;AAAA,EAEQ,KACN,OACA,UACA,SACA,MACM;AACN,QAAI,CAAC,KAAK,WAAW,QAAQ,EAAG;AAChC,UAAM,QAAQ,eAAe,QAAQ;AACrC,UAAM,WAAW,GAAG,KAAK,iBAAiB,QAAQ,KAAK,KAAK,IAAI,OAAO;AACvE,QAAI;AACF,UAAI,UAAU,QAAS,MAAK,OAAO,MAAM,UAAU,IAAI;AAAA,UAClD,MAAK,OAAO,MAAM,UAAU,IAAI;AAAA,IACvC,QAAQ;AAAA,IAGR;AAAA,EACF;AAAA;AAAA,EAGA,SAAS,SAAiB,MAAsC;AAC9D,SAAK,KAAK,SAAS,YAAY,SAAS,IAAI;AAAA,EAC9C;AAAA;AAAA,EAGA,OAAO,SAAiB,MAAsC;AAC5D,SAAK,KAAK,SAAS,UAAU,SAAS,IAAI;AAAA,EAC5C;AAAA;AAAA,EAGA,WAAW,SAAiB,MAAsC;AAChE,SAAK,KAAK,SAAS,cAAc,SAAS,IAAI;AAAA,EAChD;AAAA;AAAA,EAGA,MAAM,SAAiB,MAAsC;AAC3D,SAAK,KAAK,SAAS,SAAS,SAAS,IAAI;AAAA,EAC3C;AAAA;AAAA,EAGA,UAAU,SAAiB,MAAsC;AAC/D,SAAK,KAAK,SAAS,aAAa,SAAS,IAAI;AAAA,EAC/C;AAAA;AAAA,EAGA,OAAO,SAAiB,MAAsC;AAC5D,SAAK,KAAK,SAAS,UAAU,SAAS,IAAI;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,SAAiB,MAAsC;AAC5D,SAAK,KAAK,SAAS,UAAU,SAAS,IAAI;AAAA,EAC5C;AAAA;AAAA,EAGA,QAAQ,SAAiB,MAAsC;AAC7D,SAAK,KAAK,SAAS,WAAW,SAAS,IAAI;AAAA,EAC7C;AACF;"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { InternalLogger } from './internal-logger.js';
|
|
2
|
+
import { DebugOption } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Normalize a `DebugOption` into an `InternalLogger` ready to be threaded
|
|
5
|
+
* through the library's activities and adapters. See the `DebugOption`
|
|
6
|
+
* resolution table in the spec for the complete rules.
|
|
7
|
+
*
|
|
8
|
+
* - `undefined`: only the `errors` category is enabled; default `ConsoleLogger`.
|
|
9
|
+
* - `true`: all categories enabled; default `ConsoleLogger`.
|
|
10
|
+
* - `false`: all categories disabled (including `errors`); default `ConsoleLogger`.
|
|
11
|
+
* - `DebugConfig`: each unspecified category defaults to `true`; an optional
|
|
12
|
+
* `logger` replaces the default `ConsoleLogger`.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveDebugOption(debug: DebugOption | undefined): InternalLogger;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { ConsoleLogger } from "./console-logger.js";
|
|
2
|
+
import { InternalLogger } from "./internal-logger.js";
|
|
3
|
+
const ALL_OFF = {
|
|
4
|
+
provider: false,
|
|
5
|
+
output: false,
|
|
6
|
+
middleware: false,
|
|
7
|
+
tools: false,
|
|
8
|
+
agentLoop: false,
|
|
9
|
+
config: false,
|
|
10
|
+
errors: false,
|
|
11
|
+
request: false
|
|
12
|
+
};
|
|
13
|
+
const ALL_ON = {
|
|
14
|
+
provider: true,
|
|
15
|
+
output: true,
|
|
16
|
+
middleware: true,
|
|
17
|
+
tools: true,
|
|
18
|
+
agentLoop: true,
|
|
19
|
+
config: true,
|
|
20
|
+
errors: true,
|
|
21
|
+
request: true
|
|
22
|
+
};
|
|
23
|
+
const errorsOnlyCategories = () => ({
|
|
24
|
+
...ALL_OFF,
|
|
25
|
+
errors: true
|
|
26
|
+
});
|
|
27
|
+
const resolveCategoriesFromPartial = (partial) => ({
|
|
28
|
+
provider: partial.provider ?? true,
|
|
29
|
+
output: partial.output ?? true,
|
|
30
|
+
middleware: partial.middleware ?? true,
|
|
31
|
+
tools: partial.tools ?? true,
|
|
32
|
+
agentLoop: partial.agentLoop ?? true,
|
|
33
|
+
config: partial.config ?? true,
|
|
34
|
+
errors: partial.errors ?? true,
|
|
35
|
+
request: partial.request ?? true
|
|
36
|
+
});
|
|
37
|
+
function resolveDebugOption(debug) {
|
|
38
|
+
if (debug === void 0) {
|
|
39
|
+
return new InternalLogger(new ConsoleLogger(), errorsOnlyCategories());
|
|
40
|
+
}
|
|
41
|
+
if (debug === true) {
|
|
42
|
+
return new InternalLogger(new ConsoleLogger(), ALL_ON);
|
|
43
|
+
}
|
|
44
|
+
if (debug === false) {
|
|
45
|
+
return new InternalLogger(new ConsoleLogger(), ALL_OFF);
|
|
46
|
+
}
|
|
47
|
+
const { logger, ...cats } = debug;
|
|
48
|
+
const userLogger = logger ?? new ConsoleLogger();
|
|
49
|
+
return new InternalLogger(userLogger, resolveCategoriesFromPartial(cats));
|
|
50
|
+
}
|
|
51
|
+
export {
|
|
52
|
+
resolveDebugOption
|
|
53
|
+
};
|
|
54
|
+
//# sourceMappingURL=resolve.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve.js","sources":["../../../src/logger/resolve.ts"],"sourcesContent":["import { ConsoleLogger } from './console-logger'\nimport { InternalLogger } from './internal-logger'\nimport type { ResolvedCategories } from './internal-logger'\nimport type { DebugCategories, DebugConfig, DebugOption, Logger } from './types'\n\nconst ALL_OFF: ResolvedCategories = {\n provider: false,\n output: false,\n middleware: false,\n tools: false,\n agentLoop: false,\n config: false,\n errors: false,\n request: false,\n}\n\nconst ALL_ON: ResolvedCategories = {\n provider: true,\n output: true,\n middleware: true,\n tools: true,\n agentLoop: true,\n config: true,\n errors: true,\n request: true,\n}\n\nconst errorsOnlyCategories = (): ResolvedCategories => ({\n ...ALL_OFF,\n errors: true,\n})\n\nconst resolveCategoriesFromPartial = (\n partial: DebugCategories,\n): ResolvedCategories => ({\n provider: partial.provider ?? true,\n output: partial.output ?? true,\n middleware: partial.middleware ?? true,\n tools: partial.tools ?? true,\n agentLoop: partial.agentLoop ?? true,\n config: partial.config ?? true,\n errors: partial.errors ?? true,\n request: partial.request ?? true,\n})\n\n/**\n * Normalize a `DebugOption` into an `InternalLogger` ready to be threaded\n * through the library's activities and adapters. See the `DebugOption`\n * resolution table in the spec for the complete rules.\n *\n * - `undefined`: only the `errors` category is enabled; default `ConsoleLogger`.\n * - `true`: all categories enabled; default `ConsoleLogger`.\n * - `false`: all categories disabled (including `errors`); default `ConsoleLogger`.\n * - `DebugConfig`: each unspecified category defaults to `true`; an optional\n * `logger` replaces the default `ConsoleLogger`.\n */\nexport function resolveDebugOption(\n debug: DebugOption | undefined,\n): InternalLogger {\n if (debug === undefined) {\n return new InternalLogger(new ConsoleLogger(), errorsOnlyCategories())\n }\n if (debug === true) {\n return new InternalLogger(new ConsoleLogger(), ALL_ON)\n }\n if (debug === false) {\n return new InternalLogger(new ConsoleLogger(), ALL_OFF)\n }\n const { logger, ...cats }: DebugConfig = debug\n const userLogger: Logger = logger ?? new ConsoleLogger()\n return new InternalLogger(userLogger, resolveCategoriesFromPartial(cats))\n}\n"],"names":[],"mappings":";;AAKA,MAAM,UAA8B;AAAA,EAClC,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACX;AAEA,MAAM,SAA6B;AAAA,EACjC,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACX;AAEA,MAAM,uBAAuB,OAA2B;AAAA,EACtD,GAAG;AAAA,EACH,QAAQ;AACV;AAEA,MAAM,+BAA+B,CACnC,aACwB;AAAA,EACxB,UAAU,QAAQ,YAAY;AAAA,EAC9B,QAAQ,QAAQ,UAAU;AAAA,EAC1B,YAAY,QAAQ,cAAc;AAAA,EAClC,OAAO,QAAQ,SAAS;AAAA,EACxB,WAAW,QAAQ,aAAa;AAAA,EAChC,QAAQ,QAAQ,UAAU;AAAA,EAC1B,QAAQ,QAAQ,UAAU;AAAA,EAC1B,SAAS,QAAQ,WAAW;AAC9B;AAaO,SAAS,mBACd,OACgB;AAChB,MAAI,UAAU,QAAW;AACvB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,sBAAsB;AAAA,EACvE;AACA,MAAI,UAAU,MAAM;AAClB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,MAAM;AAAA,EACvD;AACA,MAAI,UAAU,OAAO;AACnB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,OAAO;AAAA,EACxD;AACA,QAAM,EAAE,QAAQ,GAAG,KAAA,IAAsB;AACzC,QAAM,aAAqB,UAAU,IAAI,cAAA;AACzC,SAAO,IAAI,eAAe,YAAY,6BAA6B,IAAI,CAAC;AAC1E;"}
|