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
9 changes: 6 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ only document constraints and rules an agent would get wrong without being told.

## Architecture

Single TUI plugin exported from `index.js` with logic split into `lib/`.
Single OpenCode V2 CLI plugin exported from `index.js` with logic split into `lib/`.

## Key invariants

- Single default export: `{ id, tui }`. No server-side plugin.
- Single default export: `Plugin.define({ id, setup })` from `@opencode/plugin/tui`. No server-side plugin.
- The host provides `@opencode/plugin/tui` at runtime; never add it as a runtime dependency.
- LLM calls use the OpenAI chat completions API, not the Anthropic messages API.
- Configuration uses `options` (static) and `api.kv` (runtime). No dotfile I/O.
- Configuration uses `context.options` (static) and `context.storage` (runtime, wrapped by `lib/kv.js`). No dotfile I/O.
- V2 does not expose the prompt composer to plugins; STT sends prompts via `context.client.session.prompt`. Do not reintroduce `tui.appendPrompt`/`api.command.register` (V1 APIs).
- Voice features need `submitOnStop: true` for hands-free sending; the default opens an edit dialog instead.
- No build step. Plain ESM JavaScript, shipped as-is.

## Scripts
Expand Down
149 changes: 87 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,48 +5,57 @@

# opencode-voice

Speech-to-text and text-to-speech plugin for [OpenCode](https://opencode.ai/).
Speech-to-text and text-to-speech plugin for [OpenCode V2](https://opencode.ai/v2/docs/cli/plugins).

Record voice prompts with local whisper transcription, hear assistant responses
spoken aloud via Piper TTS. Both directions use an LLM to normalize text for
natural speech (fixing homophones, splitting camelCase identifiers, summarizing
code-heavy responses, etc.).

> [!NOTE]
> **OpenCode V2 only.** V2 ships a new plugin API; V1 implementations do not
> run on it. This version targets OpenCode V2 (`opencode-v2`). V1 is no longer
> supported.

## Install

Add to your `tui.json` (create at `~/.config/opencode/tui.json` if it doesn't
exist). You must configure at least `endpoint` and `model`:
Add the plugin to your `cli.json` (create at `~/.config/opencode/cli.json` if
it doesn't exist). You must configure at least `endpoint` and `model`:

> [!NOTE]
> **Clobbering default keybinds.** This plugin uses `ctrl+r` for voice
> recording, but OpenCode assigns it to session rename by default. Session
> rename is not used frequently and is still accessible via `/rename`, so we
> clobber the factory default to let the plugin use `ctrl+r` properly. See
> the `keybinds` section in the config below.
> rename is still accessible via `/rename`, so we clobber the factory default
> to let the plugin use `ctrl+r` properly. See the `keybinds` section in the
> config below.

```json
{
"$schema": "https://opencode.ai/tui.json",
"$schema": "https://opencode.ai/v2/cli.json",
"keybinds": {
"session_rename": "none"
"session.rename": "none"
},
"plugin": [
[
"@renjfk/opencode-voice",
{
"plugins": [
{
"package": "/path/to/opencode-voice",
"options": {
"endpoint": "https://api.anthropic.com/v1",
"model": "claude-haiku-4-5",
"apiKeyEnv": "ANTHROPIC_API_KEY"
}
]
}
]
}
```

Use a package name (`@renjfk/opencode-voice`) or a local path
(`/path/to/opencode-voice`) in `package`. Local paths are loaded straight from
disk, so edits are picked up on save.

### Refresh cached plugin after updates

If OpenCode keeps using an older published version of the plugin after an
update, clear the cached package and restart OpenCode:
If you install from npm and OpenCode keeps using an older published version of
the plugin after an update, clear the cached package and restart OpenCode:

```bash
rm -rf ~/.cache/opencode/packages/@renjfk/
Expand Down Expand Up @@ -233,21 +242,21 @@ speech-to-text it cleans up whisper output (punctuation, filler words, software
engineering homophones). For text-to-speech it converts markdown into natural
spoken text.

Configure your endpoint in `tui.json` via plugin options. Any OpenAI-compatible
Configure your endpoint in `cli.json` via plugin options. Any OpenAI-compatible
endpoint works (Anthropic, OpenAI, Ollama, vLLM, LM Studio, etc.). The `apiKeyEnv`
option is optional - omit it for unauthenticated endpoints like Ollama.

```json
{
"plugin": [
[
"@renjfk/opencode-voice",
{
"plugins": [
{
"package": "@renjfk/opencode-voice",
"options": {
"endpoint": "https://api.anthropic.com/v1",
"model": "claude-haiku-4-5",
"apiKeyEnv": "ANTHROPIC_API_KEY"
}
]
}
]
}
```
Expand All @@ -256,14 +265,14 @@ For unauthenticated local endpoints (e.g. Ollama):

```json
{
"plugin": [
[
"@renjfk/opencode-voice",
{
"plugins": [
{
"package": "@renjfk/opencode-voice",
"options": {
"endpoint": "http://localhost:11434/v1",
"model": "llama3.2"
}
]
}
]
}
```
Expand All @@ -278,13 +287,20 @@ For unauthenticated local endpoints (e.g. Ollama):
- `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`
- `trimSilence` _(optional)_ - whether to remove leading silence from recordings (default `true`). Set to `false` if your recordings are missing the first word or syllable
- `submitOnStop` _(optional)_ - when `true`, stopping a recording sends the transcription as a prompt immediately (default `false`, which opens an edit dialog first)
- `recordKeybind` _(optional)_ - key that toggles recording (default `ctrl+r`)
- `cancelKeybind` _(optional)_ - key that cancels recording (default `ctrl+y`)
- `submitKeybind` _(optional)_ - key for `/stt-submit` (default: no keybind; use the command)
- `speakKeybind` _(optional)_ - key that reads the last response aloud (default `<leader>v`)
- `toggleKeybind` _(optional)_ - key that toggles auto TTS (default `<leader>o`)
- `stopKeybind` _(optional)_ - key that stops TTS playback (default: no keybind; use `/tts-stop`)

### Logging

The plugin writes diagnostics through OpenCode's structured app logger. If this plugin is not working with your setup, check the OpenCode log file and, optionally, enable debug mode. See the [OpenCode Docs](https://opencode.ai/docs/troubleshooting/#logs) for details.

Routine plugin diagnostics use `debug`; recoverable issues use `warn`; failed
child processes, API calls, or unexpected exceptions use `error`.
Set `OPENCODE_VOICE_LOG` to a file path to enable plugin diagnostics, e.g.
`OPENCODE_VOICE_LOG=~/.local/share/opencode/log/opencode-voice.log opencode`.
Routine diagnostics use `debug`; recoverable issues use `warn`; failed child
processes, API calls, or unexpected exceptions use `error`.

### STT API transcription (optional)

Expand All @@ -294,15 +310,15 @@ plugin on a machine without whisper-cpp installed.

```json
{
"plugin": [
[
"@renjfk/opencode-voice",
{
"plugins": [
{
"package": "@renjfk/opencode-voice",
"options": {
"sttEndpoint": "http://127.0.0.1:8000/v1",
"sttModel": "whisper-large-v3-turbo",
"sttApiKeyEnv": "MY_STT_API_KEY"
}
]
}
]
}
```
Expand All @@ -321,15 +337,15 @@ up or how responses are spoken.

```json
{
"plugin": [
[
"@renjfk/opencode-voice",
{
"plugins": [
{
"package": "@renjfk/opencode-voice",
"options": {
"sttPrompt": "~/.config/opencode/stt-prompt.md",
"ttsAutoPrompt": "~/.config/opencode/tts-auto-prompt.md",
"ttsManualPrompt": "~/.config/opencode/tts-manual-prompt.md"
}
]
}
]
}
```
Expand All @@ -344,14 +360,14 @@ If a path is not set, the built-in default prompt is used.

### Speech-to-text

| Command | Keybind | Description |
| --------------- | ---------- | -------------------------------------- |
| `/stt-record` | `ctrl+r` | Start/stop recording + transcribe |
| `/stt-submit` | `leader+r` | Stop recording, transcribe, and submit |
| `/stt-stop` | | Cancel recording |
| `/stt-model` | | Select whisper model |
| `/stt-language` | | Select transcription language |
| `/stt-mic` | | Select microphone |
| Command | Keybind | Description |
| --------------- | -------- | ------------------------------------ |
| `/stt-record` | `ctrl+r` | Start/stop recording + transcribe |
| `/stt-submit` | | Stop recording, transcribe, and send |
| `/stt-stop` | `ctrl+y` | Cancel recording |
| `/stt-model` | | Select whisper model |
| `/stt-language` | | Select transcription language |
| `/stt-mic` | | Select microphone |

`/stt-mic` lists CoreAudio input devices on macOS, and PulseAudio sources on
Linux (via `pactl`, monitor sources excluded). On systems without a supported
Expand All @@ -363,14 +379,14 @@ outside the list can be set via the `sttLanguage` plugin option.

### Text-to-speech

The `leader` key in OpenCode is `ctrl+x`. So `leader+s` means press `ctrl+x`
then `s`.
The `leader` key in OpenCode is `ctrl+x`. So `leader+v` means press `ctrl+x`
then `v`.

| Command | Keybind | Description |
| ------------ | ---------- | ------------------------ |
| `/tts-speak` | `leader+s` | Read last response aloud |
| `/tts-mode` | `leader+v` | Toggle auto TTS on/off |
| `/tts-stop` | `escape` | Stop playback |
| `/tts-speak` | `leader+v` | Read last response aloud |
| `/tts-mode` | `leader+o` | Toggle auto TTS on/off |
| `/tts-stop` | | Stop playback |
| `/tts-voice` | | Select TTS voice |

## How it works
Expand All @@ -384,10 +400,18 @@ then `s`.
3. LLM normalizes the transcription: fixes punctuation, removes filler words,
corrects software engineering homophones ("Jason" to "JSON", "bullion" to
"boolean", etc.)
4. Cleaned text is appended to the OpenCode prompt, or submitted immediately
when `/stt-submit` is used. If normalization fails (e.g. LLM endpoint
unreachable), the raw transcription is used as a fallback so you never lose
your input
4. Cleaned text is sent as a prompt (creating a session first when you are on
the home screen). With `submitOnStop: true` it is sent immediately;
otherwise an edit dialog opens first, and pressing Enter sends the edited
text. If normalization fails (e.g. LLM endpoint unreachable), the raw
transcription is used as a fallback so you never lose your input

> [!NOTE]
> OpenCode V2 does not yet expose the input composer to plugins
> ([opencode#51209](https://github.com/anomalyco/opencode/issues/51209),
> [opencode#51392](https://github.com/anomalyco/opencode/issues/51392)), so
> transcriptions cannot be appended to an in-progress draft. Voice input
> sends a prompt instead; use the edit dialog to review it first.

### TTS pipeline

Expand All @@ -403,7 +427,7 @@ When enabled (`/tts-mode`), the plugin automatically speaks:

- Assistant responses when a session goes idle after work
- Permission requests
- Questions that need your answer
- Questions that need your answer (V2 forms)

## Contributing

Expand Down Expand Up @@ -431,13 +455,14 @@ npm run fmt:fix # oxfmt --write

### Test local plugin in OpenCode

To test unpublished changes in the OpenCode TUI, point `~/.config/opencode/tui.json`
at the local repo path, not the npm package name:
To test unpublished changes in the OpenCode TUI, point
`~/.config/opencode/cli.json` at the local repo path, not the npm package
name:

```json
{
"$schema": "https://opencode.ai/tui.json",
"plugin": ["/Users/your-user/opencode-voice"]
"$schema": "https://opencode.ai/v2/cli.json",
"plugins": ["/Users/your-user/opencode-voice"]
}
```

Expand Down
77 changes: 19 additions & 58 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// opencode-voice: Speech-to-text and text-to-speech for OpenCode.
// opencode-voice: Speech-to-text and text-to-speech for OpenCode V2.
//
// STT: Record voice via sox, transcribe with whisper-cpp, normalize with
// an OpenAI-compatible LLM, append to the TUI prompt.
// an OpenAI-compatible LLM, then submit it as a prompt (or edit it in a
// dialog first when submitOnStop is off).
//
// TTS: Auto-speak assistant responses (or read on demand) via Piper,
// with LLM normalization for natural speech.
Expand All @@ -10,64 +11,24 @@
// STT: brew install whisper-cpp sox
// TTS: Piper binary on PATH, voice models at ~/.local/share/piper-voices/
//
// Configuration via tui.json plugin options:
// ["opencode-voice", { "endpoint": "...", "model": "...", "apiKeyEnv": "..." }]
// Configuration via cli.json plugin options:
// { "plugins": [{ "package": "opencode-voice", "options": { ... } }] }
//
// Runtime state (model, mic, voice, tts mode) persisted via api.kv.
// Runtime state (model, mic, voice, tts mode) persisted via context.storage.
//
// Commands:
// /stt-record (ctrl+r) - start/stop recording + transcribe
// /stt-submit (leader+r)- stop recording + transcribe + submit
// /stt-stop - cancel recording
// /stt-model - select whisper model
// /stt-language - select transcription language
// /stt-mic - select microphone
// /tts-speak (leader+s)- read last response aloud
// /tts-mode (leader+v) - toggle auto TTS on/off
// /tts-stop (escape) - stop playback
// /tts-voice - select TTS voice
// /stt-record (ctrl+r) - start/stop recording + transcribe + send
// /stt-submit - stop recording + transcribe + send
// /stt-stop (ctrl+y) - cancel recording
// /stt-model - select whisper model
// /stt-language - select transcription language
// /stt-mic - select microphone
// /tts-speak (leader+v) - read last response aloud
// /tts-mode (leader+o) - toggle auto TTS on/off
// /tts-stop - stop playback
// /tts-voice - select TTS voice

import fs from "node:fs";
import os from "node:os";
import { registerSTT } from "./lib/stt.js";
import { registerTTS } from "./lib/tts.js";
import { createClient } from "./lib/llm-client.js";
import { createLogger } from "./lib/logger.js";
import { Plugin } from "@opencode/plugin/tui";
import { createPluginDefinition } from "./lib/plugin.js";

function loadPromptFile(filePath, logger, name) {
if (!filePath) return null;
const resolved = filePath.replace(/^~(?=\/|$)/, os.homedir());
try {
const prompt = fs.readFileSync(resolved, "utf-8").trim() || null;
logger?.log(
"plugin",
prompt ? `Loaded ${name} prompt: ${resolved}` : `Ignored empty ${name} prompt: ${resolved}`,
"debug",
);
return prompt;
} catch (err) {
logger?.log("Plugin", `Failed to load ${name} prompt ${resolved}: ${err.message}`, "warn");
return null;
}
}

export default {
id: "opencode-voice",
tui: async (api, options) => {
const { kv } = api;
const logger = createLogger(api.client);
logger.log("plugin", "Initializing", "debug");
const { complete } = createClient(options, logger);

const prompts = {
stt: loadPromptFile(options?.sttPrompt, logger, "STT"),
ttsAuto: loadPromptFile(options?.ttsAutoPrompt, logger, "TTS auto"),
ttsManual: loadPromptFile(options?.ttsManualPrompt, logger, "TTS manual"),
};

const sttCommands = registerSTT(api, kv, complete, prompts, options, logger);
const ttsCommands = registerTTS(api, kv, complete, prompts, logger);

api.command.register(() => [...sttCommands, ...ttsCommands]);
},
};
export default Plugin.define(createPluginDefinition());
Loading