@juspay/neurolink 9.65.2 → 9.67.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.
Files changed (89) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +12 -12
  3. package/dist/avatar/index.d.ts +13 -0
  4. package/dist/avatar/index.js +72 -0
  5. package/dist/browser/neurolink.min.js +355 -347
  6. package/dist/cli/commands/proxy.js +154 -5
  7. package/dist/core/baseProvider.js +49 -8
  8. package/dist/factories/providerRegistry.js +23 -0
  9. package/dist/index.d.ts +10 -1
  10. package/dist/index.js +36 -1
  11. package/dist/lib/avatar/index.d.ts +13 -0
  12. package/dist/lib/avatar/index.js +72 -0
  13. package/dist/lib/core/baseProvider.js +49 -8
  14. package/dist/lib/factories/providerRegistry.js +23 -0
  15. package/dist/lib/files/fileTools.d.ts +1 -1
  16. package/dist/lib/index.d.ts +10 -1
  17. package/dist/lib/index.js +36 -1
  18. package/dist/lib/music/index.d.ts +14 -0
  19. package/dist/lib/music/index.js +80 -0
  20. package/dist/lib/proxy/modelRouter.d.ts +5 -1
  21. package/dist/lib/proxy/modelRouter.js +8 -0
  22. package/dist/lib/proxy/openaiFormat.d.ts +137 -0
  23. package/dist/lib/proxy/openaiFormat.js +801 -0
  24. package/dist/lib/proxy/proxyTranslationEngine.d.ts +124 -0
  25. package/dist/lib/proxy/proxyTranslationEngine.js +679 -0
  26. package/dist/lib/server/routes/claudeProxyRoutes.d.ts +6 -5
  27. package/dist/lib/server/routes/claudeProxyRoutes.js +22 -355
  28. package/dist/lib/server/routes/index.d.ts +1 -0
  29. package/dist/lib/server/routes/index.js +10 -2
  30. package/dist/lib/server/routes/openaiProxyRoutes.d.ts +30 -0
  31. package/dist/lib/server/routes/openaiProxyRoutes.js +337 -0
  32. package/dist/lib/types/avatar.d.ts +8 -1
  33. package/dist/lib/types/multimodal.d.ts +20 -7
  34. package/dist/lib/types/music.d.ts +8 -1
  35. package/dist/lib/types/proxy.d.ts +179 -0
  36. package/dist/lib/types/server.d.ts +3 -0
  37. package/dist/lib/types/tts.d.ts +9 -1
  38. package/dist/lib/utils/avatarProcessor.d.ts +7 -1
  39. package/dist/lib/utils/avatarProcessor.js +6 -0
  40. package/dist/lib/utils/musicProcessor.d.ts +7 -1
  41. package/dist/lib/utils/musicProcessor.js +6 -0
  42. package/dist/lib/utils/parameterValidation.js +5 -1
  43. package/dist/lib/utils/sttProcessor.d.ts +5 -3
  44. package/dist/lib/utils/sttProcessor.js +4 -2
  45. package/dist/lib/utils/ttsProcessor.d.ts +6 -3
  46. package/dist/lib/utils/ttsProcessor.js +5 -2
  47. package/dist/lib/voice/RealtimeVoiceAPI.d.ts +5 -2
  48. package/dist/lib/voice/RealtimeVoiceAPI.js +4 -1
  49. package/dist/lib/voice/index.d.ts +23 -0
  50. package/dist/lib/voice/index.js +124 -2
  51. package/dist/lib/voice/providers/CartesiaTTS.d.ts +31 -0
  52. package/dist/lib/voice/providers/CartesiaTTS.js +189 -0
  53. package/dist/lib/workflow/config.d.ts +3 -3
  54. package/dist/music/index.d.ts +14 -0
  55. package/dist/music/index.js +80 -0
  56. package/dist/proxy/modelRouter.d.ts +5 -1
  57. package/dist/proxy/modelRouter.js +8 -0
  58. package/dist/proxy/openaiFormat.d.ts +137 -0
  59. package/dist/proxy/openaiFormat.js +800 -0
  60. package/dist/proxy/proxyTranslationEngine.d.ts +124 -0
  61. package/dist/proxy/proxyTranslationEngine.js +678 -0
  62. package/dist/server/routes/claudeProxyRoutes.d.ts +6 -5
  63. package/dist/server/routes/claudeProxyRoutes.js +22 -355
  64. package/dist/server/routes/index.d.ts +1 -0
  65. package/dist/server/routes/index.js +10 -2
  66. package/dist/server/routes/openaiProxyRoutes.d.ts +30 -0
  67. package/dist/server/routes/openaiProxyRoutes.js +336 -0
  68. package/dist/types/avatar.d.ts +8 -1
  69. package/dist/types/multimodal.d.ts +20 -7
  70. package/dist/types/music.d.ts +8 -1
  71. package/dist/types/proxy.d.ts +179 -0
  72. package/dist/types/server.d.ts +3 -0
  73. package/dist/types/tts.d.ts +9 -1
  74. package/dist/utils/avatarProcessor.d.ts +7 -1
  75. package/dist/utils/avatarProcessor.js +6 -0
  76. package/dist/utils/musicProcessor.d.ts +7 -1
  77. package/dist/utils/musicProcessor.js +6 -0
  78. package/dist/utils/parameterValidation.js +5 -1
  79. package/dist/utils/sttProcessor.d.ts +5 -3
  80. package/dist/utils/sttProcessor.js +4 -2
  81. package/dist/utils/ttsProcessor.d.ts +6 -3
  82. package/dist/utils/ttsProcessor.js +5 -2
  83. package/dist/voice/RealtimeVoiceAPI.d.ts +5 -2
  84. package/dist/voice/RealtimeVoiceAPI.js +4 -1
  85. package/dist/voice/index.d.ts +23 -0
  86. package/dist/voice/index.js +124 -2
  87. package/dist/voice/providers/CartesiaTTS.d.ts +31 -0
  88. package/dist/voice/providers/CartesiaTTS.js +188 -0
  89. package/package.json +65 -2
@@ -234,6 +234,122 @@ async function clearClaudeProxySettings(expectedBaseUrl) {
234
234
  fs.writeFileSync(CLAUDE_SETTINGS_PATH, JSON.stringify(settings, null, 2));
235
235
  return hadBaseUrl || hadToolSearch;
236
236
  }
237
+ // =============================================================================
238
+ // OPENCODE AUTO-CONFIGURATION
239
+ // =============================================================================
240
+ function getOpenCodeConfigDir() {
241
+ if (process.platform === "darwin") {
242
+ return join(homedir(), "Library", "Application Support", "opencode");
243
+ }
244
+ // Linux/other: XDG_CONFIG_HOME or ~/.config
245
+ return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode");
246
+ }
247
+ const OPENCODE_CONFIG_PATH = join(getOpenCodeConfigDir(), "opencode.json");
248
+ /**
249
+ * Key under which we persist the snapshot of the user's pre-existing
250
+ * `provider.neurolink` config inside `opencode.json` itself. Persisting (rather
251
+ * than relying on in-process state) means restoration still works even if the
252
+ * proxy crashes or shutdown handlers run in a different process.
253
+ *
254
+ * Mirrors the Claude pattern (`__proxy_original_env` inside Claude's settings).
255
+ */
256
+ const OPENCODE_ORIGINAL_KEY = "__proxy_original_neurolink";
257
+ async function setOpenCodeProxySettings(baseUrl, proxyKey) {
258
+ const fs = await import("fs");
259
+ const configDir = getOpenCodeConfigDir();
260
+ try {
261
+ fs.accessSync(configDir);
262
+ }
263
+ catch {
264
+ // OpenCode not installed — config directory does not exist, skip silently
265
+ return;
266
+ }
267
+ let config;
268
+ try {
269
+ config = JSON.parse(fs.readFileSync(OPENCODE_CONFIG_PATH, "utf8"));
270
+ }
271
+ catch {
272
+ // file missing/invalid — create fresh config object
273
+ config = { provider: {} };
274
+ }
275
+ const provider = (config.provider ?? {});
276
+ // Persist a snapshot of the user's pre-existing provider.neurolink — but
277
+ // only the first time we touch the file. Subsequent set() calls must NOT
278
+ // overwrite the snapshot (otherwise after the proxy writes its own block,
279
+ // the next set() would store the proxy's block as the "original" and
280
+ // permanently lose the user's real config on the next clear()).
281
+ if (!(OPENCODE_ORIGINAL_KEY in config)) {
282
+ config[OPENCODE_ORIGINAL_KEY] =
283
+ "neurolink" in provider
284
+ ? JSON.parse(JSON.stringify(provider.neurolink))
285
+ : null;
286
+ }
287
+ provider.neurolink = {
288
+ id: "neurolink",
289
+ name: "NeuroLink Proxy",
290
+ npm: "@ai-sdk/openai-compatible",
291
+ env: [],
292
+ models: {},
293
+ options: {
294
+ baseURL: baseUrl,
295
+ apiKey: proxyKey || "neurolink-proxy",
296
+ },
297
+ };
298
+ config.provider = provider;
299
+ fs.writeFileSync(OPENCODE_CONFIG_PATH, JSON.stringify(config, null, 2));
300
+ }
301
+ async function clearOpenCodeProxySettings(expectedBaseUrl) {
302
+ const fs = await import("fs");
303
+ let config;
304
+ try {
305
+ config = JSON.parse(fs.readFileSync(OPENCODE_CONFIG_PATH, "utf8"));
306
+ }
307
+ catch {
308
+ return false;
309
+ }
310
+ const provider = config.provider;
311
+ if (!provider || !("neurolink" in provider)) {
312
+ return false;
313
+ }
314
+ // Check if our proxy URL matches before removing
315
+ const existing = provider.neurolink;
316
+ if (expectedBaseUrl && existing) {
317
+ const options = existing.options;
318
+ if (options && typeof options.baseURL === "string") {
319
+ if (options.baseURL !== expectedBaseUrl) {
320
+ // User configured a different URL; do not clobber
321
+ return false;
322
+ }
323
+ }
324
+ }
325
+ const hadNeurolink = "neurolink" in provider;
326
+ // Restore from the snapshot persisted at first set(), regardless of process
327
+ // identity. Only delete provider.neurolink when the snapshot says the user
328
+ // explicitly had no entry before — never on an "undefined" snapshot, since
329
+ // that would mean the snapshot was lost and we cannot prove the entry is ours.
330
+ if (OPENCODE_ORIGINAL_KEY in config) {
331
+ const snapshot = config[OPENCODE_ORIGINAL_KEY];
332
+ if (snapshot === null) {
333
+ // User had no provider.neurolink before the proxy started — safe to remove.
334
+ delete provider.neurolink;
335
+ }
336
+ else {
337
+ provider.neurolink = snapshot;
338
+ }
339
+ delete config[OPENCODE_ORIGINAL_KEY];
340
+ }
341
+ else {
342
+ // No snapshot present — refuse to delete to avoid destroying a config
343
+ // the proxy may not own (e.g. a user wrote their own `neurolink` block
344
+ // before the snapshot key was introduced, or this is being cleared from
345
+ // a process that never ran set()).
346
+ logger.debug("[proxy] OpenCode clear: no original-provider snapshot found, leaving provider.neurolink intact");
347
+ return false;
348
+ }
349
+ config.provider = provider;
350
+ fs.writeFileSync(OPENCODE_CONFIG_PATH, JSON.stringify(config, null, 2));
351
+ return hadNeurolink;
352
+ }
237
353
  async function isProxyHealthy(host, port, timeoutMs) {
238
354
  try {
239
355
  const response = await fetch(`http://${host}:${port}/health`, {
@@ -533,9 +649,10 @@ function printProxyBanner(url, strategy) {
533
649
  logger.always(` ${chalk.bold("PID:")} ${chalk.cyan(process.pid)}`);
534
650
  logger.always("");
535
651
  logger.always(chalk.bold("Endpoints:"));
536
- logger.always(` ${chalk.blue("POST")} /v1/messages Proxy to Anthropic`);
537
- logger.always(` ${chalk.green("GET")} /health Health check`);
538
- logger.always(` ${chalk.green("GET")} /status Detailed status`);
652
+ logger.always(` ${chalk.blue("POST")} /v1/messages Claude proxy (Anthropic format)`);
653
+ logger.always(` ${chalk.blue("POST")} /v1/chat/completions OpenAI-compatible proxy`);
654
+ logger.always(` ${chalk.green("GET")} /health Health check`);
655
+ logger.always(` ${chalk.green("GET")} /status — Detailed status`);
539
656
  logger.always("");
540
657
  logger.always(chalk.bold("Set in Claude Code:"));
541
658
  logger.always(` ${chalk.cyan(`ANTHROPIC_BASE_URL=${url}`)}`);
@@ -706,6 +823,7 @@ async function resolveBootPrimaryAccountKey(primaryEmail) {
706
823
  }
707
824
  async function createProxyStartApp(params) {
708
825
  const { createClaudeProxyRoutes } = await import("../../lib/server/routes/claudeProxyRoutes.js");
826
+ const { createOpenAIProxyRoutes } = await import("../../lib/server/routes/openaiProxyRoutes.js");
709
827
  const { Hono } = await import("hono");
710
828
  const app = new Hono();
711
829
  const readiness = createProxyReadinessState();
@@ -724,7 +842,9 @@ async function createProxyStartApp(params) {
724
842
  }, 502);
725
843
  });
726
844
  const routeGroup = createClaudeProxyRoutes(params.modelRouter, "", params.strategy, params.passthrough, params.primaryAccountKey);
727
- for (const route of routeGroup.routes) {
845
+ const openaiRouteGroup = createOpenAIProxyRoutes(params.modelRouter, "", params.port);
846
+ const allProxyRoutes = [...routeGroup.routes, ...openaiRouteGroup.routes];
847
+ for (const route of allProxyRoutes) {
728
848
  const method = route.method.toLowerCase();
729
849
  app[method](route.path, async (c) => {
730
850
  const emptyBody = {};
@@ -1025,6 +1145,13 @@ function registerProxyShutdownHandlers(params) {
1025
1145
  catch {
1026
1146
  // non-fatal
1027
1147
  }
1148
+ try {
1149
+ const shutdownHost = params.host === "0.0.0.0" ? "localhost" : params.host;
1150
+ await clearOpenCodeProxySettings(`http://${shutdownHost}:${params.port}/v1`);
1151
+ }
1152
+ catch {
1153
+ // non-fatal
1154
+ }
1028
1155
  }
1029
1156
  try {
1030
1157
  params.server.close?.();
@@ -1114,6 +1241,15 @@ async function startProxyRuntime(params) {
1114
1241
  logger.debug("[proxy] Failed to auto-configure Claude Code: " +
1115
1242
  (error instanceof Error ? error.message : String(error)));
1116
1243
  }
1244
+ try {
1245
+ await setOpenCodeProxySettings(`${url}/v1`);
1246
+ logger.always(chalk.green(" ✓ Auto-configured OpenCode settings"));
1247
+ logger.always(chalk.dim(" Restart OpenCode to connect through proxy"));
1248
+ }
1249
+ catch (error) {
1250
+ logger.debug("[proxy] Failed to auto-configure OpenCode: " +
1251
+ (error instanceof Error ? error.message : String(error)));
1252
+ }
1117
1253
  }
1118
1254
  else {
1119
1255
  logger.always(chalk.dim(" ⊘ Dev mode: skipping client auto-configuration"));
@@ -1808,6 +1944,12 @@ export const proxyGuardCommand = {
1808
1944
  }
1809
1945
  // Restart failed or launchd not installed — clean up Claude settings
1810
1946
  const cleared = await clearClaudeProxySettings(expectedBaseUrl);
1947
+ try {
1948
+ await clearOpenCodeProxySettings(`${expectedBaseUrl}/v1`);
1949
+ }
1950
+ catch {
1951
+ // non-fatal
1952
+ }
1811
1953
  const state = loadProxyState();
1812
1954
  if (state &&
1813
1955
  state.host === host &&
@@ -1916,9 +2058,16 @@ export const proxySetupCommand = {
1916
2058
  console.info(chalk.green(" ✓ Claude Code configured"));
1917
2059
  }
1918
2060
  catch (e) {
1919
- console.info(chalk.yellow(` ⚠ Could not auto-configure: ${e instanceof Error ? e.message : String(e)}`));
2061
+ console.info(chalk.yellow(` ⚠ Could not auto-configure Claude Code: ${e instanceof Error ? e.message : String(e)}`));
1920
2062
  console.info(chalk.yellow(` Set manually: ANTHROPIC_BASE_URL=${url}`));
1921
2063
  }
2064
+ try {
2065
+ await setOpenCodeProxySettings(`${url}/v1`);
2066
+ console.info(chalk.green(" ✓ OpenCode configured"));
2067
+ }
2068
+ catch (e) {
2069
+ console.info(chalk.yellow(` ⚠ Could not auto-configure OpenCode: ${e instanceof Error ? e.message : String(e)}`));
2070
+ }
1922
2071
  // Done!
1923
2072
  console.info("");
1924
2073
  console.info(chalk.bold.green("Setup complete!"));
@@ -1389,9 +1389,13 @@ export class BaseProvider {
1389
1389
  * // result.video contains the generated video
1390
1390
  * ```
1391
1391
  */
1392
+ // eslint-disable-next-line max-lines-per-function
1392
1393
  async handleVideoGeneration(options, startTime) {
1393
- // Dynamic imports to avoid loading video dependencies unless needed
1394
- const { generateVideoWithVertex, VideoError, VIDEO_ERROR_CODES } = await import("../adapters/video/vertexVideoHandler.js");
1394
+ // Dynamic imports to avoid loading video dependencies unless needed.
1395
+ // Pull VideoError + VIDEO_ERROR_CODES from VideoProcessor (which already
1396
+ // re-exports both) so non-vertex routes don't carry a direct dependency
1397
+ // on the Vertex adapter's module.
1398
+ const { VideoProcessor, VideoError, VIDEO_ERROR_CODES } = await import("../utils/videoProcessor.js");
1395
1399
  const { validateVideoGenerationInput, validateImageForVideo, validateDirectorModeInput, } = await import("../utils/parameterValidation.js");
1396
1400
  const { ErrorFactory } = await import("../utils/errorHandling.js");
1397
1401
  // Build GenerateOptions for validation
@@ -1559,17 +1563,54 @@ export class BaseProvider {
1559
1563
  }
1560
1564
  // Get prompt text
1561
1565
  const prompt = options.prompt || options.input?.text || "";
1566
+ // Honor output.video.provider — when omitted, fall back to "vertex"
1567
+ // for backward compatibility with the original implementation.
1568
+ const requestedProvider = options.output?.video?.provider ?? "vertex";
1569
+ if (!VideoProcessor.supports(requestedProvider)) {
1570
+ throw new VideoError({
1571
+ code: VIDEO_ERROR_CODES.PROVIDER_NOT_SUPPORTED,
1572
+ message: `Video provider "${requestedProvider}" is not registered. Available: ${VideoProcessor.listProviders().join(", ")}`,
1573
+ retriable: false,
1574
+ context: {
1575
+ provider: requestedProvider,
1576
+ available: VideoProcessor.listProviders(),
1577
+ },
1578
+ });
1579
+ }
1580
+ // Resolve the model name without hardcoding a Vertex default for
1581
+ // non-Vertex routes. Precedence: caller-supplied output.video.model,
1582
+ // then options.model (LLM-level field that the caller may have repurposed
1583
+ // for video), then the Vertex Veo default but only when we're actually
1584
+ // calling Vertex. Otherwise leave it null at this stage and let the
1585
+ // handler's metadata fill it in below.
1586
+ const requestedVideoModel = options.output?.video?.model;
1587
+ const resolvedRequestModel = requestedVideoModel ??
1588
+ options.model ??
1589
+ (requestedProvider === "vertex" ? "veo-3.1-generate-001" : undefined);
1562
1590
  logger.info("Starting video generation", {
1563
- provider: "vertex",
1564
- model: options.model || "veo-3.1-generate-001",
1591
+ provider: requestedProvider,
1592
+ ...(resolvedRequestModel ? { model: resolvedRequestModel } : {}),
1565
1593
  promptLength: prompt.length,
1566
1594
  imageSize: imageBuffer.length,
1567
1595
  resolution: options.output?.video?.resolution || "720p",
1568
1596
  duration: options.output?.video?.length || 6,
1569
1597
  });
1570
- // Generate video using Vertex handler (no processor abstraction)
1571
- const videoResult = await generateVideoWithVertex(imageBuffer, prompt, options.output?.video, options.region);
1598
+ // Dispatch through the central VideoProcessor picks up vertex,
1599
+ // kling, runway, replicate (or any custom handler) registered via
1600
+ // ProviderRegistry / VideoProcessor.registerHandler(). Wrap in the
1601
+ // shared timeout helper so standard video gen honors the caller's
1602
+ // timeout the same way director mode does (see above ~Line 2062).
1603
+ const videoTimeout = options.timeout ?? 600_000; // 10 min default
1604
+ const videoResult = await this.executeWithTimeout(() => VideoProcessor.generate(requestedProvider, imageBuffer, prompt, options.output?.video ?? {}, options.region), { timeout: videoTimeout, operationType: "generate" });
1605
+ // Prefer the handler's own model id (more accurate — it knows the exact
1606
+ // checkpoint that ran). Fall back to the request-time value, and finally
1607
+ // to the Vertex default only when we're on the Vertex route.
1608
+ const responseModel = videoResult.metadata?.model ??
1609
+ resolvedRequestModel ??
1610
+ (requestedProvider === "vertex" ? "veo-3.1-generate-001" : "unknown");
1572
1611
  logger.info("Video generation complete", {
1612
+ provider: requestedProvider,
1613
+ model: responseModel,
1573
1614
  videoSize: videoResult.data.length,
1574
1615
  duration: videoResult.metadata?.duration,
1575
1616
  processingTime: videoResult.metadata?.processingTime,
@@ -1577,8 +1618,8 @@ export class BaseProvider {
1577
1618
  // Build result
1578
1619
  const baseResult = {
1579
1620
  content: prompt, // Echo the prompt as content
1580
- provider: "vertex",
1581
- model: options.model || "veo-3.1-generate-001",
1621
+ provider: requestedProvider,
1622
+ model: responseModel,
1582
1623
  usage: { input: 0, output: 0, total: 0 },
1583
1624
  video: videoResult,
1584
1625
  };
@@ -298,6 +298,29 @@ export class ProviderRegistry {
298
298
  catch (err) {
299
299
  logger.debug(`[ProviderRegistry] azure-tts registration skipped: ${err instanceof Error ? err.message : String(err)}`);
300
300
  }
301
+ // Fish Audio and Cartesia also auto-register via the voice/index.ts
302
+ // barrel side-effect. The supports() guard here keeps registration
303
+ // idempotent across entry points — same handler, no overwrite warning.
304
+ try {
305
+ const { TTSProcessor } = await import("../utils/ttsProcessor.js");
306
+ if (!TTSProcessor.supports("fish-audio")) {
307
+ const { FishAudioTTS } = await import("../voice/providers/FishAudioTTS.js");
308
+ TTSProcessor.registerHandler("fish-audio", new FishAudioTTS());
309
+ }
310
+ }
311
+ catch (err) {
312
+ logger.debug(`[ProviderRegistry] fish-audio registration skipped: ${err instanceof Error ? err.message : String(err)}`);
313
+ }
314
+ try {
315
+ const { TTSProcessor } = await import("../utils/ttsProcessor.js");
316
+ if (!TTSProcessor.supports("cartesia")) {
317
+ const { CartesiaTTS } = await import("../voice/providers/CartesiaTTS.js");
318
+ TTSProcessor.registerHandler("cartesia", new CartesiaTTS());
319
+ }
320
+ }
321
+ catch (err) {
322
+ logger.debug(`[ProviderRegistry] cartesia registration skipped: ${err instanceof Error ? err.message : String(err)}`);
323
+ }
301
324
  // ===== STT HANDLER REGISTRATION =====
302
325
  try {
303
326
  const { STTProcessor } = await import("../utils/sttProcessor.js");
package/dist/index.d.ts CHANGED
@@ -33,7 +33,6 @@
33
33
  */
34
34
  import { AIProviderFactory } from "./core/factory.js";
35
35
  export { AIProviderFactory };
36
- export { GoogleTTSHandler } from "./adapters/tts/googleTTSHandler.js";
37
36
  export { NeuroLinkConfigManager as ConfigManager } from "./config/configManager.js";
38
37
  export { BaseFactory, BaseRegistry, NeuroLinkFeatureError, createErrorFactory, withRetry, TypedEventEmitter, } from "./core/infrastructure/index.js";
39
38
  export { NeuroLinkClient, createClient, NeuroLinkApiError, NeuroLinkLanguageModel, NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance, createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware, SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream, OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv, ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/index.js";
@@ -52,6 +51,16 @@ export { AvatarProcessor } from "./utils/avatarProcessor.js";
52
51
  export { AVATAR_ERROR_CODES, AvatarError } from "./utils/avatarProcessor.js";
53
52
  export { MusicProcessor } from "./utils/musicProcessor.js";
54
53
  export { MUSIC_ERROR_CODES, MusicError } from "./utils/musicProcessor.js";
54
+ export { STTProcessor } from "./utils/sttProcessor.js";
55
+ export { AzureTTS, AzureTTSHandler, CartesiaTTS, CartesiaTTSHandler, ElevenLabsTTS, ElevenLabsTTSHandler, FishAudioTTS, FishAudioTTSHandler, GoogleTTSHandler, OpenAITTS, OpenAITTSHandler, AzureSTT, AzureSTTHandler, DeepgramSTT, DeepgramSTTHandler, GoogleSTT, GoogleSTTHandler, OpenAISTT, OpenAISTTHandler, WhisperSTT, WhisperSTTHandler, BaseRealtimeHandler, GeminiLive, GeminiLiveHandler, OpenAIRealtime, OpenAIRealtimeHandler, RealtimeProcessor, RealtimeError, STTError, VoiceError, registerDefaultRealtimeHandlers, registerDefaultSTTHandlers, registerDefaultTTSHandlers, } from "./voice/index.js";
56
+ export { BeatovenMusic, BeatovenMusicHandler, ElevenLabsMusic, ElevenLabsMusicHandler, LyriaMusic, LyriaMusicHandler, registerDefaultMusicHandlers, ReplicateMusic, ReplicateMusicHandler, } from "./music/index.js";
57
+ export { DIDAvatar, DIDAvatarHandler, HeyGenAvatar, HeyGenAvatarHandler, registerDefaultAvatarHandlers, ReplicateAvatar, ReplicateAvatarHandler, } from "./avatar/index.js";
58
+ export { KlingVideoHandler } from "./adapters/video/klingVideoHandler.js";
59
+ export { ReplicateVideoHandler } from "./adapters/video/replicateVideoHandler.js";
60
+ export { RunwayVideoHandler } from "./adapters/video/runwayVideoHandler.js";
61
+ export { VertexVideoHandler, isVertexVideoConfigured, } from "./adapters/video/vertexVideoHandler.js";
62
+ export { ImageGenService } from "./image-gen/ImageGenService.js";
63
+ export { HITLManager } from "./hitl/hitlManager.js";
55
64
  export { ProviderRegistry } from "./factories/providerRegistry.js";
56
65
  import { NeuroLink } from "./neurolink.js";
57
66
  export { NeuroLink };
package/dist/index.js CHANGED
@@ -34,7 +34,6 @@
34
34
  // Core exports
35
35
  import { AIProviderFactory } from "./core/factory.js";
36
36
  export { AIProviderFactory };
37
- export { GoogleTTSHandler } from "./adapters/tts/googleTTSHandler.js";
38
37
  // Config Manager export
39
38
  export { NeuroLinkConfigManager as ConfigManager } from "./config/configManager.js";
40
39
  // Core Infrastructure exports (factory + registry patterns)
@@ -81,6 +80,42 @@ export { AVATAR_ERROR_CODES, AvatarError } from "./utils/avatarProcessor.js";
81
80
  // Music utilities
82
81
  export { MusicProcessor } from "./utils/musicProcessor.js";
83
82
  export { MUSIC_ERROR_CODES, MusicError } from "./utils/musicProcessor.js";
83
+ // STT / Realtime processors (registries for speech-to-text + live voice)
84
+ export { STTProcessor } from "./utils/sttProcessor.js";
85
+ // STT_ERROR_CODES is surfaced via the types barrel (export * from "./types/index.js")
86
+ // STTError is re-exported below from the voice/index.js barrel
87
+ // ============================================================================
88
+ // MEDIA HANDLER CLASSES + AUTO-REGISTRATION
89
+ // ============================================================================
90
+ // Re-exporting from the voice/music/avatar barrels also triggers their
91
+ // module-level auto-registration side effects. Consumers who follow the
92
+ // documented `nl.generate(...)` flow get every shipped handler whose API
93
+ // key is present in process.env, with no manual registerHandler() needed.
94
+ // TTS, STT, Realtime handlers + RealtimeProcessor
95
+ export {
96
+ // TTS
97
+ AzureTTS, AzureTTSHandler, CartesiaTTS, CartesiaTTSHandler, ElevenLabsTTS, ElevenLabsTTSHandler, FishAudioTTS, FishAudioTTSHandler, GoogleTTSHandler, OpenAITTS, OpenAITTSHandler,
98
+ // STT
99
+ AzureSTT, AzureSTTHandler, DeepgramSTT, DeepgramSTTHandler, GoogleSTT, GoogleSTTHandler, OpenAISTT, OpenAISTTHandler, WhisperSTT, WhisperSTTHandler,
100
+ // Realtime
101
+ BaseRealtimeHandler, GeminiLive, GeminiLiveHandler, OpenAIRealtime, OpenAIRealtimeHandler, RealtimeProcessor,
102
+ // Voice error classes (RealtimeError + STTError + VoiceError)
103
+ RealtimeError, STTError, VoiceError,
104
+ // Auto-registration functions (exposed so consumers can re-run them
105
+ // after mutating process.env at runtime, e.g. in test setups)
106
+ registerDefaultRealtimeHandlers, registerDefaultSTTHandlers, registerDefaultTTSHandlers, } from "./voice/index.js";
107
+ // Music handlers
108
+ export { BeatovenMusic, BeatovenMusicHandler, ElevenLabsMusic, ElevenLabsMusicHandler, LyriaMusic, LyriaMusicHandler, registerDefaultMusicHandlers, ReplicateMusic, ReplicateMusicHandler, } from "./music/index.js";
109
+ // Avatar handlers
110
+ export { DIDAvatar, DIDAvatarHandler, HeyGenAvatar, HeyGenAvatarHandler, registerDefaultAvatarHandlers, ReplicateAvatar, ReplicateAvatarHandler, } from "./avatar/index.js";
111
+ // Video handlers (live under adapters/video; no separate video/ barrel)
112
+ export { KlingVideoHandler } from "./adapters/video/klingVideoHandler.js";
113
+ export { ReplicateVideoHandler } from "./adapters/video/replicateVideoHandler.js";
114
+ export { RunwayVideoHandler } from "./adapters/video/runwayVideoHandler.js";
115
+ export { VertexVideoHandler, isVertexVideoConfigured, } from "./adapters/video/vertexVideoHandler.js";
116
+ // Image generation + HITL — surfaced from their dedicated barrels
117
+ export { ImageGenService } from "./image-gen/ImageGenService.js";
118
+ export { HITLManager } from "./hitl/hitlManager.js";
84
119
  // Provider registry (for tests, advanced consumers, and tools that need to
85
120
  // invoke registerAllProviders() outside of constructing a NeuroLink instance)
86
121
  export { ProviderRegistry } from "./factories/providerRegistry.js";
@@ -7,7 +7,20 @@
7
7
  * Use `AvatarProcessor.generate(provider, options)` to dispatch to the
8
8
  * registered handler for `provider`.
9
9
  *
10
+ * Importing this module also auto-registers every shipped avatar handler
11
+ * whose backing API key is present in `process.env`. Registration is
12
+ * idempotent and silently skipped if a provider is already registered or
13
+ * its constructor throws.
14
+ *
10
15
  * @module avatar
11
16
  */
12
17
  export { AVATAR_ERROR_CODES, AvatarError, AvatarProcessor, } from "../utils/avatarProcessor.js";
13
18
  export { DIDAvatar, DIDAvatar as DIDAvatarHandler, } from "./providers/DIDAvatar.js";
19
+ export { HeyGenAvatar, HeyGenAvatar as HeyGenAvatarHandler, } from "./providers/HeyGenAvatar.js";
20
+ export { ReplicateAvatar, ReplicateAvatar as ReplicateAvatarHandler, } from "./providers/ReplicateAvatar.js";
21
+ /**
22
+ * Register every shipped avatar handler whose backing credentials are
23
+ * present in the environment. Safe to call multiple times — existing
24
+ * registrations are preserved.
25
+ */
26
+ export declare function registerDefaultAvatarHandlers(): void;
@@ -7,8 +7,80 @@
7
7
  * Use `AvatarProcessor.generate(provider, options)` to dispatch to the
8
8
  * registered handler for `provider`.
9
9
  *
10
+ * Importing this module also auto-registers every shipped avatar handler
11
+ * whose backing API key is present in `process.env`. Registration is
12
+ * idempotent and silently skipped if a provider is already registered or
13
+ * its constructor throws.
14
+ *
10
15
  * @module avatar
11
16
  */
17
+ import { logger } from "../utils/logger.js";
18
+ import { AvatarProcessor } from "../utils/avatarProcessor.js";
12
19
  export { AVATAR_ERROR_CODES, AvatarError, AvatarProcessor, } from "../utils/avatarProcessor.js";
20
+ // ============================================================================
21
+ // HANDLER CLASSES
22
+ // ============================================================================
13
23
  export { DIDAvatar, DIDAvatar as DIDAvatarHandler, } from "./providers/DIDAvatar.js";
24
+ export { HeyGenAvatar, HeyGenAvatar as HeyGenAvatarHandler, } from "./providers/HeyGenAvatar.js";
25
+ export { ReplicateAvatar, ReplicateAvatar as ReplicateAvatarHandler, } from "./providers/ReplicateAvatar.js";
26
+ // ============================================================================
27
+ // AUTO-REGISTRATION
28
+ // ============================================================================
29
+ import { DIDAvatar } from "./providers/DIDAvatar.js";
30
+ import { HeyGenAvatar } from "./providers/HeyGenAvatar.js";
31
+ import { ReplicateAvatar } from "./providers/ReplicateAvatar.js";
32
+ const AVATAR_HANDLER_CANDIDATES = [
33
+ { name: "d-id", factory: () => new DIDAvatar() },
34
+ { name: "heygen", factory: () => new HeyGenAvatar() },
35
+ {
36
+ name: "replicate",
37
+ aliases: ["musetalk"],
38
+ factory: () => new ReplicateAvatar(),
39
+ },
40
+ ];
41
+ /**
42
+ * Register every shipped avatar handler whose backing credentials are
43
+ * present in the environment. Safe to call multiple times — existing
44
+ * registrations are preserved.
45
+ */
46
+ export function registerDefaultAvatarHandlers() {
47
+ for (const { name, aliases, factory } of AVATAR_HANDLER_CANDIDATES) {
48
+ // Compute missingName / missingAliases separately so a pre-registered
49
+ // primary doesn't block alias backfill — keeps "musetalk" reachable
50
+ // when only "replicate" was wired up via another path.
51
+ const missingName = !AvatarProcessor.supports(name);
52
+ const missingAliases = (aliases ?? []).filter((alias) => !AvatarProcessor.supports(alias));
53
+ if (!missingName && missingAliases.length === 0) {
54
+ continue;
55
+ }
56
+ try {
57
+ // Reuse the already-registered primary's handler for alias backfill
58
+ // when one exists — wiring an alias to a factory-fresh instance
59
+ // would silently diverge from the canonical primary's config.
60
+ let handler;
61
+ if (!missingName) {
62
+ handler = AvatarProcessor.getHandler(name);
63
+ }
64
+ if (!handler) {
65
+ handler = factory();
66
+ if (!handler.isConfigured()) {
67
+ continue;
68
+ }
69
+ }
70
+ if (missingName) {
71
+ AvatarProcessor.registerHandler(name, handler);
72
+ }
73
+ for (const alias of missingAliases) {
74
+ AvatarProcessor.registerHandler(alias, handler);
75
+ }
76
+ }
77
+ catch (err) {
78
+ logger.debug(`[avatar] ${name} auto-registration skipped: ${err instanceof Error ? err.message : String(err)}`);
79
+ }
80
+ }
81
+ }
82
+ // Run once at module import so consumers who follow the documented
83
+ // `nl.generate(...)` flow get every configured handler without manually
84
+ // calling `registerHandler`.
85
+ registerDefaultAvatarHandlers();
14
86
  //# sourceMappingURL=index.js.map
@@ -1389,9 +1389,13 @@ export class BaseProvider {
1389
1389
  * // result.video contains the generated video
1390
1390
  * ```
1391
1391
  */
1392
+ // eslint-disable-next-line max-lines-per-function
1392
1393
  async handleVideoGeneration(options, startTime) {
1393
- // Dynamic imports to avoid loading video dependencies unless needed
1394
- const { generateVideoWithVertex, VideoError, VIDEO_ERROR_CODES } = await import("../adapters/video/vertexVideoHandler.js");
1394
+ // Dynamic imports to avoid loading video dependencies unless needed.
1395
+ // Pull VideoError + VIDEO_ERROR_CODES from VideoProcessor (which already
1396
+ // re-exports both) so non-vertex routes don't carry a direct dependency
1397
+ // on the Vertex adapter's module.
1398
+ const { VideoProcessor, VideoError, VIDEO_ERROR_CODES } = await import("../utils/videoProcessor.js");
1395
1399
  const { validateVideoGenerationInput, validateImageForVideo, validateDirectorModeInput, } = await import("../utils/parameterValidation.js");
1396
1400
  const { ErrorFactory } = await import("../utils/errorHandling.js");
1397
1401
  // Build GenerateOptions for validation
@@ -1559,17 +1563,54 @@ export class BaseProvider {
1559
1563
  }
1560
1564
  // Get prompt text
1561
1565
  const prompt = options.prompt || options.input?.text || "";
1566
+ // Honor output.video.provider — when omitted, fall back to "vertex"
1567
+ // for backward compatibility with the original implementation.
1568
+ const requestedProvider = options.output?.video?.provider ?? "vertex";
1569
+ if (!VideoProcessor.supports(requestedProvider)) {
1570
+ throw new VideoError({
1571
+ code: VIDEO_ERROR_CODES.PROVIDER_NOT_SUPPORTED,
1572
+ message: `Video provider "${requestedProvider}" is not registered. Available: ${VideoProcessor.listProviders().join(", ")}`,
1573
+ retriable: false,
1574
+ context: {
1575
+ provider: requestedProvider,
1576
+ available: VideoProcessor.listProviders(),
1577
+ },
1578
+ });
1579
+ }
1580
+ // Resolve the model name without hardcoding a Vertex default for
1581
+ // non-Vertex routes. Precedence: caller-supplied output.video.model,
1582
+ // then options.model (LLM-level field that the caller may have repurposed
1583
+ // for video), then the Vertex Veo default but only when we're actually
1584
+ // calling Vertex. Otherwise leave it null at this stage and let the
1585
+ // handler's metadata fill it in below.
1586
+ const requestedVideoModel = options.output?.video?.model;
1587
+ const resolvedRequestModel = requestedVideoModel ??
1588
+ options.model ??
1589
+ (requestedProvider === "vertex" ? "veo-3.1-generate-001" : undefined);
1562
1590
  logger.info("Starting video generation", {
1563
- provider: "vertex",
1564
- model: options.model || "veo-3.1-generate-001",
1591
+ provider: requestedProvider,
1592
+ ...(resolvedRequestModel ? { model: resolvedRequestModel } : {}),
1565
1593
  promptLength: prompt.length,
1566
1594
  imageSize: imageBuffer.length,
1567
1595
  resolution: options.output?.video?.resolution || "720p",
1568
1596
  duration: options.output?.video?.length || 6,
1569
1597
  });
1570
- // Generate video using Vertex handler (no processor abstraction)
1571
- const videoResult = await generateVideoWithVertex(imageBuffer, prompt, options.output?.video, options.region);
1598
+ // Dispatch through the central VideoProcessor picks up vertex,
1599
+ // kling, runway, replicate (or any custom handler) registered via
1600
+ // ProviderRegistry / VideoProcessor.registerHandler(). Wrap in the
1601
+ // shared timeout helper so standard video gen honors the caller's
1602
+ // timeout the same way director mode does (see above ~Line 2062).
1603
+ const videoTimeout = options.timeout ?? 600_000; // 10 min default
1604
+ const videoResult = await this.executeWithTimeout(() => VideoProcessor.generate(requestedProvider, imageBuffer, prompt, options.output?.video ?? {}, options.region), { timeout: videoTimeout, operationType: "generate" });
1605
+ // Prefer the handler's own model id (more accurate — it knows the exact
1606
+ // checkpoint that ran). Fall back to the request-time value, and finally
1607
+ // to the Vertex default only when we're on the Vertex route.
1608
+ const responseModel = videoResult.metadata?.model ??
1609
+ resolvedRequestModel ??
1610
+ (requestedProvider === "vertex" ? "veo-3.1-generate-001" : "unknown");
1572
1611
  logger.info("Video generation complete", {
1612
+ provider: requestedProvider,
1613
+ model: responseModel,
1573
1614
  videoSize: videoResult.data.length,
1574
1615
  duration: videoResult.metadata?.duration,
1575
1616
  processingTime: videoResult.metadata?.processingTime,
@@ -1577,8 +1618,8 @@ export class BaseProvider {
1577
1618
  // Build result
1578
1619
  const baseResult = {
1579
1620
  content: prompt, // Echo the prompt as content
1580
- provider: "vertex",
1581
- model: options.model || "veo-3.1-generate-001",
1621
+ provider: requestedProvider,
1622
+ model: responseModel,
1582
1623
  usage: { input: 0, output: 0, total: 0 },
1583
1624
  video: videoResult,
1584
1625
  };
@@ -298,6 +298,29 @@ export class ProviderRegistry {
298
298
  catch (err) {
299
299
  logger.debug(`[ProviderRegistry] azure-tts registration skipped: ${err instanceof Error ? err.message : String(err)}`);
300
300
  }
301
+ // Fish Audio and Cartesia also auto-register via the voice/index.ts
302
+ // barrel side-effect. The supports() guard here keeps registration
303
+ // idempotent across entry points — same handler, no overwrite warning.
304
+ try {
305
+ const { TTSProcessor } = await import("../utils/ttsProcessor.js");
306
+ if (!TTSProcessor.supports("fish-audio")) {
307
+ const { FishAudioTTS } = await import("../voice/providers/FishAudioTTS.js");
308
+ TTSProcessor.registerHandler("fish-audio", new FishAudioTTS());
309
+ }
310
+ }
311
+ catch (err) {
312
+ logger.debug(`[ProviderRegistry] fish-audio registration skipped: ${err instanceof Error ? err.message : String(err)}`);
313
+ }
314
+ try {
315
+ const { TTSProcessor } = await import("../utils/ttsProcessor.js");
316
+ if (!TTSProcessor.supports("cartesia")) {
317
+ const { CartesiaTTS } = await import("../voice/providers/CartesiaTTS.js");
318
+ TTSProcessor.registerHandler("cartesia", new CartesiaTTS());
319
+ }
320
+ }
321
+ catch (err) {
322
+ logger.debug(`[ProviderRegistry] cartesia registration skipped: ${err instanceof Error ? err.message : String(err)}`);
323
+ }
301
324
  // ===== STT HANDLER REGISTRATION =====
302
325
  try {
303
326
  const { STTProcessor } = await import("../utils/sttProcessor.js");
@@ -157,7 +157,7 @@ export declare function createFileTools(registry: FileReferenceRegistry): {
157
157
  } | undefined;
158
158
  columns?: string[] | undefined;
159
159
  entry_path?: string | undefined;
160
- format?: "text" | "summary" | "detailed" | undefined;
160
+ format?: "text" | "detailed" | "summary" | undefined;
161
161
  }, {
162
162
  success: false;
163
163
  error: string | undefined;