Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` /
Expand Down
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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"),
Expand Down
44 changes: 44 additions & 0 deletions lib/normalize.js
Original file line number Diff line number Diff line change
@@ -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 };
}
82 changes: 82 additions & 0 deletions test/normalize.test.js
Original file line number Diff line number Diff line change
@@ -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");
});
});