From 45d72e0145ddb48c484365cbac18355572ab05ff Mon Sep 17 00:00:00 2001 From: Fede Ciliberti Date: Sat, 31 Oct 2026 17:11:22 -0300 Subject: [PATCH] feat(normalize): allow a separate model/endpoint for normalization Normalization is the cheap pass: STT cleanup after transcription and markdown -> spoken text before TTS. It reused the main endpoint/model, so a large answering model was also doing the normalization. Route both stages through a new createNormalizer() that reads normalizeModel, normalizeEndpoint and normalizeApiKeyEnv, each defaulting to its main counterpart, and expose normalize: false to skip the pass entirely (the STT pipeline already falls back to the raw transcript when normalization fails). Default behaviour is unchanged when no normalize* option is set. --- AGENTS.md | 4 +++ README.md | 24 +++++++++++++ index.js | 4 +-- lib/normalize.js | 44 +++++++++++++++++++++++ test/normalize.test.js | 82 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 lib/normalize.js create mode 100644 test/normalize.test.js diff --git a/AGENTS.md b/AGENTS.md index d9d71c4..2a20060 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,10 @@ Single TUI plugin exported from `index.js` with logic split into `lib/`. - Single TUI plugin via `Plugin.define` from `@opencode/plugin/tui`; `setup` returns a cleanup that detaches the data listeners. No server-side plugin. - LLM calls use the OpenAI chat completions API, not the Anthropic messages API. +- Normalization (STT cleanup and TTS markdown conversion) goes through + `createNormalizer` in `lib/normalize.js`; `normalizeModel` / + `normalizeEndpoint` / `normalizeApiKeyEnv` can point it at a different model + than the one answering, and `normalize: false` disables the pass entirely. - Configuration uses `options` (static) and the storage-backed `api.kv` (runtime). No dotfile I/O. - Auto TTS triggers on `session.execution.started` / `succeeded` / diff --git a/README.md b/README.md index 1146a9e..13b0418 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,26 @@ For unauthenticated local endpoints (e.g. Ollama): } ``` +To normalize with a smaller model than the one answering — both normalization +stages (STT cleanup and TTS markdown conversion) share this client, so they use +the same `normalize*` settings: + +```json +{ + "plugins": [ + { + "package": "@renjfk/opencode-voice", + "options": { + "endpoint": "https://api.anthropic.com/v1", + "model": "claude-sonnet-4-6", + "apiKeyEnv": "ANTHROPIC_API_KEY", + "normalizeModel": "claude-haiku-4-5" + } + } + ] +} +``` + - `endpoint` _(required)_ - OpenAI-compatible base URL - `model` _(required)_ - model name sent to `/chat/completions` - `apiKeyEnv` _(optional)_ - environment variable containing the API key @@ -278,6 +298,10 @@ For unauthenticated local endpoints (e.g. Ollama): - `retries` _(optional)_ - number of retry attempts for transient LLM failures - `tmpDir` _(optional)_ - directory used for the temporary STT recording file (default `/tmp`) - `sttLanguage` _(optional)_ - spoken language passed to local `whisper-cli -l` (default `auto`; any whisper.cpp language code, e.g. `en`, `zh`). Can be changed at runtime via `/stt-language` +- `normalize` _(optional)_ - set to `false` to skip the normalization pass and use the raw transcription (STT) or the unprocessed response (TTS) instead (default `true`) +- `normalizeModel` _(optional)_ - model used for normalization calls (default: `model`), so a small/cheap model can normalize while a larger one answers +- `normalizeEndpoint` _(optional)_ - OpenAI-compatible base URL used for normalization calls (default: `endpoint`) +- `normalizeApiKeyEnv` _(optional)_ - environment variable holding the API key for `normalizeEndpoint` (default: `apiKeyEnv`) - `trimSilence` _(optional)_ - whether to remove leading silence from recordings (default `true`). Set to `false` if your recordings are missing the first word or syllable ### Logging diff --git a/index.js b/index.js index aa2007e..cbbea89 100644 --- a/index.js +++ b/index.js @@ -40,7 +40,7 @@ import os from "node:os"; import { Plugin } from "@opencode/plugin/tui"; import { registerSTT } from "./lib/stt.js"; import { registerTTS } from "./lib/tts.js"; -import { createClient } from "./lib/llm-client.js"; +import { createNormalizer } from "./lib/normalize.js"; import { createLogger } from "./lib/logger.js"; function loadPromptFile(filePath, logger, name) { @@ -252,7 +252,7 @@ export default Plugin.define({ const options = context.options; const logger = createLogger(); logger.log("plugin", "Initializing", "debug"); - const { complete } = createClient(options, logger); + const { complete } = createNormalizer(options, logger); const prompts = { stt: loadPromptFile(options?.sttPrompt, logger, "STT"), diff --git a/lib/normalize.js b/lib/normalize.js new file mode 100644 index 0000000..3899355 --- /dev/null +++ b/lib/normalize.js @@ -0,0 +1,44 @@ +// Normalization client: lets the normalizing model differ from the main one. +// +// Every normalization call (STT cleanup after transcription, TTS markdown -> +// spoken text) goes through this client, so a small/cheap model can normalize +// while a larger model answers. With no `normalize*` option set it reuses the +// main endpoint/model/apiKeyEnv, so the default behaviour is unchanged. +// +// Options (plugin options in cli.json / opencode.json): +// normalize: true|false (default true) +// normalizeModel: string (default: model) +// normalizeEndpoint: string (default: endpoint) +// normalizeApiKeyEnv: string (default: apiKeyEnv) + +import { createClient } from "./llm-client.js"; + +/** + * Create the completion function used for text normalization. + * + * @param {object} [pluginOptions] - Static config from plugin options + * @param {{ log?: (scope: string, message: string, level?: string) => void }} [logger] + * @returns {{ complete: (opts: object) => Promise<{ text: string | null, error?: string }>, enabled: boolean }} + */ +export function createNormalizer(pluginOptions, logger) { + const options = pluginOptions ?? {}; + const enabled = options.normalize !== false; + const endpoint = options.normalizeEndpoint ?? options.endpoint; + const model = options.normalizeModel ?? options.model; + const apiKeyEnv = options.normalizeApiKeyEnv ?? options.apiKeyEnv; + + const client = createClient({ ...options, endpoint, model, apiKeyEnv }, logger); + + logger?.log?.( + "LLM", + `normalizer configured enabled=${enabled} model=${model ?? "-"} endpoint=${endpoint ?? "-"}`, + "debug", + ); + + async function complete(opts) { + if (!enabled) return { text: null, error: "normalization disabled" }; + return client.complete(opts); + } + + return { complete, enabled }; +} diff --git a/test/normalize.test.js b/test/normalize.test.js new file mode 100644 index 0000000..a5945ca --- /dev/null +++ b/test/normalize.test.js @@ -0,0 +1,82 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { createNormalizer } from "../lib/normalize.js"; + +function withFetch(handler, run) { + const original = globalThis.fetch; + globalThis.fetch = handler; + return run().finally(() => { + globalThis.fetch = original; + }); +} + +function captureRequest() { + const captured = { body: null, url: null }; + const handler = async (url, opts) => { + captured.url = url; + captured.body = JSON.parse(opts.body); + return new Response(JSON.stringify({ choices: [{ message: { content: "ok" } }] }), { + status: 200, + }); + }; + return { captured, handler }; +} + +test("normalize: disabled -> no llama al LLM y devuelve 'normalization disabled'", async () => { + let called = 0; + await withFetch( + async () => { + called++; + return new Response("{}", { status: 200 }); + }, + async () => { + const { complete, enabled } = createNormalizer({ + normalize: false, + endpoint: "http://x/v1", + model: "m", + }); + assert.equal(enabled, false); + const res = await complete({ prompt: "hola" }); + assert.equal(res.text, null); + assert.equal(res.error, "normalization disabled"); + assert.equal(called, 0); + }, + ); +}); + +test("normalize: normalizeModel override se usa en el request", async () => { + const { captured, handler } = captureRequest(); + await withFetch(handler, async () => { + const { complete } = createNormalizer({ + endpoint: "http://x/v1", + model: "base", + normalizeModel: "norm-model", + }); + const res = await complete({ prompt: "hola" }); + assert.equal(res.text, "ok"); + assert.equal(captured.body.model, "norm-model"); + }); +}); + +test("normalize: default usa model si no hay normalizeModel", async () => { + const { captured, handler } = captureRequest(); + await withFetch(handler, async () => { + const { complete } = createNormalizer({ endpoint: "http://x/v1", model: "base" }); + await complete({ prompt: "hola" }); + assert.equal(captured.body.model, "base"); + }); +}); + +test("normalize: normalizeEndpoint override apunta a otro endpoint", async () => { + const { captured, handler } = captureRequest(); + await withFetch(handler, async () => { + const { complete } = createNormalizer({ + endpoint: "http://main/v1", + model: "base", + normalizeEndpoint: "http://cheap/v1", + }); + await complete({ prompt: "hola" }); + assert.equal(captured.url, "http://cheap/v1/chat/completions"); + }); +});