Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
fix: tighten Volcengine env loading and shared Access Token config
liuPig4ac108673997
diff --git a/.env.example b/.env.exampleindex 83285b90..66dd0333 100644--- a/.env.example+++ b/.env.example@@ -1,5 +1,6 @@-# Local secrets only. Copy to .env.local (gitignored) and fill in values.-# Do not commit real keys.+# OpenCreator Volcengine / Doubao Voice credentials.+# Copy to ~/.opencreator/.env.local, or point OPENCREATOR_ENV_FILE at this file.+# These are the speech console App ID and Access Token, not IAM AK/SK.+# The same Access Token authenticates ASR, TTS V1, and TTS V3.VOLCENGINE_APP_ID=VOLCENGINE_ACCESS_TOKEN=-VOLCENGINE_SECRET_KEY=diff --git a/apps/daemon/src/creator-services/config-store.ts b/apps/daemon/src/creator-services/config-store.tsindex 0d789acb..6a4c5a9a 100644--- a/apps/daemon/src/creator-services/config-store.ts+++ b/apps/daemon/src/creator-services/config-store.ts@@ -93,9 +93,20 @@ const legacyVideoConfigSchema = z.object({const legacyAliyunTtsSchema = aliyunSchema.transform(() => (structuredClone(creatorServicesDefaults.tts.aliyun)));-const volcengineTtsSchema = ttsProviderSchema(creatorServicesDefaults.tts.volcengine.defaultVoiceId).extend({+const volcengineTtsSchema = z.object({+ baseUrl: boundedString(2048),+ accessToken: boundedString(4096).optional(),+ apiKey: boundedString(4096).optional(),+ model: boundedString(128),+ defaultVoiceId: boundedString(256).default(creatorServicesDefaults.tts.volcengine.defaultVoiceId),appId: boundedString(256).default('')-}).strict();+}).strict().transform(value => ({+ baseUrl: value.baseUrl,+ accessToken: value.accessToken || value.apiKey || '',+ model: value.model,+ defaultVoiceId: value.defaultVoiceId,+ appId: value.appId+}));const ttsConfigSchema = z.object({provider: z.enum(['openai', 'aliyun', 'edge-tts', 'minimax', 'volcengine']),openai: ttsProviderSchema(creatorServicesDefaults.tts.openai.defaultVoiceId),@@ -294,7 +305,7 @@ const creatorCredentialPaths = ['tts.minimax.apiKey','tts.aliyun.apiKey','tts.volcengine.appId',- 'tts.volcengine.apiKey',+ 'tts.volcengine.accessToken','image.openai.apiKey','image.jimeng.apiKey','image.kling.accessKey',@@ -325,13 +336,26 @@ function applyCreatorServiceCredentials(credentials: Record<string, string>): CreatorServicesConfig {const merged = structuredClone(config);+ const migrated = migrateVolcengineTtsCredentials(credentials);for (const path of creatorCredentialPaths) {- const value = credentials[path];+ const value = migrated[path];if (value !== undefined) writePath(merged, path, value);}return parseCreatorServicesConfig(merged);}+function migrateVolcengineTtsCredentials(+ credentials: Record<string, string>+): Record<string, string> {+ if (credentials['tts.volcengine.accessToken'] || !credentials['tts.volcengine.apiKey']) {+ return credentials;+ }+ const next = { ...credentials };+ next['tts.volcengine.accessToken'] = credentials['tts.volcengine.apiKey'];+ delete next['tts.volcengine.apiKey'];+ return next;+}+function readPath(value: unknown, path: string): unknown {let current = value;for (const part of path.split('.')) {@@ -379,7 +403,7 @@ export function presentCreatorServicesConfig(redact('tts.minimax.apiKey', redacted.tts.minimax.apiKey, () => { redacted.tts.minimax.apiKey = ''; });redact('tts.aliyun.apiKey', redacted.tts.aliyun.apiKey, () => { redacted.tts.aliyun.apiKey = ''; });redact('tts.volcengine.appId', redacted.tts.volcengine.appId, () => { redacted.tts.volcengine.appId = ''; });- redact('tts.volcengine.apiKey', redacted.tts.volcengine.apiKey, () => { redacted.tts.volcengine.apiKey = ''; });+ redact('tts.volcengine.accessToken', redacted.tts.volcengine.accessToken, () => { redacted.tts.volcengine.accessToken = ''; });redact('image.openai.apiKey', redacted.image.openai.apiKey, () => { redacted.image.openai.apiKey = ''; });redact('image.jimeng.apiKey', redacted.image.jimeng.apiKey, () => { redacted.image.jimeng.apiKey = ''; });redact('image.kling.accessKey', redacted.image.kling.accessKey, () => { redacted.image.kling.accessKey = ''; });@@ -419,7 +443,7 @@ export function retainCreatorServicesCredentials(retainBlank(() => merged.tts.minimax.apiKey, value => { merged.tts.minimax.apiKey = value; }, current.tts.minimax.apiKey);retainBlank(() => merged.tts.aliyun.apiKey, value => { merged.tts.aliyun.apiKey = value; }, current.tts.aliyun.apiKey);retainBlank(() => merged.tts.volcengine.appId, value => { merged.tts.volcengine.appId = value; }, current.tts.volcengine.appId);- retainBlank(() => merged.tts.volcengine.apiKey, value => { merged.tts.volcengine.apiKey = value; }, current.tts.volcengine.apiKey);+ retainBlank(() => merged.tts.volcengine.accessToken, value => { merged.tts.volcengine.accessToken = value; }, current.tts.volcengine.accessToken);retainBlank(() => merged.image.openai.apiKey, value => { merged.image.openai.apiKey = value; }, current.image.openai.apiKey);retainBlank(() => merged.image.jimeng.apiKey, value => { merged.image.jimeng.apiKey = value; }, current.image.jimeng.apiKey);retainBlank(() => merged.image.kling.accessKey, value => { merged.image.kling.accessKey = value; }, current.image.kling.accessKey);diff --git a/apps/daemon/src/creator-services/volcengine-env.ts b/apps/daemon/src/creator-services/volcengine-env.tsindex f2e4702c..ecdb54f3 100644--- a/apps/daemon/src/creator-services/volcengine-env.ts+++ b/apps/daemon/src/creator-services/volcengine-env.ts@@ -1,13 +1,14 @@import type { CreatorServicesConfig } from '@opencreator/protocol';+import {+ loadVolcengineEnvironment,+ type VolcengineEnvironment+} from '../env-local.js';-export type VolcengineEnvironment = {- VOLCENGINE_APP_ID?: string;- VOLCENGINE_ACCESS_TOKEN?: string;-};+export type { VolcengineEnvironment };export function applyVolcengineEnvironmentOverrides(config: CreatorServicesConfig,- env: VolcengineEnvironment = process.env+ env: VolcengineEnvironment = loadVolcengineEnvironment()): CreatorServicesConfig {const appId = env.VOLCENGINE_APP_ID?.trim() ?? '';const accessToken = env.VOLCENGINE_ACCESS_TOKEN?.trim() ?? '';@@ -26,17 +27,19 @@ export function applyVolcengineEnvironmentOverrides(if (!next.transcription.volcengine.accessToken.trim()) {next.transcription.volcengine.accessToken = accessToken;}- if (!next.tts.volcengine.apiKey.trim()) {- next.tts.volcengine.apiKey = accessToken;+ if (!next.tts.volcengine.accessToken.trim()) {+ next.tts.volcengine.accessToken = accessToken;}}- const configured = next.transcription.volcengine.appId.trim().length > 0- && next.transcription.volcengine.accessToken.trim().length > 0;- if (configured && shouldPreferVolcengineTranscription(next)) {+ const asr = next.transcription.volcengine;+ const tts = next.tts.volcengine;+ const asrConfigured = Boolean(asr.appId.trim() && asr.accessToken.trim());+ const ttsConfigured = Boolean(tts.appId.trim() && tts.accessToken.trim());+ if (asrConfigured && shouldPreferVolcengineTranscription(next)) {next.transcription.provider = 'volcengine';}- if (configured && shouldPreferVolcengineTts(next)) {+ if (ttsConfigured && shouldPreferVolcengineTts(next)) {next.tts.provider = 'volcengine';}return next;diff --git a/apps/daemon/src/creator/krillin/config-bridge.ts b/apps/daemon/src/creator/krillin/config-bridge.tsindex d0394808..d1dda8f0 100644--- a/apps/daemon/src/creator/krillin/config-bridge.ts+++ b/apps/daemon/src/creator/krillin/config-bridge.ts@@ -42,7 +42,7 @@ export function createKrillinConfigToml(config: CreatorServicesConfig): string {aliyun: ttsProvider(config.tts.aliyun),volcengine: {app_id: config.tts.volcengine.appId,- access_token: config.tts.volcengine.apiKey,+ access_token: config.tts.volcengine.accessToken,cluster: config.tts.volcengine.model,default_voice_id: config.tts.volcengine.defaultVoiceId,base_url: config.tts.volcengine.baseUrldiff --git a/apps/daemon/src/creator/krillin/tts-service.ts b/apps/daemon/src/creator/krillin/tts-service.tsindex 6f328ef4..80dccd65 100644--- a/apps/daemon/src/creator/krillin/tts-service.ts+++ b/apps/daemon/src/creator/krillin/tts-service.ts@@ -21,6 +21,7 @@ import {resolveVolcengineTtsRoute,volcengineSpeechRate} from './volcengine-tts-catalog.js';+import { parseVolcengineV3Audio } from './volcengine-tts-v3.js';const MAX_OUTPUT_BYTES = 100 * 1024 * 1024;const MAX_PROCESS_OUTPUT_BYTES = 4 * 1024 * 1024;@@ -268,7 +269,7 @@ function ensureCredentials(provider: Exclude<CreatorTtsProvider, 'edge-tts'>): void {if (provider === 'volcengine') {- if (config.tts.volcengine.appId.trim() && config.tts.volcengine.apiKey.trim()) return;+ if (config.tts.volcengine.appId.trim() && config.tts.volcengine.accessToken.trim()) return;throw new KrillinTtsServiceError('creator_tts_config_missing','Configure the Volcengine TTS App ID and Access Token before generating speech',@@ -348,13 +349,13 @@ async function synthesizeVolcengine(const response = await timedFetch(endpoint, {method: 'POST',headers: {- authorization: `Bearer;${provider.apiKey}`,+ authorization: `Bearer;${provider.accessToken}`,'content-type': 'application/json'},body: JSON.stringify({app: {appid: provider.appId,- token: provider.apiKey,+ token: provider.accessToken,cluster: route.cluster},user: { uid: 'opencreator' },@@ -400,7 +401,7 @@ async function synthesizeVolcengineV3(headers: {'content-type': 'application/json','X-Api-App-Id': provider.appId,- 'X-Api-Access-Key': provider.apiKey,+ 'X-Api-Access-Key': provider.accessToken,'X-Api-Resource-Id': resourceId,'X-Api-Request-Id': crypto.randomUUID()},@@ -418,34 +419,10 @@ async function synthesizeVolcengineV3(})}, input);if (!response.ok) await throwProviderHttpError(response);- const chunks: Buffer[] = [];- const payload = await response.text();- for (const line of payload.split(/\r?\n/)) {- collectVolcengineV3Audio(line, chunks);- }- const content = Buffer.concat(chunks);- if (content.length === 0) throw new Error('Volcengine TTS 2.0 response did not contain audio');+ const content = parseVolcengineV3Audio(await response.text());return { content, format: detectAudioFormat(content, input.format) };}-function collectVolcengineV3Audio(line: string, chunks: Buffer[]): void {- const trimmed = line.trim();- if (!trimmed) return;- let payload: { code?: number; message?: string; data?: string };- try {- payload = JSON.parse(trimmed) as { code?: number; message?: string; data?: string };- } catch {- return;- }- if (payload.code === 20000000) return;- if (payload.code !== undefined && payload.code !== 0) {- throw new Error(`Volcengine TTS 2.0 failed: ${payload.message || payload.code}`);- }- if (typeof payload.data === 'string' && payload.data.length > 0) {- chunks.push(Buffer.from(payload.data, 'base64'));- }-}-async function synthesizeOpenAi(input: ExecuteSynthesisInput & { timeoutMs: number }): Promise<ExecuteSynthesisResult> {diff --git a/apps/daemon/src/creator/krillin/volcengine-tts-v3.ts b/apps/daemon/src/creator/krillin/volcengine-tts-v3.tsnew file mode 100644index 00000000..4695dc9c--- /dev/null+++ b/apps/daemon/src/creator/krillin/volcengine-tts-v3.ts@@ -0,0 +1,84 @@+export const VOLCENGINE_TTS_V3_AUDIO_CODE = 0;+export const VOLCENGINE_TTS_V3_COMPLETE_CODE = 20000000;++type VolcengineV3Frame = {+ kind: 'audio';+ data: Buffer;+} | {+ kind: 'complete';+};++export function parseVolcengineV3Audio(payload: string): Buffer {+ const chunks: Buffer[] = [];+ let completed = false;+ for (const line of payload.split(/\r?\n/)) {+ const frame = parseVolcengineV3Frame(line);+ if (frame === undefined) continue;+ if (frame.kind === 'complete') {+ completed = true;+ break;+ }+ chunks.push(frame.data);+ }+ if (chunks.length === 0) {+ throw new Error(+ completed+ ? 'Volcengine TTS 2.0 completed without audio'+ : 'Volcengine TTS 2.0 response did not contain audio'+ );+ }+ return Buffer.concat(chunks);+}++export function parseVolcengineV3Frame(line: string): VolcengineV3Frame | undefined {+ const trimmed = line.trim();+ if (!trimmed) return undefined;+ const jsonText = trimmed.startsWith('data:') ? trimmed.slice(5).trim() : trimmed;+ if (!jsonText) return undefined;++ let decoded: unknown;+ try {+ decoded = JSON.parse(jsonText);+ } catch {+ throw new Error(`Volcengine TTS 2.0 returned a non-JSON frame: ${truncateFrame(jsonText)}`);+ }++ if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {+ throw new Error(`Volcengine TTS 2.0 returned a non-object frame: ${truncateFrame(jsonText)}`);+ }++ const payload = decoded as { code?: unknown; message?: unknown; data?: unknown };+ if (typeof payload.code !== 'number' || !Number.isFinite(payload.code)) {+ throw new Error(`Volcengine TTS 2.0 frame is missing a numeric code: ${truncateFrame(jsonText)}`);+ }+ if (payload.code === VOLCENGINE_TTS_V3_COMPLETE_CODE) {+ return { kind: 'complete' };+ }+ if (payload.code !== VOLCENGINE_TTS_V3_AUDIO_CODE) {+ const message = typeof payload.message === 'string' && payload.message.trim()+ ? payload.message.trim()+ : String(payload.code);+ throw new Error(`Volcengine TTS 2.0 failed: ${message}`);+ }+ if (typeof payload.data !== 'string' || payload.data.length === 0) {+ return undefined;+ }+ return { kind: 'audio', data: decodeVolcengineV3Audio(payload.data) };+}++function decodeVolcengineV3Audio(value: string): Buffer {+ const normalized = value.replace(/\s+/g, '');+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) {+ throw new Error('Volcengine TTS 2.0 returned invalid audio encoding');+ }+ const data = Buffer.from(normalized, 'base64');+ if (data.length === 0) {+ throw new Error('Volcengine TTS 2.0 returned invalid audio');+ }+ return data;+}++function truncateFrame(value: string): string {+ const compact = value.replace(/\s+/g, ' ');+ return compact.length > 120 ? `${compact.slice(0, 117)}...` : compact;+}diff --git a/apps/daemon/src/creator/templates/video-translation-actions.ts b/apps/daemon/src/creator/templates/video-translation-actions.tsindex 94389ed7..7ccc919a 100644--- a/apps/daemon/src/creator/templates/video-translation-actions.ts+++ b/apps/daemon/src/creator/templates/video-translation-actions.ts@@ -145,7 +145,7 @@ function hasTtsCredentials(if (provider === 'openai') return config.tts.openai.apiKey.length > 0;if (provider === 'minimax') return config.tts.minimax.apiKey.length > 0;if (provider === 'volcengine') {- return config.tts.volcengine.appId.length > 0 && config.tts.volcengine.apiKey.length > 0;+ return config.tts.volcengine.appId.length > 0 && config.tts.volcengine.accessToken.length > 0;}return config.tts.aliyun.apiKey.length > 0;}diff --git a/apps/daemon/src/env-local.ts b/apps/daemon/src/env-local.tsindex e79cb4f9..06650b63 100644--- a/apps/daemon/src/env-local.ts+++ b/apps/daemon/src/env-local.ts@@ -1,12 +1,14 @@import { existsSync, readFileSync } from 'node:fs';import { homedir } from 'node:os';-import { dirname, join, resolve } from 'node:path';+import { join, resolve } from 'node:path';-const MAX_WALK_DEPTH = 8;+export const VOLCENGINE_ENV_KEYS = ['VOLCENGINE_APP_ID', 'VOLCENGINE_ACCESS_TOKEN'] as const;+export type VolcengineEnvKey = (typeof VOLCENGINE_ENV_KEYS)[number];++export type VolcengineEnvironment = Partial<Record<VolcengineEnvKey, string>>;export type LocalEnvironmentLoadOptions = {env?: NodeJS.ProcessEnv;- cwd?: string;homeDir?: string | null;};@@ -32,50 +34,45 @@ export function parseEnvFile(source: string): Record<string, string> {return result;}-export function loadLocalEnvironment(+export function loadVolcengineEnvironment(options: LocalEnvironmentLoadOptions = {}-): string[] {+): VolcengineEnvironment {const env = options.env ?? process.env;- const loaded: string[] = [];- for (const file of resolveLocalEnvFiles(options)) {- applyEnvFile(file, env);- loaded.push(file);+ const fileValues = readWhitelistedVolcengineEnvFile(options);+ const result: VolcengineEnvironment = {};+ for (const key of VOLCENGINE_ENV_KEYS) {+ if (Object.prototype.hasOwnProperty.call(env, key)) {+ const trimmed = env[key]?.trim() ?? '';+ if (trimmed) result[key] = trimmed;+ continue;+ }+ const fromFile = fileValues[key]?.trim();+ if (fromFile) result[key] = fromFile;}- return loaded;+ return result;}-function resolveLocalEnvFiles(options: LocalEnvironmentLoadOptions): string[] {- const env = options.env ?? process.env;- const explicit = env.OPENCREATOR_ENV_FILE?.trim();- if (explicit) {- return existsSync(explicit) ? [resolve(explicit)] : [];- }-- const files: string[] = [];- if (options.homeDir !== null) {- const homeFile = join(options.homeDir ?? homedir(), '.opencreator', '.env.local');- if (existsSync(homeFile)) files.push(homeFile);- }-- let dir = resolve(options.cwd ?? process.cwd());- for (let depth = 0; depth < MAX_WALK_DEPTH; depth += 1) {- const candidate = join(dir, '.env.local');- if (existsSync(candidate) && !files.includes(candidate)) {- files.push(candidate);- break;- }- const parent = dirname(dir);- if (parent === dir) break;- dir = parent;+function readWhitelistedVolcengineEnvFile(+ options: LocalEnvironmentLoadOptions+): VolcengineEnvironment {+ const file = resolveVolcengineEnvFile(options);+ if (file === undefined) return {};+ const parsed = parseEnvFile(readFileSync(file, 'utf8'));+ const result: VolcengineEnvironment = {};+ for (const key of VOLCENGINE_ENV_KEYS) {+ const value = parsed[key]?.trim();+ if (value) result[key] = value;}- return files;+ return result;}-function applyEnvFile(file: string, env: NodeJS.ProcessEnv): void {- const parsed = parseEnvFile(readFileSync(file, 'utf8'));- for (const [key, value] of Object.entries(parsed)) {- if (env[key] === undefined || env[key] === '') {- env[key] = value;- }+function resolveVolcengineEnvFile(options: LocalEnvironmentLoadOptions): string | undefined {+ const env = options.env ?? process.env;+ const explicit = env.OPENCREATOR_ENV_FILE?.trim();+ if (explicit) {+ return existsSync(explicit) ? resolve(explicit) : undefined;}+ if (options.homeDir === null) return undefined;+ const homeFile = join(options.homeDir ?? homedir(), '.opencreator', '.env.local');+ return existsSync(homeFile) ? homeFile : undefined;}diff --git a/apps/daemon/src/main.ts b/apps/daemon/src/main.tsindex 2be8d187..5c7b4d28 100644--- a/apps/daemon/src/main.ts+++ b/apps/daemon/src/main.ts@@ -38,8 +38,6 @@ import {installManagedParentWatch,parseManagedParentPid} from './managed-parent.js';-import { loadLocalEnvironment } from './env-local.js';-type BootstrapPhase = 'starting_runtime';let server: FastifyInstance | undefined;@@ -63,7 +61,6 @@ await main().catch(error => {});async function main(): Promise<void> {- loadLocalEnvironment();const token = createRuntimeToken();const environment = resolveProductionServerEnvironment();const paths = resolveProductionRuntimePaths(environment, {diff --git a/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts b/apps/daemon/test/integration/creator-krillin-cli-runner.test.tsindex 9171c5f9..db011326 100644--- a/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts+++ b/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts@@ -112,7 +112,7 @@ describe('KrillinAI CLI runner', () => {config.transcription.volcengine.accessToken = 'asr-token';config.tts.provider = 'volcengine';config.tts.volcengine.appId = 'tts-app';- config.tts.volcengine.apiKey = 'tts-token';+ config.tts.volcengine.accessToken = 'tts-token';const value = parse(createKrillinConfigToml(config)) as {transcribe: { provider: string; volcengine: Record<string, string> };diff --git a/apps/daemon/test/unit/creator-services-config-store.test.ts b/apps/daemon/test/unit/creator-services-config-store.test.tsindex 2234d7b7..65a365c4 100644--- a/apps/daemon/test/unit/creator-services-config-store.test.ts+++ b/apps/daemon/test/unit/creator-services-config-store.test.ts@@ -9,6 +9,7 @@ import {createFileCreatorServicesConfigStore,createOpenCreatorCreatorServicesConfigStore,CreatorServicesConfigStoreError,+ parseCreatorServicesConfig,presentCreatorServicesConfig,retainCreatorServicesCredentials,type CreatorServicesConfigStore@@ -118,7 +119,7 @@ describe('CreatorServicesConfigStore', () => {expect(config.transcription.volcengine.accessToken).toBe('env-access-token');expect(config.tts.provider).toBe('volcengine');expect(config.tts.volcengine.appId).toBe('env-app-id');- expect(config.tts.volcengine.apiKey).toBe('env-access-token');+ expect(config.tts.volcengine.accessToken).toBe('env-access-token');expect(existsSync(configFile)).toBe(false);expect(existsSync(credentialsFile)).toBe(false);});@@ -186,25 +187,46 @@ describe('CreatorServicesConfigStore', () => {current.transcription.volcengine.appId = 'asr-app';current.transcription.volcengine.accessToken = 'asr-token';current.tts.volcengine.appId = 'tts-app';- current.tts.volcengine.apiKey = 'tts-token';+ current.tts.volcengine.accessToken = 'tts-token';const presented = presentCreatorServicesConfig(current);expect(presented.configuredCredentials).toEqual(expect.arrayContaining(['transcription.volcengine.appId','transcription.volcengine.accessToken','tts.volcengine.appId',- 'tts.volcengine.apiKey'+ 'tts.volcengine.accessToken']));expect(presented.config.transcription.volcengine.appId).toBe('');expect(presented.config.transcription.volcengine.accessToken).toBe('');expect(presented.config.tts.volcengine.appId).toBe('');- expect(presented.config.tts.volcengine.apiKey).toBe('');+ expect(presented.config.tts.volcengine.accessToken).toBe('');expect(retainCreatorServicesCredentials(presented.config, current).transcription.volcengine).toEqual(current.transcription.volcengine);expect(retainCreatorServicesCredentials(presented.config, current).tts.volcengine).toEqual(current.tts.volcengine);});+ it('migrates legacy tts.volcengine.apiKey into accessToken', () => {+ const current = createDefaultCreatorServicesConfig();+ const parsed = parseCreatorServicesConfig({+ ...current,+ tts: {+ ...current.tts,+ volcengine: {+ baseUrl: current.tts.volcengine.baseUrl,+ apiKey: 'legacy-token',+ model: current.tts.volcengine.model,+ defaultVoiceId: current.tts.volcengine.defaultVoiceId,+ appId: 'app-1'+ }+ }+ } as unknown);++ expect(parsed.tts.volcengine.accessToken).toBe('legacy-token');+ expect(parsed.tts.volcengine.appId).toBe('app-1');+ expect(parsed.tts.volcengine).not.toHaveProperty('apiKey');+ });+it('uses Codex as fallback until a custom text model is configured', async () => {let persisted = createDefaultCreatorServicesConfig();const rawStore: CreatorServicesConfigStore = {diff --git a/apps/daemon/test/unit/env-local.test.ts b/apps/daemon/test/unit/env-local.test.tsindex c309f896..1e7e2bd5 100644--- a/apps/daemon/test/unit/env-local.test.ts+++ b/apps/daemon/test/unit/env-local.test.ts@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, describe, expect, it } from 'vitest';-import { loadLocalEnvironment, parseEnvFile } from '../../src/env-local.js';+import { loadVolcengineEnvironment, parseEnvFile } from '../../src/env-local.js';describe('local environment files', () => {let root: string | undefined;@@ -17,44 +17,82 @@ describe('local environment files', () => {'# comment','VOLCENGINE_APP_ID=123','export VOLCENGINE_ACCESS_TOKEN="token-value"',- "VOLCENGINE_SECRET_KEY='secret-value'",+ "DATABASE_URL='secret-value'",'INVALID',''].join('\n'))).toEqual({VOLCENGINE_APP_ID: '123',VOLCENGINE_ACCESS_TOKEN: 'token-value',- VOLCENGINE_SECRET_KEY: 'secret-value'+ DATABASE_URL: 'secret-value'});});- it('loads .env.local from the working directory walk-up without overriding existing values', () => {+ it('does not walk the working directory or copy unrelated secrets into process.env', () => {root = mkdtempSync(join(tmpdir(), 'opencreator-env-local-'));- const nested = join(root, 'apps', 'daemon');- mkdirSync(nested, { recursive: true });writeFileSync(join(root, '.env.local'), ['VOLCENGINE_APP_ID=file-app-id',- 'VOLCENGINE_ACCESS_TOKEN=file-token'+ 'VOLCENGINE_ACCESS_TOKEN=file-token',+ 'DATABASE_URL=should-not-load'].join('\n'));const env: NodeJS.ProcessEnv = {VOLCENGINE_APP_ID: 'shell-app-id'};- const loaded = loadLocalEnvironment({ cwd: nested, env, homeDir: null });+ const loaded = loadVolcengineEnvironment({ env, homeDir: null });- expect(loaded).toEqual([join(root, '.env.local')]);- expect(env.VOLCENGINE_APP_ID).toBe('shell-app-id');- expect(env.VOLCENGINE_ACCESS_TOKEN).toBe('file-token');+ expect(loaded).toEqual({ VOLCENGINE_APP_ID: 'shell-app-id' });+ expect(env.VOLCENGINE_ACCESS_TOKEN).toBeUndefined();+ expect(env.DATABASE_URL).toBeUndefined();+ });++ it('loads only VOLCENGINE_* keys from ~/.opencreator/.env.local', () => {+ root = mkdtempSync(join(tmpdir(), 'opencreator-home-env-'));+ const homeDir = join(root, 'home');+ mkdirSync(join(homeDir, '.opencreator'), { recursive: true });+ writeFileSync(join(homeDir, '.opencreator', '.env.local'), [+ 'VOLCENGINE_APP_ID=home-app-id',+ 'VOLCENGINE_ACCESS_TOKEN=home-token',+ 'DATABASE_URL=should-not-load',+ 'VOLCENGINE_SECRET_KEY=unused'+ ].join('\n'));++ const env: NodeJS.ProcessEnv = {};+ const loaded = loadVolcengineEnvironment({ env, homeDir });++ expect(loaded).toEqual({+ VOLCENGINE_APP_ID: 'home-app-id',+ VOLCENGINE_ACCESS_TOKEN: 'home-token'+ });+ expect(env).toEqual({});});it('loads an explicit OPENCREATOR_ENV_FILE when provided', () => {root = mkdtempSync(join(tmpdir(), 'opencreator-env-file-'));const file = join(root, 'secrets.env');- writeFileSync(file, 'VOLCENGINE_SECRET_KEY=from-explicit-file\n');+ writeFileSync(file, [+ 'VOLCENGINE_ACCESS_TOKEN=from-explicit-file',+ 'DATABASE_URL=should-not-load'+ ].join('\n'));const env: NodeJS.ProcessEnv = {OPENCREATOR_ENV_FILE: file};- expect(loadLocalEnvironment({ cwd: root, env, homeDir: null })).toEqual([file]);- expect(env.VOLCENGINE_SECRET_KEY).toBe('from-explicit-file');+ expect(loadVolcengineEnvironment({ env, homeDir: null })).toEqual({+ VOLCENGINE_ACCESS_TOKEN: 'from-explicit-file'+ });+ expect(env.VOLCENGINE_ACCESS_TOKEN).toBeUndefined();+ expect(env.DATABASE_URL).toBeUndefined();+ });++ it('does not fall back to a file when a process env key is explicitly empty', () => {+ root = mkdtempSync(join(tmpdir(), 'opencreator-empty-env-'));+ const homeDir = join(root, 'home');+ mkdirSync(join(homeDir, '.opencreator'), { recursive: true });+ writeFileSync(join(homeDir, '.opencreator', '.env.local'), 'VOLCENGINE_APP_ID=home-app-id\n');+ const env: NodeJS.ProcessEnv = {+ VOLCENGINE_APP_ID: ''+ };++ expect(loadVolcengineEnvironment({ env, homeDir })).toEqual({});});});diff --git a/apps/daemon/test/unit/krillin-tts-service.test.ts b/apps/daemon/test/unit/krillin-tts-service.test.tsindex 8f8916b8..7481bf02 100644--- a/apps/daemon/test/unit/krillin-tts-service.test.ts+++ b/apps/daemon/test/unit/krillin-tts-service.test.ts@@ -253,7 +253,7 @@ describe('KrillinTtsService', () => {const config = createDefaultCreatorServicesConfig();config.tts.provider = 'volcengine';config.tts.volcengine.appId = 'app-1';- config.tts.volcengine.apiKey = 'token-1';+ config.tts.volcengine.accessToken = 'token-1';const audio = Buffer.from('mp3-bytes');const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({code: 3000,@@ -304,7 +304,7 @@ describe('KrillinTtsService', () => {const config = createDefaultCreatorServicesConfig();config.tts.provider = 'volcengine';config.tts.volcengine.appId = 'app-1';- config.tts.volcengine.apiKey = 'token-1';+ config.tts.volcengine.accessToken = 'token-1';const audio = Buffer.from('v3-bytes');const ndjson = [JSON.stringify({ code: 0, data: audio.toString('base64') }),diff --git a/apps/daemon/test/unit/volcengine-env.test.ts b/apps/daemon/test/unit/volcengine-env.test.tsindex 4c471543..71cc6802 100644--- a/apps/daemon/test/unit/volcengine-env.test.ts+++ b/apps/daemon/test/unit/volcengine-env.test.ts@@ -17,7 +17,35 @@ describe('volcengine environment overrides', () => {expect(config.transcription.volcengine.accessToken).toBe('env-access-token');expect(config.tts.provider).toBe('volcengine');expect(config.tts.volcengine.appId).toBe('env-app-id');- expect(config.tts.volcengine.apiKey).toBe('env-access-token');+ expect(config.tts.volcengine.accessToken).toBe('env-access-token');+ });++ it('selects ASR and TTS independently based on their own credentials', () => {+ const asrOnly = createDefaultCreatorServicesConfig();+ asrOnly.transcription.volcengine.appId = 'asr-app';+ asrOnly.transcription.volcengine.accessToken = 'asr-token';++ const asrConfig = applyVolcengineEnvironmentOverrides(asrOnly, {+ VOLCENGINE_APP_ID: 'env-app-id'+ });+ expect(asrConfig.transcription.provider).toBe('volcengine');+ expect(asrConfig.transcription.volcengine.appId).toBe('asr-app');+ expect(asrConfig.tts.provider).toBe('openai');+ expect(asrConfig.tts.volcengine.appId).toBe('env-app-id');+ expect(asrConfig.tts.volcengine.accessToken).toBe('');++ const ttsOnly = createDefaultCreatorServicesConfig();+ ttsOnly.tts.volcengine.appId = 'tts-app';+ ttsOnly.tts.volcengine.accessToken = 'tts-token';++ const ttsConfig = applyVolcengineEnvironmentOverrides(ttsOnly, {+ VOLCENGINE_APP_ID: 'env-app-id'+ });+ expect(ttsConfig.transcription.provider).toBe('openai');+ expect(ttsConfig.transcription.volcengine.appId).toBe('env-app-id');+ expect(ttsConfig.transcription.volcengine.accessToken).toBe('');+ expect(ttsConfig.tts.provider).toBe('volcengine');+ expect(ttsConfig.tts.volcengine.appId).toBe('tts-app');});it('does not replace saved credentials or a non-default provider', () => {@@ -27,7 +55,7 @@ describe('volcengine environment overrides', () => {current.transcription.volcengine.accessToken = 'saved-token';current.tts.provider = 'minimax';current.tts.volcengine.appId = 'saved-app-id';- current.tts.volcengine.apiKey = 'saved-token';+ current.tts.volcengine.accessToken = 'saved-token';const config = applyVolcengineEnvironmentOverrides(current, {VOLCENGINE_APP_ID: 'env-app-id',@@ -39,6 +67,6 @@ describe('volcengine environment overrides', () => {expect(config.transcription.volcengine.accessToken).toBe('saved-token');expect(config.tts.provider).toBe('minimax');expect(config.tts.volcengine.appId).toBe('saved-app-id');- expect(config.tts.volcengine.apiKey).toBe('saved-token');+ expect(config.tts.volcengine.accessToken).toBe('saved-token');});});diff --git a/apps/daemon/test/unit/volcengine-tts-v3.test.ts b/apps/daemon/test/unit/volcengine-tts-v3.test.tsnew file mode 100644index 00000000..93c3d7d1--- /dev/null+++ b/apps/daemon/test/unit/volcengine-tts-v3.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';+import { parseVolcengineV3Audio } from '../../src/creator/krillin/volcengine-tts-v3.js';++describe('volcengine V3 TTS frames', () => {+ it('concatenates multi-chunk audio and stops at the completion frame', () => {+ const audio = parseVolcengineV3Audio([+ JSON.stringify({ code: 0, data: Buffer.from('aa').toString('base64') }),+ JSON.stringify({ code: 0, data: Buffer.from('bb').toString('base64') }),+ JSON.stringify({ code: 20000000, message: 'OK' }),+ JSON.stringify({ code: 0, data: Buffer.from('cc').toString('base64') })+ ].join('\n'));++ expect(audio.equals(Buffer.from('aabb'))).toBe(true);+ });++ it('accepts SSE data wrappers around JSON frames', () => {+ const audio = parseVolcengineV3Audio([+ `data: ${JSON.stringify({ code: 0, data: Buffer.from('sse').toString('base64') })}`,+ 'data: {"code":20000000,"message":"OK"}'+ ].join('\n'));++ expect(audio.equals(Buffer.from('sse'))).toBe(true);+ });++ it('fails on malformed frames instead of dropping them', () => {+ expect(() => parseVolcengineV3Audio('{"code":0,"data":"YQ=="}\n{not-json}\n'))+ .toThrow(/non-JSON frame/i);+ expect(() => parseVolcengineV3Audio(JSON.stringify({ message: 'oops' })))+ .toThrow(/missing a numeric code/i);+ expect(() => parseVolcengineV3Audio(JSON.stringify({ code: 45000000, message: 'quota exceeded' })))+ .toThrow(/quota exceeded/);+ expect(() => parseVolcengineV3Audio(JSON.stringify({ code: 0, data: '@@@' })))+ .toThrow(/invalid audio encoding/i);+ });++ it('fails when a completion frame arrives without audio', () => {+ expect(() => parseVolcengineV3Audio(JSON.stringify({ code: 20000000, message: 'OK' })))+ .toThrow(/completed without audio/i);+ });+});diff --git a/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx b/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsxindex 73f905f7..e9e4bc89 100644--- a/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx+++ b/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx@@ -2,6 +2,7 @@ import {readCreatorResultSnapshots,type CreatorArtifact,type CreatorJson,+ type CreatorServicesConfigResponse,type CreatorStageRun,type CreatorTtsProvider,type CreatorVisualAssetRef,@@ -277,11 +278,7 @@ export default function StickmanVideoWorkspace(props: {const providerConfig = provider === 'edge-tts'? null: response.config.tts[provider];- const configured = provider === 'edge-tts'- || (providerConfig !== null && (- providerConfig.apiKey.trim().length > 0- || response.configuredCredentials.some(credential => credential === `tts.${provider}.apiKey`)- ));+ const configured = ttsCredentialsConfigured(provider, response);setTtsConfigurationStatus(configured ? 'configured' : 'missing');const imageProvider = response.config.image.provider;if (imageProvider !== 'openai' && imageProvider !== 'gemini') {@@ -1186,6 +1183,24 @@ function isTtsProvider(value: unknown): value is CreatorTtsProvider {|| value === 'volcengine';}+function ttsCredentialsConfigured(+ provider: CreatorTtsProvider,+ response: CreatorServicesConfigResponse+): boolean {+ if (provider === 'edge-tts') return true;+ if (provider === 'volcengine') {+ const value = response.config.tts.volcengine;+ return (value.appId.trim().length > 0 && value.accessToken.trim().length > 0)+ || (+ response.configuredCredentials.includes('tts.volcengine.appId')+ && response.configuredCredentials.includes('tts.volcengine.accessToken')+ );+ }+ const providerConfig = response.config.tts[provider];+ return providerConfig.apiKey.trim().length > 0+ || response.configuredCredentials.some(credential => credential === `tts.${provider}.apiKey`);+}+function cloneScriptManifest(value: ScriptManifest): ScriptManifest {return {...value,diff --git a/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsx b/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsxindex 7bdb51b4..97e9f125 100644--- a/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsx+++ b/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsx@@ -373,7 +373,7 @@ function createVideoConfig() {aliyun: { baseUrl: '', apiKey: '', model: '', defaultVoiceId: '' },volcengine: {baseUrl: 'https://openspeech.bytedance.com',- apiKey: '',+ accessToken: '',model: 'volcano_tts',defaultVoiceId: 'BV001_streaming',appId: ''diff --git a/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx b/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsxindex 047c896b..5c56a8e0 100644--- a/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx+++ b/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx@@ -103,6 +103,7 @@ describe('CreatorServicesSettingsView', () => {await user.click(screen.getByRole('option', { name: '火山引擎' }));expect(screen.getByLabelText('Access Token')).toBeInTheDocument();expect(screen.getByLabelText('资源 ID')).toHaveValue('volc.seedasr.auc');+ expect(screen.getByText(/共用同一套 Access Token/)).toBeInTheDocument();expect(screen.queryByText('OSS 存储')).not.toBeInTheDocument();await user.click(screen.getByRole('tab', { name: '配音服务' }));@@ -112,6 +113,7 @@ describe('CreatorServicesSettingsView', () => {.toHaveTextContent('小模型 TTS(volcano_tts)');expect(screen.getByLabelText('Access Token')).toBeInTheDocument();expect(screen.getByLabelText('克隆 / 自定义 Speaker ID')).toBeInTheDocument();+ expect(screen.getByText(/使用与语音识别相同的豆包语音控制台/)).toBeInTheDocument();expect(screen.getByText(/豆包 2.0 \/ 声音复刻走 V3/)).toBeInTheDocument();await user.click(screen.getByRole('combobox', { name: '服务商' }));diff --git a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx b/apps/web/src/features/settings/CreatorServicesSettingsView.tsxindex 8532c6be..f0e6bb1d 100644--- a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx+++ b/apps/web/src/features/settings/CreatorServicesSettingsView.tsx@@ -634,8 +634,8 @@ function TranscriptionSettings(props: SettingsGroupProps & {/><p className="creator-services-inline-note">{l(- '使用豆包语音控制台的 App ID 和 Access Token。录音文件识别大模型需单独开通。',- 'Use the App ID and Access Token from the Doubao Voice console. File recognition must be enabled separately.'+ '使用豆包语音控制台的 App ID 和 Access Token。录音文件识别、TTS V1 与 TTS V3 共用同一套 Access Token,仅请求头字段名不同。',+ 'Use the App ID and Access Token from the Doubao Voice console. File recognition, TTS V1, and TTS V3 share that Access Token; only the HTTP field names differ.')}</p></>@@ -767,8 +767,8 @@ function TtsSettings(props: SettingsGroupProps) {/><p className="creator-services-inline-note">{l(- '小模型走 V1 HTTP;豆包 2.0 / 声音复刻走 V3。可在音色列表选择官方音色,或填写克隆 Speaker ID(S_ 开头)。',- 'Small-model voices use V1 HTTP. Doubao 2.0 and voice cloning use V3. Pick an official voice or enter a cloned speaker ID starting with S_.'+ '使用与语音识别相同的豆包语音控制台 App ID 和 Access Token。小模型走 V1 HTTP(Bearer Token);豆包 2.0 / 声音复刻走 V3(X-Api-Access-Key)。可在音色列表选择官方音色,或填写克隆 Speaker ID(S_ 开头)。',+ 'Use the same Doubao Voice console App ID and Access Token as transcription. Small-model voices use V1 HTTP (Bearer token). Doubao 2.0 and voice cloning use V3 (X-Api-Access-Key). Pick an official voice or enter a cloned speaker ID starting with S_.')}</p></>@@ -1007,11 +1007,11 @@ function VolcengineTtsFields(props: {onChange={appId => props.onChange({ ...props.value, appId })}/><PasswordField- id="tts-volcengine-api-key"+ id="tts-volcengine-access-token"label="Access Token"- value={props.value.apiKey}- configured={props.configuredCredentials.has('tts.volcengine.apiKey')}- onChange={apiKey => props.onChange({ ...props.value, apiKey })}+ value={props.value.accessToken}+ configured={props.configuredCredentials.has('tts.volcengine.accessToken')}+ onChange={accessToken => props.onChange({ ...props.value, accessToken })}/><SelectFieldid="tts-volcengine-cluster"diff --git a/packages/protocol/src/creator-services.ts b/packages/protocol/src/creator-services.tsindex 7e051eea..71f710c3 100644--- a/packages/protocol/src/creator-services.ts+++ b/packages/protocol/src/creator-services.ts@@ -17,13 +17,24 @@ export type CreatorTtsProviderConfig = OpenAiCompatibleConfig & {defaultVoiceId: string;};-export type VolcengineTtsConfig = CreatorTtsProviderConfig & {+/**+ * Doubao Voice / OpenSpeech console credentials.+ * ASR, TTS V1, and TTS V3 share this Access Token; only the wire names differ:+ * ASR and TTS V3 send `X-Api-Access-Key`, while TTS V1 sends+ * `Authorization: Bearer;<token>` and JSON `app.token`.+ */+export type VolcengineSpeechCredentials = {appId: string;+ accessToken: string;};-export type VolcengineAsrConfig = {- appId: string;- accessToken: string;+export type VolcengineTtsConfig = VolcengineSpeechCredentials & {+ baseUrl: string;+ model: string;+ defaultVoiceId: string;+};++export type VolcengineAsrConfig = VolcengineSpeechCredentials & {resourceId: string;baseUrl: string;};@@ -165,7 +176,7 @@ export type CreatorServicesCredentialField =| 'tts.minimax.apiKey'| 'tts.aliyun.apiKey'| 'tts.volcengine.appId'- | 'tts.volcengine.apiKey'+ | 'tts.volcengine.accessToken'| 'image.openai.apiKey'| 'image.jimeng.apiKey'| 'image.kling.accessKey'@@ -235,7 +246,7 @@ export function createDefaultCreatorServicesConfig(): CreatorServicesConfig {},volcengine: {baseUrl: defaultVolcengineSpeechBaseUrl,- apiKey: '',+ accessToken: '',model: defaultVolcengineTtsCluster,defaultVoiceId: defaultVolcengineTtsVoiceId,appId: ''diff --git a/runtime/krillinai/config/config.go b/runtime/krillinai/config/config.goindex a84977e5..fcf4480e 100644--- a/runtime/krillinai/config/config.go+++ b/runtime/krillinai/config/config.go@@ -62,6 +62,8 @@ type AliyunTranscribeConfig struct {Speech AliyunSpeechConfig `toml:"speech"`}+// VolcengineAsrConfig holds Doubao Voice / OpenSpeech console credentials.+// AppId and AccessToken are shared with TTS; ASR sends the token as X-Api-Access-Key.type VolcengineAsrConfig struct {AppId string `toml:"app_id"`AccessToken string `toml:"access_token"`@@ -69,6 +71,9 @@ type VolcengineAsrConfig struct {BaseUrl string `toml:"base_url"`}+// VolcengineTtsConfig uses the same console Access Token as ASR.+// V1 sends it as Authorization: Bearer;<token> and JSON app.token.+// V3 sends it as X-Api-Access-Key.type VolcengineTtsConfig struct {AppId string `toml:"app_id"`AccessToken string `toml:"access_token"`diff --git a/runtime/krillinai/pkg/volcengine/tts.go b/runtime/krillinai/pkg/volcengine/tts.goindex f03e3cbb..6055294f 100644--- a/runtime/krillinai/pkg/volcengine/tts.go+++ b/runtime/krillinai/pkg/volcengine/tts.go@@ -245,44 +245,87 @@ func (c *TtsClient) synthesizeV3(ctx context.Context, options types.TTSSpeechOptif response.StatusCode != http.StatusOK {return fmt.Errorf("volcengine tts 2.0 returned HTTP %d: %s", response.StatusCode, boundedMessage(payload))}+ audio, err := parseV3Audio(payload)+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(options.OutputFile), 0755); err != nil {+ return err+ }+ return os.WriteFile(options.OutputFile, audio, 0644)+}++type ttsV3Chunk struct {+ Code *int `json:"code"`+ Message string `json:"message"`+ Data string `json:"data"`+}++func parseV3Audio(payload []byte) ([]byte, error) {var audio []byte+ completed := falsefor _, line := range strings.Split(string(payload), "\n") {- line = strings.TrimSpace(line)- if line == "" {- continue- }- var decoded ttsV3Chunk- if err := json.Unmarshal([]byte(line), &decoded); err != nil {- continue+ chunk, done, err := parseV3Frame(line)+ if err != nil {+ return nil, err}- if decoded.Code == ttsV3SuccessCode {+ if done {+ completed = truebreak}- if decoded.Code != 0 {- return fmt.Errorf("volcengine tts 2.0 error %d: %s", decoded.Code, decoded.Message)+ if len(chunk) > 0 {+ audio = append(audio, chunk...)}- if decoded.Data == "" {- continue- }- chunk, err := base64.StdEncoding.DecodeString(decoded.Data)- if err != nil {- return fmt.Errorf("volcengine tts 2.0 decode audio: %w", err)- }- audio = append(audio, chunk...)}if len(audio) == 0 {- return fmt.Errorf("volcengine tts 2.0 response did not include audio")- }- if err := os.MkdirAll(filepath.Dir(options.OutputFile), 0755); err != nil {- return err+ if completed {+ return nil, fmt.Errorf("volcengine tts 2.0 completed without audio")+ }+ return nil, fmt.Errorf("volcengine tts 2.0 response did not include audio")}- return os.WriteFile(options.OutputFile, audio, 0644)+ return audio, nil}-type ttsV3Chunk struct {- Code int `json:"code"`- Message string `json:"message"`- Data string `json:"data"`+func parseV3Frame(line string) (chunk []byte, complete bool, err error) {+ line = strings.TrimSpace(line)+ if line == "" {+ return nil, false, nil+ }+ if strings.HasPrefix(line, "data:") {+ line = strings.TrimSpace(strings.TrimPrefix(line, "data:"))+ if line == "" {+ return nil, false, nil+ }+ }+ var decoded ttsV3Chunk+ if unmarshalErr := json.Unmarshal([]byte(line), &decoded); unmarshalErr != nil {+ return nil, false, fmt.Errorf("volcengine tts 2.0 returned a non-JSON frame: %s", boundedMessage([]byte(line)))+ }+ if decoded.Code == nil {+ return nil, false, fmt.Errorf("volcengine tts 2.0 frame missing code: %s", boundedMessage([]byte(line)))+ }+ switch *decoded.Code {+ case ttsV3SuccessCode:+ return nil, true, nil+ case 0:+ if decoded.Data == "" {+ return nil, false, nil+ }+ audio, decodeErr := base64.StdEncoding.DecodeString(decoded.Data)+ if decodeErr != nil {+ return nil, false, fmt.Errorf("volcengine tts 2.0 decode audio: %w", decodeErr)+ }+ if len(audio) == 0 {+ return nil, false, fmt.Errorf("volcengine tts 2.0 returned invalid audio")+ }+ return audio, false, nil+ default:+ message := strings.TrimSpace(decoded.Message)+ if message == "" {+ message = fmt.Sprintf("%d", *decoded.Code)+ }+ return nil, false, fmt.Errorf("volcengine tts 2.0 error %d: %s", *decoded.Code, message)+ }}func resolveTTSRoute(cluster, voice string) (api, resource string) {diff --git a/runtime/krillinai/pkg/volcengine/volcengine_test.go b/runtime/krillinai/pkg/volcengine/volcengine_test.goindex 48c43a6d..9b3ac354 100644--- a/runtime/krillinai/pkg/volcengine/volcengine_test.go+++ b/runtime/krillinai/pkg/volcengine/volcengine_test.go@@ -238,6 +238,44 @@ func TestTtsSynthesizeUsesV3ForDoubaoTwoOhVoices(t *testing.T) {}}+func TestParseV3AudioStrictFrames(t *testing.T) {+ first := base64.StdEncoding.EncodeToString([]byte("aa"))+ second := base64.StdEncoding.EncodeToString([]byte("bb"))+ audio, err := parseV3Audio([]byte(strings.Join([]string{+ `{"code":0,"data":"` + first + `"}`,+ `{"code":0,"data":"` + second + `"}`,+ `{"code":20000000,"message":"OK"}`,+ `{"code":0,"data":"` + base64.StdEncoding.EncodeToString([]byte("cc")) + `"}`,+ }, "\n")))+ if err != nil {+ t.Fatalf("parseV3Audio() error = %v", err)+ }+ if string(audio) != "aabb" {+ t.Fatalf("audio = %q", audio)+ }++ sse, err := parseV3Audio([]byte("data: {\"code\":0,\"data\":\"" + first + "\"}\ndata: {\"code\":20000000,\"message\":\"OK\"}\n"))+ if err != nil {+ t.Fatalf("SSE parseV3Audio() error = %v", err)+ }+ if string(sse) != "aa" {+ t.Fatalf("sse audio = %q", sse)+ }++ if _, err := parseV3Audio([]byte("{\"code\":0,\"data\":\"" + first + "\"}\n{not-json}\n")); err == nil || !strings.Contains(err.Error(), "non-JSON frame") {+ t.Fatalf("malformed frame error = %v", err)+ }+ if _, err := parseV3Audio([]byte(`{"message":"oops"}`)); err == nil || !strings.Contains(err.Error(), "missing code") {+ t.Fatalf("missing code error = %v", err)+ }+ if _, err := parseV3Audio([]byte(`{"code":45000000,"message":"quota exceeded"}`)); err == nil || !strings.Contains(err.Error(), "quota exceeded") {+ t.Fatalf("provider error = %v", err)+ }+ if _, err := parseV3Audio([]byte(`{"code":20000000,"message":"OK"}`)); err == nil || !strings.Contains(err.Error(), "completed without audio") {+ t.Fatalf("empty completion error = %v", err)+ }+}+func TestSpeechFormatUsesOutputExtension(t *testing.T) {if got := speechFormat("", "speech.wav"); got != "wav" {t.Fatalf("wav format = %q", got)