diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b6a473..8612685 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ Format based on [Keep a Changelog](https://keepachangelog.com/). Versioning foll ## [Unreleased] +## [0.23.0] - 2026-11-08 + +### Changed + +- `voicethere projects voice-advanced` no longer carries its own list of keys, defaults and ranges. The platform returns the definitions, and the voice engine facts (type, whole numbers, allowed values, range) come from `@node-webrtc-rust/voice-catalog` 0.18.0. A new setting shows up in `list` and works with `set` without a CLI update. Against a platform that does not return definitions yet, `set` takes the type from the project's current defaults and the server validates the value. +- `list` shows the defaults the platform returns. Platforms that return definitions show the values the runner uses with no override (`vad.threshold` 0.05, `vad.minSpeechDurationMs` 200, `vad.speechPadMs` 500, `tts.postUtteranceSilenceMs` 1750). +- `@node-webrtc-rust/voice-catalog` is now 0.18.0, which is licensed BUSL-1.1. +- `set` no longer checks the shape of the JSON text settings (`voice.profilesByLanguage`, the wait and ready message texts) locally; the server rejects bad input. + ## [0.22.0] - 2026-11-06 ### Added diff --git a/README.md b/README.md index a043b07..1c0598e 100644 --- a/README.md +++ b/README.md @@ -457,6 +457,18 @@ voicethere projects session-settings set error_message "Sorry, something went wr Boolean values for `set`: `true` / `false` / `1` / `0` / `yes` / `no`. +## Advanced voice settings + +`voicethere projects voice-advanced list` prints every setting of the project with its current value, its default and its range. The platform sends the list, so a key added there shows up without a CLI update. `set` checks the value against the voice engine's type, whole-number and range rules and, when the platform sends them, against the platform's own limits before it sends anything. The server still has the final say. + +```bash +voicethere projects voice-advanced list +voicethere projects voice-advanced set vad.threshold 0.05 +voicethere projects voice-advanced reset +``` + +Defaults are the values the runner uses with no override. `voicethere projects voice-advanced --help` lists the engine settings offline. Changes apply on the next **`voicethere deploy --wait`**. + ## Reconnect window `connection.reconnectWindowSec` sets how long a dropped voice conversation is held for the client to reconnect: a whole number of seconds from 15 to 30 (default 15). A recovered conversation is billed including the interruption. An unrecovered one stops billing at the drop but holds an agent runner slot for the window. It applies on the next **`voicethere deploy --wait`**. diff --git a/package-lock.json b/package-lock.json index 7da7ab5..a7312fb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "@voicethere/cli", - "version": "0.22.0", + "version": "0.23.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@voicethere/cli", - "version": "0.22.0", + "version": "0.23.0", "license": "MIT", "dependencies": { - "@node-webrtc-rust/voice-catalog": "0.13.4", + "@node-webrtc-rust/voice-catalog": "0.18.0", "@voicethere/agent": "0.29.1", "commander": "13.1.0", "diff": "5.2.0", @@ -649,10 +649,10 @@ } }, "node_modules/@node-webrtc-rust/voice-catalog": { - "version": "0.13.4", - "resolved": "https://registry.npmjs.org/@node-webrtc-rust/voice-catalog/-/voice-catalog-0.13.4.tgz", - "integrity": "sha512-vlBsaqmepaDkeX/8gyVSjAYvRAHAmPY0p8ijyTpo0BmgdEVZCVUF4i3z8moZsDyfS3SX9BHTydmqif3SeNfDpw==", - "license": "MIT", + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/@node-webrtc-rust/voice-catalog/-/voice-catalog-0.18.0.tgz", + "integrity": "sha512-AzHATkrBjQksxoHlOFuK5PYL0mIm7x0Wqccot0+6qgeMgPruES9fRHh8W4v5PjQIDd2TQMcLuQdyXQ7bzjVB9A==", + "license": "BUSL-1.1", "engines": { "node": ">=18" } diff --git a/package.json b/package.json index ecf707e..cae4cb1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@voicethere/cli", - "version": "0.22.0", + "version": "0.23.0", "description": "VoiceThere cloud CLI — login, projects, and agent bundle upload", "type": "module", "bin": { @@ -38,7 +38,7 @@ }, "license": "MIT", "dependencies": { - "@node-webrtc-rust/voice-catalog": "0.13.4", + "@node-webrtc-rust/voice-catalog": "0.18.0", "@voicethere/agent": "0.29.1", "commander": "13.1.0", "diff": "5.2.0", diff --git a/src/cli.ts b/src/cli.ts index c0fd04c..92f05f2 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -84,7 +84,7 @@ import { import { formatVoiceAdvancedSettingsGroupHelp, voiceAdvancedSettingNamesHelp, -} from "./commands/projects/voice-advanced/defs.js"; +} from "./commands/projects/voice-advanced/definitions.js"; import { runProjectsList } from "./commands/projects/list.js"; import { runProjectsShow } from "./commands/projects/show.js"; import { runProjectsUse } from "./commands/projects/use.js"; diff --git a/src/commands/projects/voice-advanced/commands.test.ts b/src/commands/projects/voice-advanced/commands.test.ts index 76fe1c3..df930ef 100644 --- a/src/commands/projects/voice-advanced/commands.test.ts +++ b/src/commands/projects/voice-advanced/commands.test.ts @@ -1,9 +1,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { VoiceAdvancedDefinition } from "../../../lib/api.js"; import { - parseVoiceAdvancedSettingValue, - VOICE_ADVANCED_SETTING_DEFS, - VOICE_ADVANCED_SETTING_KEYS, -} from "./defs.js"; + fallbackDefinition, + formatVoiceAdvancedSettingsGroupHelp, + parseVoiceAdvancedValue, + resolveDefinitions, +} from "./definitions.js"; import { runProjectsVoiceAdvancedList } from "./list.js"; import { runProjectsVoiceAdvancedReset, @@ -32,14 +34,91 @@ vi.mock("../../../lib/project-config.js", () => ({ requireProjectId: (...args: unknown[]) => requireProjectId(...args), })); -describe("projects voice-advanced commands", () => { +function def( + partial: Partial & + Pick, +): VoiceAdvancedDefinition { + return { + path: partial.key.split("."), + label: partial.key, + description: `About ${partial.key}`, + engineKey: null, + ...partial, + }; +} + +const DEFINITIONS: VoiceAdvancedDefinition[] = [ + def({ + key: "vad.threshold", + type: "number", + default: 0.05, + engineKey: "vad.threshold", + }), + def({ + key: "vad.minSpeechDurationMs", + type: "number", + default: 200, + engineKey: "vad.minSpeechDurationMs", + }), + def({ + key: "vad.provider", + type: "string", + default: "energy", + enum: ["energy", "adaptive"], + engineKey: "vad.provider", + }), + def({ + key: "vad.gateStt", + type: "boolean", + default: true, + engineKey: "vad.gateStt", + }), + def({ + key: "vad.adaptive.stuckActiveMs", + type: "number", + default: 8000, + min: 1000, + max: 60000, + engineKey: "vad.adaptive.stuckActiveMs", + }), + def({ + key: "vad.adaptive.noiseMarginDb", + type: "number", + default: 6, + engineKey: "vad.adaptive.noiseMarginDb", + }), + def({ + key: "tts.speed", + type: "number", + default: 0.9, + integer: false, + min: 0.2, + max: 2, + }), + def({ key: "tts.phraseCache", type: "boolean", default: true }), + def({ key: "voice.profilesByLanguage", type: "string", default: "{}" }), +]; + +function resolve(key: string) { + const found = resolveDefinitions({ definitions: DEFINITIONS }).find( + (d) => d.key === key, + ); + if (!found) { + throw new Error(`fixture has no ${key}`); + } + return found; +} + +describe("projects voice-advanced", () => { beforeEach(() => { listProjectVoiceAdvancedSettings.mockReset(); setProjectVoiceAdvancedSetting.mockReset(); resetProjectVoiceAdvancedSettings.mockReset(); requireCredentials.mockReset(); requireProjectId.mockReset(); + vi.restoreAllMocks(); vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); requireCredentials.mockResolvedValue({ api_key: "vth_test", @@ -48,759 +127,273 @@ describe("projects voice-advanced commands", () => { requireProjectId.mockResolvedValue("proj-1"); }); - it("defaults follow the platform defs (lockstep)", () => { - const d = VOICE_ADVANCED_SETTING_DEFS; - expect(d["vad.minSilenceDurationMs"].default).toBe(1100); - expect(d["vad.sttGateHoldMs"].default).toBe(400); - expect( - JSON.parse(String(d["languageId.autoSwitch.waitMessage.texts"].default)), - ).toEqual({ - de: "Einen Moment bitte, ich wechsle auf {language}.", - en: "One moment, switching to {language}.", - es: "Un momento, por favor, cambio al {language}.", - fr: "Un instant, je passe en {language}.", - it: "Un momento, cambio lingua: {language}.", - nl: "Een moment, ik schakel over naar het {language}.", - pl: "Chwileczkę, przełączam na język: {language}.", - pt: "Um momento, vou mudar para {language}.", - ru: "Одну минуту, переключаюсь на {language}.", - }); - }); - - it("lists every canonical voice-advanced key", () => { - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("noiseSuppression.enabled"); - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("languageId.enabled"); - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("languageId.minSpeechMs"); - expect(VOICE_ADVANCED_SETTING_KEYS).toContain( - "languageId.autoSwitch.enabled", - ); - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("voice.profilesByLanguage"); - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("tts.phraseCache"); - expect(VOICE_ADVANCED_SETTING_KEYS).toContain( - "connection.reconnectWindowSec", - ); - expect(VOICE_ADVANCED_SETTING_KEYS).toHaveLength(49); - expect(VOICE_ADVANCED_SETTING_KEYS).not.toContain( - "voice.expectedLanguages", - ); - for (const key of [ - "languageId.autoSwitch.waitAudio", - "languageId.autoSwitch.waitMessage.mode", - "languageId.autoSwitch.waitMessage.skipWhenReady", - "languageId.autoSwitch.waitMessage.texts", - "languageId.autoSwitch.readyMessage.minSwitchMs", - "languageId.autoSwitch.readyMessage.texts", - ]) { - expect(VOICE_ADVANCED_SETTING_KEYS).toContain(key); - } - }); - - it("lists resolved advanced settings", async () => { - listProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", - settings: { - vad: { - enabled: true, - bargeIn: { requireSttPartial: false }, - }, - noiseSuppression: { enabled: true }, - events: { mode: "both" }, - }, - }); - - await runProjectsVoiceAdvancedList({}); - - expect(listProjectVoiceAdvancedSettings).toHaveBeenCalledWith("proj-1"); - expect(console.log).toHaveBeenCalledWith("vad.enabled=true"); - expect(console.log).toHaveBeenCalledWith( - "vad.bargeIn.requireSttPartial=false", - ); - expect(console.log).toHaveBeenCalledWith("noiseSuppression.enabled=true"); - }); - - it("sets noiseSuppression.enabled false", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: { noiseSuppression: { enabled: false } }, - }); - - await runProjectsVoiceAdvancedSet({ - name: "noiseSuppression.enabled", - value: "false", - }); - - expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( - "proj-1", - "noiseSuppression.enabled", - false, - ); - expect(console.log).toHaveBeenCalledWith("noiseSuppression.enabled=false"); - }); - - it("sets a boolean advanced setting", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: { vad: { bargeIn: { requireSttPartial: false } } }, - }); - - await runProjectsVoiceAdvancedSet({ - name: "vad.bargeIn.requireSttPartial", - value: "false", - }); - - expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( - "proj-1", - "vad.bargeIn.requireSttPartial", - false, - ); - expect(console.log).toHaveBeenCalledWith( - "vad.bargeIn.requireSttPartial=false", - ); - }); - - it("sets fractional tts.speed", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: { tts: { speed: 0.7 } }, - }); - - await runProjectsVoiceAdvancedSet({ - name: "tts.speed", - value: "0.7", - }); - - expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( - "proj-1", - "tts.speed", - 0.7, - ); - expect(console.log).toHaveBeenCalledWith("tts.speed=0.7"); - }); - - it("defines tts.phraseCache as a boolean that defaults to on", () => { - expect(VOICE_ADVANCED_SETTING_DEFS["tts.phraseCache"]).toMatchObject({ - type: "boolean", - default: true, - }); - }); - - it("sets tts.phraseCache true and false and rejects other values", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - - await runProjectsVoiceAdvancedSet({ - name: "tts.phraseCache", - value: "false", - }); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - "tts.phraseCache", - false, - ); - expect(console.log).toHaveBeenCalledWith("tts.phraseCache=false"); - - await runProjectsVoiceAdvancedSet({ - name: "tts.phraseCache", - value: "true", - }); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - "tts.phraseCache", - true, - ); - - await expect( - runProjectsVoiceAdvancedSet({ name: "tts.phraseCache", value: "maybe" }), - ).rejects.toThrow(/Invalid boolean/); - }); - - describe("speaker gate and adaptive VAD", () => { - const parse = parseVoiceAdvancedSettingValue; - - it("parses valid values", () => { - expect(parse("speakerGate.mode", "auto")).toBe("auto"); - expect(parse("speakerGate.mode", "manual")).toBe("manual"); - expect(parse("speakerGate.mode", "disabled")).toBe("disabled"); - expect(parse("speakerGate.bargeIn", "anyone")).toBe("anyone"); - expect(parse("speakerGate.bargeIn", "caller_only")).toBe("caller_only"); - expect(parse("speakerGate.suppressShortBargeIn", "true")).toBe(true); - expect(parse("vad.provider", "adaptive")).toBe("adaptive"); - expect(parse("vad.adaptive.noiseMarginDb", "8")).toBe(8); - expect(parse("vad.adaptive.noiseMarginDb", "7.5")).toBe(7.5); - expect(parse("vad.adaptive.noiseMarginDb", "0")).toBe(0); - expect(parse("vad.adaptive.noiseMarginDb", "30")).toBe(30); - expect(parse("vad.adaptive.useSpeechLevel", "false")).toBe(false); - expect(parse("vad.adaptive.stuckActiveMs", "1000")).toBe(1000); - expect(parse("vad.adaptive.stuckActiveMs", "60000")).toBe(60000); - }); - - it("rejects invalid values", () => { - expect(() => parse("speakerGate.mode", "bogus")).toThrow( - /must be one of: disabled, auto, manual/, - ); - expect(() => parse("speakerGate.bargeIn", "nobody")).toThrow( - /must be one of: caller_only, anyone/, - ); - expect(() => parse("speakerGate.suppressShortBargeIn", "maybe")).toThrow( - /Invalid boolean/, - ); - expect(() => parse("vad.adaptive.useSpeechLevel", "maybe")).toThrow( - /Invalid boolean/, - ); - expect(() => parse("vad.adaptive.noiseMarginDb", "31")).toThrow( - /between 0 and 30/, - ); - expect(() => parse("vad.adaptive.noiseMarginDb", "-1")).toThrow( - /between 0 and 30/, - ); - expect(() => parse("vad.adaptive.stuckActiveMs", "999")).toThrow( - /between 1000 and 60000/, + describe("parseVoiceAdvancedValue with API definitions", () => { + it("accepts a valid value of each type", () => { + expect(parseVoiceAdvancedValue(resolve("vad.gateStt"), "off")).toBe( + false, ); - expect(() => parse("vad.adaptive.stuckActiveMs", "60001")).toThrow( - /between 1000 and 60000/, + expect(parseVoiceAdvancedValue(resolve("vad.gateStt"), "Yes")).toBe(true); + expect(parseVoiceAdvancedValue(resolve("vad.threshold"), "0.3")).toBe( + 0.3, ); - }); - - it("set sends the dotted key and typed value", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ settings: {} }); - await runProjectsVoiceAdvancedSet({ - name: "speakerGate.mode", - value: "auto", - }); - await runProjectsVoiceAdvancedSet({ - name: "vad.adaptive.noiseMarginDb", - value: "8", - }); - expect(setProjectVoiceAdvancedSetting).toHaveBeenNthCalledWith( - 1, - "proj-1", - "speakerGate.mode", - "auto", - ); - expect(setProjectVoiceAdvancedSetting).toHaveBeenNthCalledWith( - 2, - "proj-1", - "vad.adaptive.noiseMarginDb", - 8, + expect( + parseVoiceAdvancedValue(resolve("vad.minSpeechDurationMs"), "300"), + ).toBe(300); + expect(parseVoiceAdvancedValue(resolve("vad.provider"), "adaptive")).toBe( + "adaptive", ); + expect(parseVoiceAdvancedValue(resolve("tts.speed"), "0.9")).toBe(0.9); + expect( + parseVoiceAdvancedValue( + resolve("voice.profilesByLanguage"), + ' {"de":{"stt":"de"}} ', + ), + ).toBe('{"de":{"stt":"de"}}'); }); - it("list prints every new key from the nested API shape", async () => { - listProjectVoiceAdvancedSettings.mockResolvedValue({ - settings: { - speakerGate: { - mode: "auto", - bargeIn: "caller_only", - suppressShortBargeIn: false, - }, - vad: { - provider: "adaptive", - adaptive: { - noiseMarginDb: 8, - useSpeechLevel: true, - stuckActiveMs: 8000, - }, - }, - }, - }); - await runProjectsVoiceAdvancedList({}); - const lines = ( - console.log as unknown as ReturnType - ).mock.calls.map((c) => String(c[0])); - for (const line of [ - "speakerGate.mode=auto", - "speakerGate.bargeIn=caller_only", - "speakerGate.suppressShortBargeIn=false", - "vad.provider=adaptive", - "vad.adaptive.noiseMarginDb=8", - "vad.adaptive.useSpeechLevel=true", - "vad.adaptive.stuckActiveMs=8000", - ]) { - expect(lines).toContain(line); - } - }); - }); - - describe("vad.provider", () => { - it("vad.provider rejects silero", () => { + it("rejects a non-number", () => { expect(() => - parseVoiceAdvancedSettingValue("vad.provider", "silero"), - ).toThrow(/must be one of: energy, adaptive/); + parseVoiceAdvancedValue(resolve("vad.threshold"), "abc"), + ).toThrow(/Invalid number/); + expect(() => + parseVoiceAdvancedValue(resolve("vad.threshold"), ""), + ).toThrow(/Invalid number/); }); - it("vad.provider accepts energy", () => { - expect(parseVoiceAdvancedSettingValue("vad.provider", "energy")).toBe( - "energy", - ); + it("rejects a fraction on an integer key", () => { + expect(() => + parseVoiceAdvancedValue(resolve("vad.minSpeechDurationMs"), "200.5"), + ).toThrow(/must be an integer/); }); - }); - describe("tts.sentenceCase", () => { - it("is a string enum auto|off that defaults to auto", () => { - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("tts.sentenceCase"); - expect(VOICE_ADVANCED_SETTING_DEFS["tts.sentenceCase"]).toMatchObject({ - type: "string", - enum: ["auto", "off"], - default: "auto", - }); + it("rejects an invalid boolean", () => { + expect(() => + parseVoiceAdvancedValue(resolve("vad.gateStt"), "maybe"), + ).toThrow(/Invalid boolean/); }); - it("appears in the list output with default auto", async () => { - listProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", - settings: { tts: { sentenceCase: "auto" } }, - }); - - await runProjectsVoiceAdvancedList({}); - - expect(console.log).toHaveBeenCalledWith("tts.sentenceCase=auto"); + it("rejects an enum value the API does not offer (silero) while the engine knows it", () => { + expect(() => + parseVoiceAdvancedValue(resolve("vad.provider"), "silero"), + ).toThrow(/must be one of: energy, adaptive/); }); - it.each(["off", "auto"])("sets %s", async (value) => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - - await runProjectsVoiceAdvancedSet({ name: "tts.sentenceCase", value }); - - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - "tts.sentenceCase", - value, - ); - expect(console.log).toHaveBeenCalledWith(`tts.sentenceCase=${value}`); + it("rejects a value above the API cap but inside the engine range", () => { + expect(() => + parseVoiceAdvancedValue(resolve("vad.adaptive.stuckActiveMs"), "60001"), + ).toThrow(/between 1000 and 60000/); }); - it("rejects bogus", async () => { - await expect( - runProjectsVoiceAdvancedSet({ - name: "tts.sentenceCase", - value: "bogus", - }), - ).rejects.toThrow(/tts\.sentenceCase must be one of: auto, off/); + it("rejects a value outside the engine range that has no API cap", () => { + expect(() => + parseVoiceAdvancedValue(resolve("vad.adaptive.noiseMarginDb"), "31"), + ).toThrow(/engine range/); + }); + + it("prints one warning when the API disagrees with the catalog and uses the catalog", () => { + const resolved = resolveDefinitions({ + definitions: [ + def({ + key: "vad.minSpeechDurationMs", + type: "number", + default: 200, + integer: false, + engineKey: "vad.minSpeechDurationMs", + }), + ], + })[0]; + const warnings = vi + .mocked(console.error) + .mock.calls.filter((c) => String(c[0]).includes("warning")); + expect(warnings).toHaveLength(1); + expect(String(warnings[0][0])).toContain("vad.minSpeechDurationMs"); + expect(resolved.integer).toBe(true); }); }); - describe("debug.ttsTextTrace", () => { - it("is a boolean that defaults to off", () => { - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("debug.ttsTextTrace"); - expect(VOICE_ADVANCED_SETTING_DEFS["debug.ttsTextTrace"]).toMatchObject({ - type: "boolean", - default: false, - }); - }); - - it.each([ - ["on", true], - ["true", true], - ["off", false], - ["false", false], - ])("set %s sends %s", async (value, expected) => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", + describe("set", () => { + it("sends the typed value for a key from definitions", async () => { + listProjectVoiceAdvancedSettings.mockResolvedValue({ settings: {}, + definitions: DEFINITIONS, }); - await runProjectsVoiceAdvancedSet({ - name: "debug.ttsTextTrace", - value, + name: "vad.threshold", + value: "0.2", }); - - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( + expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( "proj-1", - "debug.ttsTextTrace", - expected, + "vad.threshold", + 0.2, ); - expect(console.log).toHaveBeenCalledWith( - `debug.ttsTextTrace=${String(expected)}`, - ); - }); - - it("rejects an invalid value", async () => { - await expect( - runProjectsVoiceAdvancedSet({ - name: "debug.ttsTextTrace", - value: "maybe", - }), - ).rejects.toThrow(/Invalid boolean/); + expect(console.log).toHaveBeenCalledWith("vad.threshold=0.2"); }); - it("list shows on until when the API returns an end time", async () => { + it("lists the valid keys for an unknown key and sends nothing", async () => { listProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", - settings: { - debug: { - ttsTextTrace: true, - ttsTextTraceUntil: "2026-10-17T08:00:00.000Z", - }, - }, + settings: {}, + definitions: DEFINITIONS, }); - - await runProjectsVoiceAdvancedList({}); - - expect(console.log).toHaveBeenCalledWith( - "debug.ttsTextTrace=true (on until 2026-10-17T08:00:00.000Z)", + await expect( + runProjectsVoiceAdvancedSet({ name: "vad.nope", value: "1" }), + ).rejects.toThrow( + /Unknown voice advanced setting vad\.nope\. Valid: vad\.threshold, /, ); + expect(setProjectVoiceAdvancedSetting).not.toHaveBeenCalled(); }); - it("list shows plain off when the trace is off", async () => { + it("does not send an invalid value", async () => { listProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", - settings: { debug: { ttsTextTrace: false, ttsTextTraceUntil: null } }, + settings: {}, + definitions: DEFINITIONS, }); - - await runProjectsVoiceAdvancedList({}); - - expect(console.log).toHaveBeenCalledWith("debug.ttsTextTrace=false"); + await expect( + runProjectsVoiceAdvancedSet({ name: "vad.provider", value: "silero" }), + ).rejects.toThrow(/must be one of/); + expect(setProjectVoiceAdvancedSetting).not.toHaveBeenCalled(); }); }); - describe("connection.reconnectWindowSec", () => { - it("is a number 15-30 that defaults to 15", () => { - expect( - VOICE_ADVANCED_SETTING_DEFS["connection.reconnectWindowSec"], - ).toMatchObject({ type: "number", min: 15, max: 30, default: 15 }); - }); - - it("appears in the list output with default 15", async () => { - listProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", - settings: { connection: { reconnectWindowSec: 15 } }, - }); - - await runProjectsVoiceAdvancedList({}); - - expect(console.log).toHaveBeenCalledWith( - "connection.reconnectWindowSec=15", - ); - }); - - it("sets connection.reconnectWindowSec to 30", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: { connection: { reconnectWindowSec: 30 } }, - }); + describe("set against a platform without definitions", () => { + const response = { + settings: { + vad: { gateStt: true, sampleRate: 16000 }, + tts: { speed: 0.9 }, + }, + defaults: { + vad: { gateStt: true, sampleRate: 16000 }, + tts: { speed: 0.9 }, + }, + }; + it("sends a boolean for vad.gateStt, typed from defaults", async () => { + listProjectVoiceAdvancedSettings.mockResolvedValue(response); await runProjectsVoiceAdvancedSet({ - name: "connection.reconnectWindowSec", - value: "30", + name: "vad.gateStt", + value: "false", }); - expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( "proj-1", - "connection.reconnectWindowSec", - 30, - ); - expect(console.log).toHaveBeenCalledWith( - "connection.reconnectWindowSec=30", + "vad.gateStt", + false, ); }); - it.each(["14", "31", "15.5", "abc"])("rejects %s", async (value) => { - await expect( - runProjectsVoiceAdvancedSet({ - name: "connection.reconnectWindowSec", - value, - }), - ).rejects.toThrow(); - expect(setProjectVoiceAdvancedSetting).not.toHaveBeenCalled(); - }); - - it("accepts 15", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); + it("sends a string for vad.sampleRate", async () => { + listProjectVoiceAdvancedSettings.mockResolvedValue(response); await runProjectsVoiceAdvancedSet({ - name: "connection.reconnectWindowSec", - value: "15", + name: "vad.sampleRate", + value: "8000", }); expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( "proj-1", - "connection.reconnectWindowSec", - 15, - ); - }); - }); - - it("rejects tts.speed outside 0.2–2.0", async () => { - await expect( - runProjectsVoiceAdvancedSet({ name: "tts.speed", value: "0.1" }), - ).rejects.toThrow(/between 0\.2 and 2/); - }); - - describe("language switch wait settings", () => { - const set = (name: string, value: string) => - runProjectsVoiceAdvancedSet({ name, value }); - - it("rejects the removed voice.expectedLanguages key", async () => { - await expect(set("voice.expectedLanguages", "en,de")).rejects.toThrow( - /Unknown voice advanced setting voice\.expectedLanguages/, + "vad.sampleRate", + "8000", ); }); - it("accepts each waitAudio value and rejects others", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - for (const value of ["buffer_replay", "first_utterance"]) { - await set("languageId.autoSwitch.waitAudio", value); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - "languageId.autoSwitch.waitAudio", - value, - ); - } - await expect( - set("languageId.autoSwitch.waitAudio", "all"), - ).rejects.toThrow(/must be one of: buffer_replay, first_utterance/); - }); - - it("accepts each waitMessage.mode value and rejects others", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - for (const value of ["end_of_utterance", "immediate", "off"]) { - await set("languageId.autoSwitch.waitMessage.mode", value); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - "languageId.autoSwitch.waitMessage.mode", - value, - ); - } - await expect( - set("languageId.autoSwitch.waitMessage.mode", "later"), - ).rejects.toThrow(/must be one of: end_of_utterance, immediate, off/); - }); - - it("parses waitMessage.skipWhenReady as a boolean", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - await set("languageId.autoSwitch.waitMessage.skipWhenReady", "no"); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( + it("sends a fractional number for a key the catalog does not know", async () => { + listProjectVoiceAdvancedSettings.mockResolvedValue(response); + await runProjectsVoiceAdvancedSet({ name: "tts.speed", value: "0.85" }); + expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( "proj-1", - "languageId.autoSwitch.waitMessage.skipWhenReady", - false, + "tts.speed", + 0.85, ); - await expect( - set("languageId.autoSwitch.waitMessage.skipWhenReady", "maybe"), - ).rejects.toThrow(/Invalid boolean/); }); - it("validates waitMessage.texts JSON", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - const key = "languageId.autoSwitch.waitMessage.texts"; - await set(key, '{"en":"One moment, switching."}'); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - key, - '{"en":"One moment, switching."}', - ); - await expect(set(key, "nope")).rejects.toThrow(/valid JSON object/); - await expect(set(key, "[]")).rejects.toThrow( - /JSON object keyed by language code/, - ); - await expect(set(key, '{"english":"x"}')).rejects.toThrow( - /invalid language key/, - ); - await expect(set(key, '{"en":3}')).rejects.toThrow(/non-empty string/); - await expect(set(key, '{"en":" "}')).rejects.toThrow(/non-empty string/); + it("still applies the engine facts of a catalog key", async () => { + listProjectVoiceAdvancedSettings.mockResolvedValue(response); await expect( - set(key, JSON.stringify({ en: "a".repeat(301) })), - ).rejects.toThrow(/at most 300 characters/); - }); - - it("validates voice.profilesByLanguage shape", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - const key = "voice.profilesByLanguage"; - await set(key, '{"de":{"stt":"de","tts":"de-thorsten-high"}}'); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - key, - '{"de":{"stt":"de","tts":"de-thorsten-high"}}', - ); - await expect(set(key, "{")).rejects.toThrow(/valid JSON object/); - await expect(set(key, '{"german":{"stt":"de"}}')).rejects.toThrow( - /invalid language key/, - ); - await expect(set(key, '{"de":"de"}')).rejects.toThrow( - /must be an object/, - ); - await expect(set(key, '{"de":{"stt":5}}')).rejects.toThrow( - /must be a string/, - ); - await expect(set(key, '{"de":{}}')).rejects.toThrow(/is empty/); + runProjectsVoiceAdvancedSet({ name: "vad.sampleRate", value: "44100" }), + ).rejects.toThrow(/must be one of: 8000, 16000/); }); - it("sets languageId.timing to each allowed value and rejects others", async () => { - expect(VOICE_ADVANCED_SETTING_KEYS).toContain("languageId.timing"); - expect(VOICE_ADVANCED_SETTING_KEYS).not.toContain( - "languageId.continuous", + it("sends an unknown key as text and shows the server's 400", async () => { + listProjectVoiceAdvancedSettings.mockResolvedValue(response); + setProjectVoiceAdvancedSetting.mockRejectedValue( + new Error("HTTP 400: unknown key vad.nope"), ); - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - for (const value of ["early", "end_of_utterance", "continuous"]) { - await set("languageId.timing", value); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - "languageId.timing", - value, - ); - } - await expect(set("languageId.timing", "true")).rejects.toThrow( - /must be one of: early, end_of_utterance, continuous/, - ); - }); - - it("defaults minSpeechMs to 1500 within 1000–5000", async () => { - expect( - VOICE_ADVANCED_SETTING_DEFS["languageId.minSpeechMs"], - ).toMatchObject({ - default: 1500, - min: 1000, - max: 5000, - }); - expect(VOICE_ADVANCED_SETTING_DEFS["languageId.timing"].default).toBe( - "early", - ); - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - await expect(set("languageId.minSpeechMs", "999")).rejects.toThrow( - /between 1000 and 5000/, - ); - }); - - it("accepts finalHoldMs up to 10000 like the dashboard", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - await set("languageId.autoSwitch.finalHoldMs", "10000"); await expect( - set("languageId.autoSwitch.finalHoldMs", "10001"), - ).rejects.toThrow(/between 0 and 10000/); - }); - - it("validates readyMessage.minSwitchMs as 0-15000", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", - settings: {}, - }); - const key = "languageId.autoSwitch.readyMessage.minSwitchMs"; - expect(VOICE_ADVANCED_SETTING_DEFS[key]).toMatchObject({ - default: 2000, - min: 0, - max: 15000, - }); - await set(key, "0"); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( + runProjectsVoiceAdvancedSet({ name: "vad.nope", value: "1" }), + ).rejects.toThrow(/HTTP 400: unknown key vad\.nope/); + expect(setProjectVoiceAdvancedSetting).toHaveBeenCalledWith( "proj-1", - key, - 0, + "vad.nope", + "1", ); - await set(key, "15000"); - await expect(set(key, "15001")).rejects.toThrow(/between 0 and 15000/); - await expect(set(key, "-1")).rejects.toThrow(/between 0 and 15000/); - await expect(set(key, "soon")).rejects.toThrow(/Invalid number/); }); - it("validates readyMessage.texts JSON", async () => { - setProjectVoiceAdvancedSetting.mockResolvedValue({ - project_id: "proj-1", + it("reads the flat wait message path from defaults", () => { + const d = fallbackDefinition("languageId.autoSwitch.waitMessage.mode", { settings: {}, + defaults: { + languageId: { autoSwitch: { waitMessageMode: "immediate" } }, + }, }); - const key = "languageId.autoSwitch.readyMessage.texts"; - await set(key, '{"de":"Okay, machen wir auf Deutsch weiter."}'); - expect(setProjectVoiceAdvancedSetting).toHaveBeenLastCalledWith( - "proj-1", - key, - '{"de":"Okay, machen wir auf Deutsch weiter."}', - ); - await expect(set(key, "nope")).rejects.toThrow(/valid JSON object/); - await expect(set(key, '{"english":"x"}')).rejects.toThrow( - /invalid language key/, - ); - await expect( - set(key, JSON.stringify({ de: "a".repeat(301) })), - ).rejects.toThrow(/at most 300 characters/); + expect(d.type).toBe("string"); }); + }); - it("lists the ready message settings from the flat API shape", async () => { + describe("list", () => { + it("prints every key from definitions with its default", async () => { listProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", settings: { - languageId: { - autoSwitch: { - readyMessageMinSwitchMs: 3000, - readyMessageTexts: '{"de":"Okay."}', - }, + vad: { + threshold: 0.07, + minSpeechDurationMs: 200, + provider: "energy", + gateStt: true, + adaptive: { stuckActiveMs: 8000, noiseMarginDb: 6 }, }, + tts: { speed: 0.9, phraseCache: true }, + voice: { profilesByLanguage: "{}" }, }, + definitions: DEFINITIONS, }); - await runProjectsVoiceAdvancedList({}); - expect(console.log).toHaveBeenCalledWith( - "languageId.autoSwitch.readyMessage.minSwitchMs=3000", - ); - expect(console.log).toHaveBeenCalledWith( - 'languageId.autoSwitch.readyMessage.texts={"de":"Okay."}', + await runProjectsVoiceAdvancedList(); + const lines = vi.mocked(console.log).mock.calls.map((c) => String(c[0])); + expect(lines).toHaveLength(DEFINITIONS.length); + for (const d of DEFINITIONS) { + expect(lines.some((l) => l.startsWith(`${d.key}=`))).toBe(true); + } + expect(lines).toContain("vad.threshold=0.07 (default 0.05)"); + expect(lines).toContain( + "vad.adaptive.stuckActiveMs=8000 (default 8000 [1000–60000])", ); }); - it("lists the wait settings from the flat API shape", async () => { + it("without definitions prints the keys found in settings, including the flat wait paths", async () => { listProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", settings: { - languageId: { - autoSwitch: { - waitAudio: "first_utterance", - waitMessageMode: "off", - waitMessageSkipWhenReady: false, - waitMessageTexts: '{"en":"Hi."}', - }, + vad: { gateStt: true }, + debug: { + ttsTextTrace: true, + ttsTextTraceUntil: "2026-11-08T12:00:00Z", }, + languageId: { autoSwitch: { waitMessageMode: "immediate" } }, }, }); - await runProjectsVoiceAdvancedList({}); - expect(console.log).toHaveBeenCalledWith( - "languageId.autoSwitch.waitAudio=first_utterance", - ); - expect(console.log).toHaveBeenCalledWith( - "languageId.autoSwitch.waitMessage.mode=off", - ); - expect(console.log).toHaveBeenCalledWith( - "languageId.autoSwitch.waitMessage.skipWhenReady=false", - ); - expect(console.log).toHaveBeenCalledWith( - 'languageId.autoSwitch.waitMessage.texts={"en":"Hi."}', - ); + await runProjectsVoiceAdvancedList(); + const lines = vi.mocked(console.log).mock.calls.map((c) => String(c[0])); + expect(lines).toEqual([ + "vad.gateStt=true", + "debug.ttsTextTrace=true (on until 2026-11-08T12:00:00Z)", + "languageId.autoSwitch.waitMessage.mode=immediate", + ]); }); }); - it("resets advanced settings", async () => { - resetProjectVoiceAdvancedSettings.mockResolvedValue({ - project_id: "proj-1", - settings: { vad: { gateStt: true }, events: { mode: "both" } }, - }); - - await runProjectsVoiceAdvancedReset({}); + it("help lists engine keys from the catalog and points to list", () => { + const help = formatVoiceAdvancedSettingsGroupHelp(); + expect(help).toContain("vad.threshold (0.15)"); + expect(help).toContain("vad.provider (energy) [energy|adaptive|silero]"); + expect(help).toContain("voicethere projects voice-advanced list"); + }); + it("resets advanced settings", async () => { + resetProjectVoiceAdvancedSettings.mockResolvedValue({ settings: {} }); + await runProjectsVoiceAdvancedReset(); expect(resetProjectVoiceAdvancedSettings).toHaveBeenCalledWith("proj-1"); expect(console.log).toHaveBeenCalledWith("reset=defaults"); }); diff --git a/src/commands/projects/voice-advanced/definitions.ts b/src/commands/projects/voice-advanced/definitions.ts new file mode 100644 index 0000000..2545ae2 --- /dev/null +++ b/src/commands/projects/voice-advanced/definitions.ts @@ -0,0 +1,376 @@ +import { + VOICE_AGENT_SETTING_PATHS, + VOICE_AGENT_SETTINGS, + type VoiceAgentSettingDef, +} from "@node-webrtc-rust/voice-catalog"; +import type { + ProjectVoiceAdvancedSettingsResponse, + VoiceAdvancedDefinition, +} from "../../../lib/api.js"; +import { logStep } from "../../../lib/command-log.js"; + +/** + * A setting as the CLI checks it. Engine facts (type, integer, enum, engine range) come from the + * voice engine catalog; the API `definitions` add the product cap, label and description. The + * server stays the final validator. + */ +export interface ResolvedDef { + key: string; + /** Where the response's `settings` / `defaults` hold the value. */ + path: string[]; + type: "boolean" | "number" | "string"; + default?: unknown; + integer?: boolean; + /** Values the engine accepts. */ + engineEnum?: readonly string[]; + /** Values the API accepts (a product subset of the engine values). */ + apiEnum?: readonly string[]; + engineMin?: number; + engineMax?: number; + /** Product cap from the API, applied after the engine range. */ + capMin?: number; + capMax?: number; + label?: string; + description?: string; +} + +/** + * Response-shape mapping for platforms without `definitions`: the response holds these five wait + * message settings flat under `languageId.autoSwitch`, while the keys use dotted prefixes. + */ +const FLAT_RESPONSE_PATHS: Record = { + "languageId.autoSwitch.waitMessage.mode": [ + "languageId", + "autoSwitch", + "waitMessageMode", + ], + "languageId.autoSwitch.waitMessage.skipWhenReady": [ + "languageId", + "autoSwitch", + "waitMessageSkipWhenReady", + ], + "languageId.autoSwitch.waitMessage.texts": [ + "languageId", + "autoSwitch", + "waitMessageTexts", + ], + "languageId.autoSwitch.readyMessage.minSwitchMs": [ + "languageId", + "autoSwitch", + "readyMessageMinSwitchMs", + ], + "languageId.autoSwitch.readyMessage.texts": [ + "languageId", + "autoSwitch", + "readyMessageTexts", + ], +}; + +const U32_MAX = 4294967295; + +function catalogDef(path: string | null): VoiceAgentSettingDef | undefined { + if (!path || !Object.hasOwn(VOICE_AGENT_SETTINGS, path)) { + return undefined; + } + return (VOICE_AGENT_SETTINGS as Record)[path]; +} + +function warnDisagreement(key: string, what: string): void { + logStep( + `warning: ${key}: the API ${what} differs from the voice engine catalog; using the catalog`, + ); +} + +function fromApiDefinition(api: VoiceAdvancedDefinition): ResolvedDef { + const engine = catalogDef(api.engineKey); + const base: ResolvedDef = { + key: api.key, + path: api.path, + type: api.type, + default: api.default, + label: api.label, + description: api.description, + }; + if (!engine) { + // A VoiceThere-only key: the API is the only source. + return { + ...base, + ...(api.integer !== undefined ? { integer: api.integer } : {}), + ...(api.enum ? { apiEnum: api.enum } : {}), + ...(api.min !== undefined ? { capMin: api.min } : {}), + ...(api.max !== undefined ? { capMax: api.max } : {}), + }; + } + + if (api.type !== engine.type) { + warnDisagreement(api.key, `type (${api.type})`); + } + if ( + api.type === "number" && + (api.integer ?? true) !== (engine.integer ?? true) + ) { + warnDisagreement(api.key, "integer flag"); + } + let apiEnum: readonly string[] | undefined; + if (api.enum) { + const extra = api.enum.filter((v) => !engine.enum?.includes(v)); + if (extra.length > 0 && engine.enum) { + warnDisagreement(api.key, `enum (${extra.join(", ")})`); + } + apiEnum = engine.enum + ? api.enum.filter((v) => engine.enum?.includes(v)) + : api.enum; + } + + return { + ...base, + type: engine.type, + ...(engine.integer !== undefined ? { integer: engine.integer } : {}), + ...(engine.enum ? { engineEnum: engine.enum } : {}), + ...(apiEnum ? { apiEnum } : {}), + ...(engine.min !== undefined ? { engineMin: engine.min } : {}), + ...(engine.max !== undefined ? { engineMax: engine.max } : {}), + ...(api.min !== undefined ? { capMin: api.min } : {}), + ...(api.max !== undefined ? { capMax: api.max } : {}), + }; +} + +/** Every setting in the response, in the API's order. Empty when the response has no `definitions`. */ +export function resolveDefinitions( + response: Pick, +): ResolvedDef[] { + return (response.definitions ?? []).map(fromApiDefinition); +} + +export function getValueAtPath( + source: Record | undefined, + path: readonly string[], +): unknown { + let current: unknown = source; + for (const part of path) { + if (!current || typeof current !== "object") { + return undefined; + } + current = (current as Record)[part]; + } + return current; +} + +export function responsePathForKey(key: string): string[] { + return FLAT_RESPONSE_PATHS[key] ?? key.split("."); +} + +/** + * For a platform without `definitions`: the type comes from the value in `defaults` at the key's + * path, and the engine facts from the catalog when the key is a catalog path. With neither, the + * value is sent as text and the server decides. + */ +export function fallbackDefinition( + key: string, + response: Pick, +): ResolvedDef { + const path = responsePathForKey(key); + const fromDefaults = getValueAtPath(response.defaults, path); + const fromSettings = getValueAtPath(response.settings, path); + const sample = fromDefaults ?? fromSettings; + const engine = catalogDef(key); + + const sampleType = + typeof sample === "boolean" || + typeof sample === "number" || + typeof sample === "string" + ? (typeof sample as "boolean" | "number" | "string") + : undefined; + const type = engine?.type ?? sampleType ?? "string"; + + return { + key, + path, + type, + default: fromDefaults, + // Without catalog facts a number may be fractional (`tts.speed`); the server checks it. + integer: engine?.integer ?? false, + ...(engine?.enum ? { engineEnum: engine.enum } : {}), + ...(engine?.min !== undefined ? { engineMin: engine.min } : {}), + ...(engine?.max !== undefined ? { engineMax: engine.max } : {}), + }; +} + +export function parseVoiceAdvancedValue( + def: ResolvedDef, + raw: string, +): boolean | number | string { + const { key } = def; + + if (def.type === "boolean") { + const normalized = raw.trim().toLowerCase(); + if (["true", "1", "yes", "on"].includes(normalized)) { + return true; + } + if (["false", "0", "no", "off"].includes(normalized)) { + return false; + } + throw new Error(`Invalid boolean for ${key}: use true or false`); + } + + if (def.type === "number") { + const n = raw.trim() === "" ? Number.NaN : Number(raw); + if (!Number.isFinite(n)) { + throw new Error(`Invalid number for ${key}`); + } + if (def.integer !== false && !Number.isInteger(n)) { + throw new Error(`${key} must be an integer`); + } + if ( + (def.engineMin !== undefined && n < def.engineMin) || + (def.engineMax !== undefined && n > def.engineMax) + ) { + throw new Error( + `${key} must be between ${def.engineMin ?? "-inf"} and ${def.engineMax ?? "inf"} (engine range)`, + ); + } + if ( + (def.capMin !== undefined && n < def.capMin) || + (def.capMax !== undefined && n > def.capMax) + ) { + throw new Error( + `${key} must be between ${def.capMin ?? "-inf"} and ${def.capMax ?? "inf"}`, + ); + } + return n; + } + + // Strings, including the JSON-text keys, are sent as given; the server validates them. + const trimmed = raw.trim(); + if (def.engineEnum && !def.engineEnum.includes(trimmed)) { + throw new Error(`${key} must be one of: ${def.engineEnum.join(", ")}`); + } + if (def.apiEnum && !def.apiEnum.includes(trimmed)) { + throw new Error(`${key} must be one of: ${def.apiEnum.join(", ")}`); + } + return trimmed; +} + +function flattenLeaves( + value: unknown, + prefix: string[], + out: Array<{ path: string[]; value: unknown }>, +): void { + if (value && typeof value === "object" && !Array.isArray(value)) { + const entries = Object.entries(value as Record); + if (entries.length > 0) { + for (const [k, v] of entries) { + flattenLeaves(v, [...prefix, k], out); + } + return; + } + } + out.push({ path: prefix, value }); +} + +/** Keys of a response without `definitions`, taken from `settings`. */ +export function keysFromSettings(settings: Record): string[] { + const leaves: Array<{ path: string[]; value: unknown }> = []; + flattenLeaves(settings, [], leaves); + const flatByPath = new Map( + Object.entries(FLAT_RESPONSE_PATHS).map(([key, path]) => [ + path.join("."), + key, + ]), + ); + return leaves + .map((l) => flatByPath.get(l.path.join(".")) ?? l.path.join(".")) + .filter((k) => k !== "debug.ttsTextTraceUntil"); +} + +export function formatVoiceAdvancedSettingLine( + settings: Record, + key: string, + path: readonly string[] = responsePathForKey(key), + fallbackValue?: unknown, +): string | null { + const value = getValueAtPath(settings, path) ?? fallbackValue; + if (value === undefined) { + return null; + } + if (key === "debug.ttsTextTrace" && value === true) { + const until = getValueAtPath(settings, ["debug", "ttsTextTraceUntil"]); + if (typeof until === "string" && until.length > 0) { + return `${key}=${String(value)} (on until ${until})`; + } + } + return `${key}=${String(value)}`; +} + +export function describeRange(def: ResolvedDef): string { + const min = def.capMin ?? def.engineMin; + const max = def.capMax ?? def.engineMax; + // The u32 type range of an integer key says nothing to a user. + if (def.capMax === undefined && max !== undefined && max >= U32_MAX) { + return ""; + } + if (def.type === "number" && min !== undefined && max !== undefined) { + return ` [${min}–${max}]`; + } + const values = def.apiEnum ?? def.engineEnum; + return values ? ` [${values.join("|")}]` : ""; +} + +export function voiceAdvancedSettingNamesHelp(): string { + return "run `voicethere projects voice-advanced list` for every key"; +} + +export function formatVoiceAdvancedSettingsGroupHelp(): string { + const lines = [ + "", + "Advanced voice pipeline settings apply on the next deploy.", + "Boolean values: true|false|1|0|yes|no|on|off.", + "", + "Voice engine settings (default in parentheses):", + ]; + + for (const path of VOICE_AGENT_SETTING_PATHS) { + const def = VOICE_AGENT_SETTINGS[path]; + lines.push( + ` ${path} (${String(def.default ?? "derived")})${describeRange( + fromEngine(path, def), + )}`, + ); + } + + lines.push(""); + lines.push( + "Project defaults, VoiceThere-only keys and descriptions come from the platform:", + ); + lines.push(" $ voicethere projects voice-advanced list"); + lines.push(""); + lines.push("Examples:"); + lines.push( + " $ voicethere projects voice-advanced set vad.bargeIn.requireSttPartial false", + ); + lines.push(" $ voicethere projects voice-advanced set tts.speed 0.9"); + lines.push(" $ voicethere projects voice-advanced set tts.sentenceCase off"); + lines.push( + " $ voicethere projects voice-advanced set debug.ttsTextTrace on", + ); + lines.push( + ' $ voicethere projects voice-advanced set voice.profilesByLanguage \'{"de":{"stt":"de","tts":"de-thorsten-high"}}\'', + ); + lines.push( + " $ voicethere projects voice-advanced set languageId.autoSwitch.enabled true", + ); + lines.push(" $ voicethere projects voice-advanced reset"); + + return lines.join("\n"); +} + +function fromEngine(path: string, def: VoiceAgentSettingDef): ResolvedDef { + return { + key: path, + path: path.split("."), + type: def.type, + ...(def.enum ? { engineEnum: def.enum } : {}), + ...(def.min !== undefined ? { engineMin: def.min } : {}), + ...(def.max !== undefined ? { engineMax: def.max } : {}), + }; +} diff --git a/src/commands/projects/voice-advanced/defs.ts b/src/commands/projects/voice-advanced/defs.ts deleted file mode 100644 index b95de0d..0000000 --- a/src/commands/projects/voice-advanced/defs.ts +++ /dev/null @@ -1,658 +0,0 @@ -/** - * Keep in step with the platform (`platform/src/lib/voice/language-switch-wait-messages.ts`): - * same default texts, 300 character limit and ISO 639-1 keys. The server validates the - * languages and model ids; the CLI checks the shape so mistakes fail before the request. - */ -const WAIT_MESSAGE_MAX_CHARS = 300; -const DEFAULT_WAIT_MESSAGES_JSON = JSON.stringify({ - de: "Einen Moment bitte, ich wechsle auf {language}.", - en: "One moment, switching to {language}.", - es: "Un momento, por favor, cambio al {language}.", - fr: "Un instant, je passe en {language}.", - it: "Un momento, cambio lingua: {language}.", - nl: "Een moment, ik schakel over naar het {language}.", - pl: "Chwileczkę, przełączam na język: {language}.", - pt: "Um momento, vou mudar para {language}.", - ru: "Одну минуту, переключаюсь на {language}.", -}); - -/** - * Lockstep with platform `src/lib/voice/voice-advanced-settings.ts`; checked by platform CI - * `cli-voice-advanced-lockstep` (`scripts/check-cli-voice-advanced-lockstep.ts`) against this file - * on `main`. Merge the CLI side first when adding a key. - */ -export const VOICE_ADVANCED_SETTING_KEYS = [ - "vad.enabled", - "vad.provider", - "vad.adaptive.noiseMarginDb", - "vad.adaptive.useSpeechLevel", - "vad.adaptive.stuckActiveMs", - "vad.threshold", - "vad.minSpeechDurationMs", - "vad.minSilenceDurationMs", - "vad.speechPadMs", - "vad.sampleRate", - "vad.gateStt", - "vad.gateSttOpenOnPending", - "vad.sttGateHoldMs", - "vad.sttListenTimeoutMs", - "vad.utteranceFinalizeTimeoutMs", - "vad.bargeIn.enabled", - "vad.bargeIn.useVad", - "vad.bargeIn.flushTts", - "vad.bargeIn.requireSttPartial", - "vad.bargeIn.minSttPartialChars", - "vad.bargeIn.agentPlaybackGuardMs", - "tts.speed", - "tts.postUtteranceSilenceMs", - "tts.phraseCache", - "tts.sentenceCase", - "debug.ttsTextTrace", - "connection.reconnectWindowSec", - "noiseSuppression.enabled", - "languageId.enabled", - "languageId.minSpeechMs", - "languageId.timing", - "languageId.autoSwitch.enabled", - "languageId.autoSwitch.replayLastUtterance", - "languageId.autoSwitch.finalHoldMs", - "languageId.autoSwitch.minDwellMs", - "languageId.autoSwitch.confirmUtterances", - "languageId.autoSwitch.switchVoice", - "languageId.autoSwitch.waitAudio", - "languageId.autoSwitch.waitMessage.mode", - "languageId.autoSwitch.waitMessage.skipWhenReady", - "languageId.autoSwitch.waitMessage.texts", - "languageId.autoSwitch.readyMessage.minSwitchMs", - "languageId.autoSwitch.readyMessage.texts", - "voice.allowedLanguages", - "voice.profilesByLanguage", - "speakerGate.mode", - "speakerGate.bargeIn", - "speakerGate.suppressShortBargeIn", - "events.mode", -] as const; - -export type VoiceAdvancedSettingKey = - (typeof VOICE_ADVANCED_SETTING_KEYS)[number]; - -export const VOICE_ADVANCED_SETTING_DEFS: Record< - VoiceAdvancedSettingKey, - { - type: "boolean" | "number" | "string"; - default: boolean | number | string; - min?: number; - max?: number; - enum?: readonly string[]; - description: string; - } -> = { - "vad.enabled": { - type: "boolean", - default: true, - description: "Master switch for voice activity detection.", - }, - "vad.provider": { - type: "string", - default: "energy", - enum: ["energy", "adaptive"], - description: - "VAD provider: energy (fixed RMS threshold) or adaptive (threshold follows the noise floor and the caller's level).", - }, - "vad.adaptive.noiseMarginDb": { - type: "number", - default: 6, - min: 0, - max: 30, - description: - "Adaptive VAD: dB above the measured noise floor that counts as speech. Only used with vad.provider adaptive.", - }, - "vad.adaptive.useSpeechLevel": { - type: "boolean", - default: true, - description: - "Adaptive VAD: raise the threshold toward the caller's own speech level. Only used with vad.provider adaptive.", - }, - "vad.adaptive.stuckActiveMs": { - type: "number", - default: 8000, - min: 1000, - max: 60000, - description: - "Adaptive VAD: re-measure the noise floor when speech stays active this long without a pause. Only used with vad.provider adaptive.", - }, - "vad.threshold": { - type: "number", - default: 0.15, - min: 0.001, - max: 1, - description: "VAD sensitivity threshold.", - }, - "vad.minSpeechDurationMs": { - type: "number", - default: 250, - min: 50, - max: 5000, - description: "Minimum voiced duration before speech start.", - }, - "vad.minSilenceDurationMs": { - type: "number", - default: 1100, - min: 100, - max: 10000, - description: "Silence duration before speech end.", - }, - "vad.speechPadMs": { - type: "number", - default: 1000, - min: 0, - max: 3000, - description: "STT pre-roll pad in milliseconds.", - }, - "vad.sampleRate": { - type: "string", - default: "16000", - enum: ["8000", "16000"], - description: "Internal VAD sample rate.", - }, - "vad.gateStt": { - type: "boolean", - default: true, - description: "Gate STT to open windows only.", - }, - "vad.gateSttOpenOnPending": { - type: "boolean", - default: true, - description: "Feed STT during VAD pending speech.", - }, - "vad.sttGateHoldMs": { - type: "number", - default: 400, - min: 0, - max: 10000, - description: "Keep STT open after speech end.", - }, - "vad.sttListenTimeoutMs": { - type: "number", - default: 4000, - min: 500, - max: 30000, - description: "Timeout when no STT partial after VAD trigger.", - }, - "vad.utteranceFinalizeTimeoutMs": { - type: "number", - default: 1500, - min: 200, - max: 10000, - description: "Grace before forcing user_speech_final.", - }, - "vad.bargeIn.enabled": { - type: "boolean", - default: true, - description: "Enable barge-in (stop agent TTS on interrupt).", - }, - "vad.bargeIn.useVad": { - type: "boolean", - default: true, - description: "Use VAD to trigger barge-in automatically.", - }, - "vad.bargeIn.flushTts": { - type: "boolean", - default: true, - description: "Clear pending TTS on barge-in.", - }, - "vad.bargeIn.requireSttPartial": { - type: "boolean", - default: true, - description: "Require STT partial before barge-in during agent TTS.", - }, - "vad.bargeIn.minSttPartialChars": { - type: "number", - default: 2, - min: 1, - max: 32, - description: "Minimum partial length for semantic barge-in.", - }, - "vad.bargeIn.agentPlaybackGuardMs": { - type: "number", - default: 0, - min: 0, - max: 5000, - description: "Ignore VAD barge-in briefly after TTS starts.", - }, - "tts.speed": { - type: "number", - default: 0.9, - min: 0.2, - max: 2, - description: - "Piper speaking-rate multiplier for VoiceThere TTS (1.0 = model default).", - }, - "tts.postUtteranceSilenceMs": { - type: "number", - default: 2550, - min: 0, - max: 15000, - description: - "Silent PCM after each TTS utterance so remote listeners can finalize STT.", - }, - "tts.phraseCache": { - type: "boolean", - default: true, - description: - "Runner TTS phrase cache: repeated replies are served from memory on the runner instead of being synthesised again. On by default.", - }, - "tts.sentenceCase": { - type: "string", - default: "auto", - enum: ["auto", "off"], - description: - "Uppercase the first letter after . ! ? in the text sent to the voice engine so periods become sentence breaks (pause, earlier first audio). Your text is not changed anywhere else. auto (default) or off.", - }, - "debug.ttsTextTrace": { - type: "boolean", - default: false, - description: - "Write the text sent to the voice engine into your agent logs, one line per reply. Switches off automatically 24 hours after you turn it on; applies on the next deploy.", - }, - "connection.reconnectWindowSec": { - type: "number", - default: 15, - min: 15, - max: 30, - description: - "Reconnect window in whole seconds (15-30): how long a dropped voice conversation is held for the client to reconnect. A recovered conversation is billed including the interruption. An unrecovered one stops billing at the drop but holds an agent runner slot for the window.", - }, - "noiseSuppression.enabled": { - type: "boolean", - default: true, - description: - "Applies Xiph RNNoise to inbound PCM before VAD and STT on voice runners.", - }, - "languageId.enabled": { - type: "boolean", - default: true, - description: - "Enable spoken language identification (VoiceThere Whisper tiny) on voice deploys.", - }, - "languageId.minSpeechMs": { - type: "number", - default: 1500, - min: 1000, - max: 5000, - description: - "Minimum inbound PCM (ms) before first spoken-language identify per utterance (cloud default 1500). Shorter utterances skip language ID.", - }, - "languageId.timing": { - type: "string", - default: "early", - enum: ["early", "end_of_utterance", "continuous"], - description: - "When to identify the spoken language: early (once, as soon as minSpeechMs is buffered, while the caller talks), end_of_utterance (once, after the caller stops) or continuous (repeated passes; most CPU, turn off if agent audio gets choppy).", - }, - "languageId.autoSwitch.enabled": { - type: "boolean", - default: false, - description: - "Auto-switch STT/TTS when LID disagrees with session language (default off; requires languageId.enabled). Requires VoiceThere (voicethere) for both speech-to-text and text-to-speech.", - }, - "languageId.autoSwitch.replayLastUtterance": { - type: "boolean", - default: true, - description: "Replay inbound PCM after STT swap when auto-switch is on.", - }, - "languageId.autoSwitch.finalHoldMs": { - type: "number", - default: 5000, - min: 0, - max: 10_000, - description: - "Max ms to hold user_speech_final while waiting for user_language.", - }, - "languageId.autoSwitch.minDwellMs": { - type: "number", - default: 10_000, - min: 0, - max: 60_000, - description: - "Ignore LID flips for this long after a committed auto-switch.", - }, - "languageId.autoSwitch.confirmUtterances": { - type: "number", - default: 1, - min: 1, - max: 3, - description: - "Consecutive user_language events required before auto-switch.", - }, - "languageId.autoSwitch.switchVoice": { - type: "boolean", - default: true, - description: "Switch TTS as well as STT on auto-switch (false = STT only).", - }, - "languageId.autoSwitch.waitAudio": { - type: "string", - default: "buffer_replay", - enum: ["buffer_replay", "first_utterance"], - description: - "Speech kept while the new language loads: buffer_replay replays everything said during the wait, first_utterance replays only the utterance that triggered language ID.", - }, - "languageId.autoSwitch.waitMessage.mode": { - type: "string", - default: "end_of_utterance", - enum: ["end_of_utterance", "immediate", "off"], - description: - "Whether the switch may interrupt the caller: end_of_utterance (default) waits until the caller stops, immediate speaks at once and cannot be interrupted, off plays no wait message.", - }, - "languageId.autoSwitch.waitMessage.skipWhenReady": { - type: "boolean", - default: true, - description: - "Skip the wait message when the target language is already running.", - }, - "languageId.autoSwitch.waitMessage.texts": { - type: "string", - default: DEFAULT_WAIT_MESSAGES_JSON, - description: - 'JSON map of ISO 639-1 code to wait text (max 300 chars each), spoken in the language being left, e.g. {"en":"One moment, switching to your language."}.', - }, - "languageId.autoSwitch.readyMessage.minSwitchMs": { - type: "number", - default: 2000, - min: 0, - max: 15_000, - description: - "Play a short 'Okay, let's continue in .' in the new voice when a language switch took at least this long and no wait message was played. 0 turns it off.", - }, - "languageId.autoSwitch.readyMessage.texts": { - type: "string", - default: "{}", - description: - 'Per-language ready message text, e.g. {"de":"Okay, machen wir auf Deutsch weiter."}. Unset languages use the built-in text.', - }, - "voice.allowedLanguages": { - type: "string", - default: "", - description: - "Allowed languages for setVoiceLanguage / LID auto-switch (* = any for agent API). Empty = boot language plus the languages in voice.profilesByLanguage.", - }, - "voice.profilesByLanguage": { - type: "string", - default: "{}", - description: - 'STT/TTS model per language used after a switch, as JSON, e.g. {"de":{"stt":"de","tts":"de-thorsten-high"}}.', - }, - "speakerGate.mode": { - type: "string", - default: "disabled", - enum: ["disabled", "auto", "manual"], - description: - "Speaker gate: disabled (every utterance reaches your agent), auto (only the enrolled caller does; other voices arrive as user_speech_ignored), manual (every utterance reaches your agent with a speaker label).", - }, - "speakerGate.bargeIn": { - type: "string", - default: "caller_only", - enum: ["caller_only", "anyone"], - description: - "Who can interrupt the agent: caller_only or anyone. No effect while speakerGate.mode is disabled.", - }, - "speakerGate.suppressShortBargeIn": { - type: "boolean", - default: false, - description: - "Do not let speech too short to check interrupt the agent. No effect while speakerGate.mode is disabled.", - }, - "events.mode": { - type: "string", - default: "both", - enum: ["callback", "stream", "both"], - description: "Speech event delivery mode.", - }, -}; - -const SETTING_NAMES_HELP = VOICE_ADVANCED_SETTING_KEYS.join(" | "); - -export function voiceAdvancedSettingNamesHelp(): string { - return SETTING_NAMES_HELP; -} - -export function formatVoiceAdvancedSettingsGroupHelp(): string { - const lines = [ - "", - "Advanced voice pipeline settings apply on the next deploy.", - "Boolean values: true|false|1|0|yes|no|on|off.", - "", - "Keys (default in parentheses):", - ]; - - for (const key of VOICE_ADVANCED_SETTING_KEYS) { - const def = VOICE_ADVANCED_SETTING_DEFS[key]; - const range = - def.type === "number" && def.min !== undefined && def.max !== undefined - ? ` [${def.min}–${def.max}]` - : ""; - lines.push(` ${key} (${String(def.default)})${range}`); - lines.push(` ${def.description}`); - } - - lines.push(""); - lines.push("Examples:"); - lines.push(" $ voicethere projects voice-advanced list"); - lines.push( - " $ voicethere projects voice-advanced set vad.bargeIn.requireSttPartial false", - ); - lines.push(" $ voicethere projects voice-advanced set tts.speed 0.9"); - lines.push(" $ voicethere projects voice-advanced set tts.sentenceCase off"); - lines.push( - " $ voicethere projects voice-advanced set debug.ttsTextTrace on", - ); - lines.push( - ' $ voicethere projects voice-advanced set voice.profilesByLanguage \'{"de":{"stt":"de","tts":"de-thorsten-high"}}\'', - ); - lines.push( - " $ voicethere projects voice-advanced set languageId.autoSwitch.enabled true", - ); - lines.push( - " $ voicethere projects voice-advanced set languageId.autoSwitch.waitMessage.mode immediate", - ); - lines.push( - ' $ voicethere projects voice-advanced set languageId.autoSwitch.waitMessage.texts \'{"en":"One moment, switching to your language."}\'', - ); - lines.push(" $ voicethere projects voice-advanced reset"); - - return lines.join("\n"); -} - -const ISO_LANG_RE = /^[a-z]{2}$/; - -function parseJsonObject(key: string, raw: string): Record { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - throw new Error(`${key} must be a valid JSON object`); - } - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - throw new Error(`${key} must be a JSON object keyed by language code`); - } - return parsed as Record; -} - -function validateWaitMessageTexts( - raw: string, - key = "languageId.autoSwitch.waitMessage.texts", -): string { - const obj = parseJsonObject(key, raw || "{}"); - for (const [lang, text] of Object.entries(obj)) { - if (!ISO_LANG_RE.test(lang)) { - throw new Error( - `${key}: invalid language key "${lang}" (use ISO 639-1, e.g. en)`, - ); - } - if (typeof text !== "string" || !text.trim()) { - throw new Error(`${key}.${lang} must be a non-empty string`); - } - if ([...text.trim()].length > WAIT_MESSAGE_MAX_CHARS) { - throw new Error( - `${key}.${lang} must be at most ${WAIT_MESSAGE_MAX_CHARS} characters`, - ); - } - } - return raw || "{}"; -} - -function validateProfilesByLanguage(raw: string): string { - const key = "voice.profilesByLanguage"; - const obj = parseJsonObject(key, raw || "{}"); - for (const [lang, entry] of Object.entries(obj)) { - if (!ISO_LANG_RE.test(lang)) { - throw new Error( - `${key}: invalid language key "${lang}" (use ISO 639-1, e.g. en)`, - ); - } - if (!entry || typeof entry !== "object" || Array.isArray(entry)) { - throw new Error(`${key}.${lang} must be an object`); - } - const row = entry as Record; - for (const field of ["stt", "tts", "voice", "sttVendor", "ttsVendor"]) { - if (row[field] !== undefined && typeof row[field] !== "string") { - throw new Error(`${key}.${lang}.${field} must be a string`); - } - } - if (Object.keys(row).length === 0) { - throw new Error(`${key}.${lang} is empty`); - } - } - return raw || "{}"; -} - -export function parseVoiceAdvancedSettingValue( - key: VoiceAdvancedSettingKey, - raw: string, -): boolean | number | string { - const def = VOICE_ADVANCED_SETTING_DEFS[key]; - - if (def.type === "string") { - const trimmed = raw.trim(); - if (def.enum && !def.enum.includes(trimmed)) { - throw new Error(`${key} must be one of: ${def.enum.join(", ")}`); - } - if (key === "languageId.autoSwitch.waitMessage.texts") { - return validateWaitMessageTexts(trimmed); - } - if (key === "languageId.autoSwitch.readyMessage.texts") { - return validateWaitMessageTexts(trimmed, key); - } - if (key === "voice.profilesByLanguage") { - return validateProfilesByLanguage(trimmed); - } - return trimmed; - } - - if (def.type === "boolean") { - const normalized = raw.trim().toLowerCase(); - if ( - normalized === "true" || - normalized === "1" || - normalized === "yes" || - normalized === "on" - ) { - return true; - } - if ( - normalized === "false" || - normalized === "0" || - normalized === "no" || - normalized === "off" - ) { - return false; - } - throw new Error(`Invalid boolean for ${key}: use true or false`); - } - - const n = Number(raw); - if (!Number.isFinite(n)) { - throw new Error(`Invalid number for ${key}`); - } - if (key === "connection.reconnectWindowSec" && !Number.isInteger(n)) { - throw new Error(`${key} must be an integer`); - } - const min = def.min ?? 0; - const max = def.max ?? Number.MAX_SAFE_INTEGER; - if (n < min || n > max) { - throw new Error(`${key} must be between ${min} and ${max}`); - } - const keepFractional = - key === "vad.threshold" || - key === "tts.speed" || - key === "vad.adaptive.noiseMarginDb"; - return def.type === "number" && keepFractional ? n : Math.floor(n); -} - -/** - * The API returns the wait message settings flat under `languageId.autoSwitch` - * (`waitMessageMode`, `readyMessageMinSwitchMs`), while the setting keys use dotted `waitMessage.` / `readyMessage.` prefixes. - */ -const RESOLVED_PATH_OVERRIDES: Partial< - Record -> = { - "languageId.autoSwitch.waitMessage.mode": [ - "languageId", - "autoSwitch", - "waitMessageMode", - ], - "languageId.autoSwitch.waitMessage.skipWhenReady": [ - "languageId", - "autoSwitch", - "waitMessageSkipWhenReady", - ], - "languageId.autoSwitch.waitMessage.texts": [ - "languageId", - "autoSwitch", - "waitMessageTexts", - ], - "languageId.autoSwitch.readyMessage.minSwitchMs": [ - "languageId", - "autoSwitch", - "readyMessageMinSwitchMs", - ], - "languageId.autoSwitch.readyMessage.texts": [ - "languageId", - "autoSwitch", - "readyMessageTexts", - ], -}; - -function getNestedValue( - settings: Record, - key: VoiceAdvancedSettingKey | "debug.ttsTextTraceUntil", -): unknown { - const parts = - (RESOLVED_PATH_OVERRIDES as Record)[key] ?? - key.split("."); - let current: unknown = settings; - for (const part of parts) { - if (!current || typeof current !== "object") { - return undefined; - } - current = (current as Record)[part]; - } - return current; -} - -export function formatVoiceAdvancedSettingLine( - settings: Record, - key: VoiceAdvancedSettingKey, -): string | null { - const value = getNestedValue(settings, key); - if (value === undefined) { - return null; - } - if (key === "debug.ttsTextTrace" && value === true) { - const until = getNestedValue(settings, "debug.ttsTextTraceUntil"); - if (typeof until === "string" && until.length > 0) { - return `${key}=${String(value)} (on until ${until})`; - } - } - return `${key}=${String(value)}`; -} diff --git a/src/commands/projects/voice-advanced/list.ts b/src/commands/projects/voice-advanced/list.ts index 9d3acde..e03d980 100644 --- a/src/commands/projects/voice-advanced/list.ts +++ b/src/commands/projects/voice-advanced/list.ts @@ -3,10 +3,11 @@ import { createApiFromCredentials } from "../../../lib/control-plane-auth.js"; import { requireCredentials } from "../../../lib/config.js"; import { requireProjectId } from "../../../lib/project-config.js"; import { + describeRange, formatVoiceAdvancedSettingLine, - VOICE_ADVANCED_SETTING_KEYS, - type VoiceAdvancedSettingKey, -} from "./defs.js"; + keysFromSettings, + resolveDefinitions, +} from "./definitions.js"; export interface ProjectsVoiceAdvancedListOptions { projectId?: string; @@ -21,14 +22,32 @@ export async function runProjectsVoiceAdvancedList( const credentials = await requireCredentials(); const api = createApiFromCredentials(credentials); const result = await api.listProjectVoiceAdvancedSettings(projectId); - logVerbose(`found ${VOICE_ADVANCED_SETTING_KEYS.length} setting key(s)`); - for (const key of VOICE_ADVANCED_SETTING_KEYS) { + if (result.definitions) { + const defs = resolveDefinitions(result); + logVerbose(`found ${defs.length} setting key(s)`); + for (const def of defs) { + const line = formatVoiceAdvancedSettingLine( + result.settings, + def.key, + def.path, + def.default, + ); + if (line) { + console.log( + `${line} (default ${String(def.default)}${describeRange(def)})`, + ); + } + } + return; + } + + const keys = keysFromSettings(result.settings); + logVerbose(`found ${keys.length} setting key(s)`); + for (const key of keys) { const line = formatVoiceAdvancedSettingLine(result.settings, key); if (line) { console.log(line); } } } - -export { VOICE_ADVANCED_SETTING_KEYS, type VoiceAdvancedSettingKey }; diff --git a/src/commands/projects/voice-advanced/set.ts b/src/commands/projects/voice-advanced/set.ts index f570edb..ea8a008 100644 --- a/src/commands/projects/voice-advanced/set.ts +++ b/src/commands/projects/voice-advanced/set.ts @@ -3,10 +3,10 @@ import { createApiFromCredentials } from "../../../lib/control-plane-auth.js"; import { requireCredentials } from "../../../lib/config.js"; import { requireProjectId } from "../../../lib/project-config.js"; import { - parseVoiceAdvancedSettingValue, - VOICE_ADVANCED_SETTING_KEYS, - type VoiceAdvancedSettingKey, -} from "./defs.js"; + fallbackDefinition, + parseVoiceAdvancedValue, + resolveDefinitions, +} from "./definitions.js"; export interface ProjectsVoiceAdvancedSetOptions { name: string; @@ -18,18 +18,29 @@ export async function runProjectsVoiceAdvancedSet( options: ProjectsVoiceAdvancedSetOptions, ): Promise { const projectId = options.projectId?.trim() || (await requireProjectId()); - const key = options.name.trim() as VoiceAdvancedSettingKey; - if (!VOICE_ADVANCED_SETTING_KEYS.includes(key)) { - throw new Error( - `Unknown voice advanced setting ${key}. Valid: ${VOICE_ADVANCED_SETTING_KEYS.join(", ")}`, - ); - } - - const value = parseVoiceAdvancedSettingValue(key, options.value); + const key = options.name.trim(); logStep(`Setting ${key} for project ${projectId}`); const credentials = await requireCredentials(); const api = createApiFromCredentials(credentials); + const response = await api.listProjectVoiceAdvancedSettings(projectId); + + let def; + if (response.definitions) { + def = resolveDefinitions(response).find((d) => d.key === key); + if (!def) { + throw new Error( + `Unknown voice advanced setting ${key}. Valid: ${response.definitions.map((d) => d.key).join(", ")}`, + ); + } + } else { + logVerbose( + "platform returned no definitions; typing the value from defaults", + ); + def = fallbackDefinition(key, response); + } + + const value = parseVoiceAdvancedValue(def, options.value); await api.setProjectVoiceAdvancedSetting(projectId, key, value); console.log(`${key}=${String(value)}`); } diff --git a/src/lib/api.ts b/src/lib/api.ts index 106b64d..cbcf1a1 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -672,61 +672,33 @@ export interface ProjectVoiceSettings { tts_voice?: string; } -export type VoiceAdvancedSettingKey = - | "vad.enabled" - | "vad.provider" - | "vad.adaptive.noiseMarginDb" - | "vad.adaptive.useSpeechLevel" - | "vad.adaptive.stuckActiveMs" - | "vad.threshold" - | "vad.minSpeechDurationMs" - | "vad.minSilenceDurationMs" - | "vad.speechPadMs" - | "vad.sampleRate" - | "vad.gateStt" - | "vad.gateSttOpenOnPending" - | "vad.sttGateHoldMs" - | "vad.sttListenTimeoutMs" - | "vad.utteranceFinalizeTimeoutMs" - | "vad.bargeIn.enabled" - | "vad.bargeIn.useVad" - | "vad.bargeIn.flushTts" - | "vad.bargeIn.requireSttPartial" - | "vad.bargeIn.minSttPartialChars" - | "vad.bargeIn.agentPlaybackGuardMs" - | "tts.speed" - | "tts.postUtteranceSilenceMs" - | "tts.phraseCache" - | "tts.sentenceCase" - | "debug.ttsTextTrace" - | "connection.reconnectWindowSec" - | "speakerGate.mode" - | "speakerGate.bargeIn" - | "speakerGate.suppressShortBargeIn" - | "events.mode" - | "noiseSuppression.enabled" - | "languageId.enabled" - | "languageId.minSpeechMs" - | "languageId.timing" - | "languageId.autoSwitch.enabled" - | "languageId.autoSwitch.replayLastUtterance" - | "languageId.autoSwitch.finalHoldMs" - | "languageId.autoSwitch.minDwellMs" - | "languageId.autoSwitch.confirmUtterances" - | "languageId.autoSwitch.switchVoice" - | "languageId.autoSwitch.waitAudio" - | "languageId.autoSwitch.waitMessage.mode" - | "languageId.autoSwitch.waitMessage.skipWhenReady" - | "languageId.autoSwitch.waitMessage.texts" - | "languageId.autoSwitch.readyMessage.minSwitchMs" - | "languageId.autoSwitch.readyMessage.texts" - | "voice.allowedLanguages" - | "voice.profilesByLanguage"; +/** A voice-advanced setting key such as `vad.threshold`; the valid keys come from the API. */ +export type VoiceAdvancedSettingKey = string; + +/** One entry of `definitions` in the voice-advanced-settings response. */ +export interface VoiceAdvancedDefinition { + key: string; + /** Where `overrides`, `settings` and `defaults` hold this key. */ + path: string[]; + type: "boolean" | "number" | "string"; + default: boolean | number | string; + min?: number; + max?: number; + integer?: boolean; + enum?: string[]; + label: string; + description: string; + /** Voice engine config path, or null for a VoiceThere-only key. */ + engineKey: string | null; +} export interface ProjectVoiceAdvancedSettingsResponse { project_id: string; settings: Record; overrides?: Record; + defaults?: Record; + /** Absent on platforms that predate the field. */ + definitions?: VoiceAdvancedDefinition[]; } export interface VoiceCatalogModel {