diff --git a/AGENTS.md b/AGENTS.md index 25cb349..159bcd7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/README.md b/README.md index b2ed2c4..93ed5e4 100644 --- a/README.md +++ b/README.md @@ -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/ @@ -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" } - ] + } ] } ``` @@ -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" } - ] + } ] } ``` @@ -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 `v`) +- `toggleKeybind` _(optional)_ - key that toggles auto TTS (default `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) @@ -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" } - ] + } ] } ``` @@ -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" } - ] + } ] } ``` @@ -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 @@ -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 @@ -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 @@ -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 @@ -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"] } ``` diff --git a/index.js b/index.js index 3a324b1..6f42c15 100644 --- a/index.js +++ b/index.js @@ -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. @@ -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()); diff --git a/lib/kv.js b/lib/kv.js new file mode 100644 index 0000000..b3bfb0b --- /dev/null +++ b/lib/kv.js @@ -0,0 +1,21 @@ +// Durable key/value state backed by the V2 plugin storage. +// +// The V2 CLI plugin API exposes Solid stores instead of a plain get/set pair. +// This adapter restores the synchronous kv.get/kv.set shape the rest of the +// plugin uses; persistence happens asynchronously inside the host. + +export function createKV(storage) { + const [state, update] = storage.store("state", { initial: {} }); + + return { + get(key, fallback) { + const value = state[key]; + return value === undefined ? fallback : value; + }, + set(key, value) { + void update((draft) => { + draft[key] = value; + }).catch(() => {}); + }, + }; +} diff --git a/lib/logger.js b/lib/logger.js index d7a1196..a949242 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -1,14 +1,15 @@ -export function createLogger(client) { - async function log(scope, message, level = "debug") { +import fs from "node:fs"; + +const debugLogFile = process.env.OPENCODE_VOICE_LOG; + +export function createLogger() { + function log(scope, message, level = "debug") { + if (!debugLogFile) return; try { - await client?.app?.log?.({ - body: { - service: "opencode-voice", - level, - message, - extra: { scope }, - }, - }); + fs.appendFileSync( + debugLogFile, + `${new Date().toISOString()} [${level}] ${scope}: ${message}\n`, + ); } catch { // Logging should never interrupt voice features. } diff --git a/lib/plugin.js b/lib/plugin.js new file mode 100644 index 0000000..69145b7 --- /dev/null +++ b/lib/plugin.js @@ -0,0 +1,62 @@ +// V2 CLI plugin definition. +// +// Kept free of the `@opencode/plugin/tui` import so the definition can be +// built and tested without the host runtime; index.js wraps it with +// Plugin.define for OpenCode. + +import fs from "node:fs"; +import os from "node:os"; +import { registerSTT } from "./stt.js"; +import { registerTTS } from "./tts.js"; +import { createClient } from "./llm-client.js"; +import { createLogger } from "./logger.js"; +import { createKV } from "./kv.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 function createPluginDefinition() { + return { + id: "opencode-voice", + async setup(context) { + const logger = createLogger(); + const kv = createKV(context.storage); + const { complete } = createClient(context.options, logger); + logger.log("plugin", "Initializing", "debug"); + + const prompts = { + stt: loadPromptFile(context.options?.sttPrompt, logger, "STT"), + ttsAuto: loadPromptFile(context.options?.ttsAutoPrompt, logger, "TTS auto"), + ttsManual: loadPromptFile(context.options?.ttsManualPrompt, logger, "TTS manual"), + }; + + const stt = registerSTT(context, kv, complete, prompts, context.options, logger); + const tts = registerTTS(context, kv, complete, prompts, context.options, logger); + + context.keymap.layer(() => ({ + mode: "global", + priority: 10, + commands: [...stt.commands, ...tts.commands], + })); + + return () => { + stt.dispose?.(); + tts.dispose?.(); + }; + }, + }; +} diff --git a/lib/session.js b/lib/session.js index aa23946..f841941 100644 --- a/lib/session.js +++ b/lib/session.js @@ -1,14 +1,12 @@ -// Shared session helpers for OpenCode TUI plugin. +// Shared session helpers for the OpenCode V2 CLI plugin. /** * Get the title of a specific session by ID. Returns "" if unknown or on error. */ -export async function getSessionTitle(client, sessionID) { +export function getSessionTitle(context, sessionID) { if (!sessionID) return ""; try { - const result = await client.session.list(); - const session = result.data?.find((s) => s.id === sessionID); - return session?.title || ""; + return context.data.session.get(sessionID)?.title || ""; } catch { return ""; } @@ -18,11 +16,11 @@ export async function getSessionTitle(client, sessionID) { * Get the title of the most recently updated session. Returns "" on error or * when there are no sessions. */ -export async function getActiveSessionTitle(client) { +export function getActiveSessionTitle(context) { try { - const result = await client.session.list(); - if (!result.data || result.data.length === 0) return ""; - const active = result.data.sort((a, b) => b.time.updated - a.time.updated)[0]; + const sessions = context.data.session.list() ?? []; + if (sessions.length === 0) return ""; + const active = [...sessions].sort((a, b) => b.time.updated - a.time.updated)[0]; return active?.title || ""; } catch { return ""; diff --git a/lib/stt.js b/lib/stt.js index 68ebf88..42674e8 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -537,28 +537,43 @@ async function transcribeApi(kv, logger) { } } -async function appendTranscription(client, text, submit) { - let appendResult = await client.tui.appendPrompt({ body: { text } }); - - if (appendResult?.error?.data?.message === "Expected object, got undefined") { - appendResult = await client.tui.appendPrompt({ text }); +async function submitTranscription(context, text) { + let route = context.ui.router.current(); + + if (route.type !== "session") { + const location = context.location ?? context.data.location.default(); + const session = await context.client.session.create({ location }); + context.ui.router.navigate({ type: "session", sessionID: session.id }); + route = { type: "session", sessionID: session.id }; } - if (appendResult?.error) { - throw new Error( - `appendPrompt failed: ${appendResult.error.data?.message || appendResult.error.name}`, - ); - } + await context.client.session.prompt({ sessionID: route.sessionID, text }); +} +async function deliverTranscription(context, text, submit) { if (submit) { - await client.tui.submitPrompt(); + await submitTranscription(context, text); + return; } + + // V2 does not expose the composer to plugins yet (opencode issues #51209 and + // #51392), so the non-submit mode edits the transcription in a dialog and + // sends it on confirmation instead of appending it to the input field. + const edited = await context.ui.dialog.prompt({ + title: "Voice input", + description: "Edit the transcription, then press Enter to send it", + value: text, + }); + if (edited === undefined) return; + const finalText = edited.trim(); + if (!finalText) return; + await submitTranscription(context, finalText); } async function doTranscribePipeline( kv, complete, - client, + context, toast, systemPrompt, submit = false, @@ -585,7 +600,7 @@ async function doTranscribePipeline( } toast("Normalizing..."); - const sessionTitle = await getActiveSessionTitle(client); + const sessionTitle = getActiveSessionTitle(context); const llmResult = await normalizeTranscription( complete, result.text, @@ -597,13 +612,13 @@ async function doTranscribePipeline( if (!llmResult.text) { logger?.log("STT", `Normalization failed, using raw input: ${llmResult.error}`, "warn"); toast(`Normalization failed, using raw input: ${llmResult.error}`, "warning"); - await appendTranscription(client, result.text, submit); + await deliverTranscription(context, result.text, submit); return; } - await appendTranscription(client, llmResult.text, submit); + await deliverTranscription(context, llmResult.text, submit); logger?.log("STT", `Pipeline completed normalizedChars=${llmResult.text.length}`, "debug"); - toast(submit ? "Transcription submitted" : "Transcription added to prompt", "success"); + toast(submit ? "Transcription submitted" : "Transcription ready", "success"); } catch (err) { logger?.log("STT", `Pipeline error: ${err.message}`, "error"); toast(`STT error: ${err.message}`, "error"); @@ -615,13 +630,12 @@ async function doTranscribePipeline( // ---- Public API for TUI plugin ---- -export function registerSTT(api, kv, complete, prompts, opts, logger) { - const client = api.client; +export function registerSTT(context, kv, complete, prompts, opts, logger) { const systemPrompt = prompts?.stt || STT_SYSTEM_PROMPT; const backend = detectAudioBackend(); logger?.log("STT", `Audio backend=${backend}`, "debug"); function toast(message, variant = "info") { - api.ui.toast({ message, variant, duration: 3000 }); + context.ui.toast.show({ message, variant, duration: 3000 }); } if (opts?.sttEndpoint) { @@ -640,6 +654,16 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } logger?.log("STT", `Default language=${sttDefaultLanguage}`, "debug"); + const recordKeybind = opts?.recordKeybind || "ctrl+r"; + const cancelKeybind = opts?.cancelKeybind || "ctrl+y"; + const submitKeybind = opts?.submitKeybind ?? false; + const submitOnStop = opts?.submitOnStop === true; + logger?.log( + "STT", + `Record keybind=${recordKeybind} submit keybind=${submitKeybind} submitOnStop=${submitOnStop}`, + "debug", + ); + tmpDir = opts?.tmpDir || "/tmp"; try { fs.mkdirSync(tmpDir, { recursive: true }); @@ -648,23 +672,35 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } logger?.log("STT", `STT temp dir=${tmpDir}`, "debug"); - return [ + const commands = [ { + id: "opencode-voice.record", title: sttApiEndpoint ? "STT: record/transcribe (API)" : "STT: record/transcribe", - value: "stt.record", - description: sttApiEndpoint - ? "Toggle recording; press again to stop and transcribe via API" - : "Toggle recording; press again to stop and transcribe", - keybind: "ctrl+r", + group: "Voice", + palette: true, + description: submitOnStop + ? "Toggle recording; stopping transcribes and sends the prompt" + : sttApiEndpoint + ? "Toggle recording; press again to stop and transcribe via API" + : "Toggle recording; press again to stop and transcribe", + bind: recordKeybind, slash: { name: "stt-record" }, - onSelect() { + async run() { if (processing) { toast("STT busy, please wait..."); return; } if (recording) { toast("Stopping, transcribing..."); - doTranscribePipeline(kv, complete, client, toast, systemPrompt, false, logger); + await doTranscribePipeline( + kv, + complete, + context, + toast, + systemPrompt, + submitOnStop, + logger, + ); } else { startRecording(kv, backend, toast, logger, opts?.trimSilence); if (recording) toast("Recording... press again to transcribe"); @@ -672,14 +708,16 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { }, }, { + id: "opencode-voice.submit", title: sttApiEndpoint ? "STT: submit recording (API)" : "STT: submit recording", - value: "stt.submit", + group: "Voice", + palette: true, description: sttApiEndpoint - ? "Stop recording, transcribe via API, and submit prompt" - : "Stop recording, transcribe, and submit prompt", - keybind: "r", + ? "Stop recording, transcribe via API, and send the prompt" + : "Stop recording, transcribe, and send the prompt", + bind: submitKeybind, slash: { name: "stt-submit" }, - onSelect() { + async run() { if (processing) { toast("STT busy, please wait..."); return; @@ -689,15 +727,18 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { return; } toast("Stopping, transcribing..."); - doTranscribePipeline(kv, complete, client, toast, systemPrompt, true, logger); + await doTranscribePipeline(kv, complete, context, toast, systemPrompt, true, logger); }, }, { + id: "opencode-voice.cancel", title: "STT: cancel recording", - value: "stt.stop", + group: "Voice", + palette: true, description: "Cancel current recording", + bind: cancelKeybind, slash: { name: "stt-stop" }, - onSelect() { + run() { if (recording) { recording = false; forceKillSox(logger); @@ -707,80 +748,65 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { }, }, { + id: "opencode-voice.model", title: sttApiEndpoint ? "STT: select model (API)" : "STT: select model", - value: "stt.model", + group: "Voice", + palette: true, description: sttApiEndpoint ? "Choose whisper model via API" : "Choose whisper model", slash: { name: "stt-model" }, - async onSelect() { + async run() { if (sttApiEndpoint) { const current = kv.get("stt.api.model") || sttApiModel; const apiModels = await getApiModels(logger); const options = apiModels.length > 0 ? apiModels : [{ value: current, label: current }]; - api.ui.dialog.replace(() => - api.ui.DialogSelect({ - title: "Select whisper model (API)", - current, - options: options.map((m) => ({ - title: m.label, - value: m.value, - onSelect() { - kv.set("stt.api.model", m.value); - toast(`Whisper API model: ${m.label}`); - api.ui.dialog.clear(); - }, - })), - }), - ); + const selected = await context.ui.dialog.select({ + title: "Select whisper model (API)", + current, + options: options.map((m) => ({ title: m.label, value: m.value })), + }); + if (selected === undefined) return; + kv.set("stt.api.model", selected); + toast(`Whisper API model: ${selected}`); } else { const current = getModelName(kv); - api.ui.dialog.replace(() => - api.ui.DialogSelect({ - title: "Select whisper model", - current, - options: Object.entries(MODELS).map(([key, v]) => ({ - title: v.label, - value: key, - onSelect() { - kv.set("stt.model", key); - toast(`Whisper model: ${v.label}`); - api.ui.dialog.clear(); - }, - })), - }), - ); + const selected = await context.ui.dialog.select({ + title: "Select whisper model", + current, + options: Object.entries(MODELS).map(([key, v]) => ({ title: v.label, value: key })), + }); + if (selected === undefined) return; + kv.set("stt.model", selected); + toast(`Whisper model: ${MODELS[selected]?.label || selected}`); } }, }, { + id: "opencode-voice.language", title: "STT: select language", - value: "stt.language", + group: "Voice", + palette: true, description: "Choose transcription language (local whisper-cli only)", slash: { name: "stt-language" }, - onSelect() { + async run() { const current = getLanguage(kv); - api.ui.dialog.replace(() => - api.ui.DialogSelect({ - title: "Select transcription language", - current, - options: Object.entries(LANGUAGES).map(([key, v]) => ({ - title: v.label, - value: key, - onSelect() { - kv.set("stt.language", key); - toast(`Whisper language: ${v.label}`); - api.ui.dialog.clear(); - }, - })), - }), - ); + const selected = await context.ui.dialog.select({ + title: "Select transcription language", + current, + options: Object.entries(LANGUAGES).map(([key, v]) => ({ title: v.label, value: key })), + }); + if (selected === undefined) return; + kv.set("stt.language", selected); + toast(`Whisper language: ${LANGUAGES[selected]?.label || selected}`); }, }, { + id: "opencode-voice.mic", title: "STT: select microphone", - value: "stt.mic", + group: "Voice", + palette: true, description: "Choose audio input device", slash: { name: "stt-mic" }, - onSelect() { + async run() { const current = kv.get("stt.mic", ""); const devices = listInputDevices(backend); if (devices.length === 0) { @@ -790,33 +816,33 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { toast(hint); return; } - api.ui.dialog.replace(() => - api.ui.DialogSelect({ - title: "Select microphone", - current, - options: [ - { - title: "System default", - value: "", - onSelect() { - kv.set("stt.mic", ""); - toast("Mic: system default"); - api.ui.dialog.clear(); - }, - }, - ...devices.map((d) => ({ - title: d.label, - value: d.name, - onSelect() { - kv.set("stt.mic", d.name); - toast(`Mic: ${d.label}`); - api.ui.dialog.clear(); - }, - })), - ], - }), - ); + const selected = await context.ui.dialog.select({ + title: "Select microphone", + current, + options: [ + { title: "System default", value: "" }, + ...devices.map((d) => ({ title: d.label, value: d.name })), + ], + }); + if (selected === undefined) return; + kv.set("stt.mic", selected); + if (!selected) { + toast("Mic: system default"); + return; + } + const device = devices.find((d) => d.name === selected); + toast(`Mic: ${device?.label || selected}`); }, }, ]; + + return { + commands, + dispose() { + if (recording) { + recording = false; + forceKillSox(logger); + } + }, + }; } diff --git a/lib/tts.js b/lib/tts.js index c97967b..6b49aa0 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -59,58 +59,68 @@ Rules: // ---- Session helpers ---- -async function getTurnAssistantText(client, api) { - const route = api.route.current; - if (route.name !== "session") return null; - - const sessionID = route.params.sessionID; - const stateMessages = api.state.session.messages(sessionID); - if (!stateMessages || stateMessages.length === 0) return null; - - const assistantIDs = []; - for (let i = stateMessages.length - 1; i >= 0; i--) { - if (stateMessages[i].role === "user") break; - if (stateMessages[i].role === "assistant") { - assistantIDs.unshift(stateMessages[i].id); +async function getTurnAssistantText(context) { + const route = context.ui.router.current(); + if (route.type !== "session") return null; + + const sessionID = route.sessionID; + const messages = context.data.session.message.list(sessionID) ?? []; + if (messages.length === 0) return null; + + const assistant = []; + for (let i = messages.length - 1; i >= 0; i--) { + if (messages[i].type === "user") break; + if (messages[i].type === "assistant") { + assistant.unshift(messages[i]); } } - if (assistantIDs.length === 0) return null; + if (assistant.length === 0) return null; const allText = []; - for (const msgID of assistantIDs) { - try { - const fullMsg = await client.session - .message({ sessionID, messageID: msgID }, { throwOnError: true }) - .then((r) => r.data); - - const textParts = (fullMsg?.parts || []).filter((p) => p.type === "text"); - const text = textParts - .map((p) => p.text || "") - .join("\n\n") - .trim(); - if (text) allText.push(text); - } catch { - // Skip messages that fail to fetch + for (const message of assistant) { + let text = (message.content ?? []) + .filter((part) => part.type === "text") + .map((part) => part.text || "") + .join("\n\n") + .trim(); + if (!text) { + try { + const full = await context.client.session.message.get({ + sessionID, + messageID: message.id, + }); + text = (full?.content ?? []) + .filter((part) => part.type === "text") + .map((part) => part.text || "") + .join("\n\n") + .trim(); + } catch { + // Skip messages that fail to fetch + } } + if (text) allText.push(text); } if (allText.length === 0) return null; return { - lastMessageID: assistantIDs[assistantIDs.length - 1], + lastMessageID: assistant[assistant.length - 1].id, text: allText.join("\n\n"), }; } // ---- Public API for TUI plugin ---- -export function registerTTS(api, kv, complete, prompts, logger) { - const client = api.client; +export function registerTTS(context, kv, complete, prompts, opts, logger) { const systemAuto = prompts?.ttsAuto || SYSTEM_AUTO; const systemManual = prompts?.ttsManual || SYSTEM_MANUAL; + const speakKeybind = opts?.speakKeybind || "v"; + const toggleKeybind = opts?.toggleKeybind || "o"; + const stopKeybind = opts?.stopKeybind ?? false; + function toast(message, variant = "info") { - api.ui.toast({ message, variant, duration: 3000 }); + context.ui.toast.show({ message, variant, duration: 3000 }); } function getVoiceModel() { @@ -253,7 +263,7 @@ export function registerTTS(api, kv, complete, prompts, logger) { // ---- Session-prefixed announcements ---- async function speakWithSessionPrefix(sessionID, message, suffix) { - const sessionTitle = await getSessionTitle(client, sessionID); + const sessionTitle = getSessionTitle(context, sessionID); const parts = []; if (sessionTitle) parts.push(`Session: ${sessionTitle}.`); parts.push(message); @@ -272,54 +282,64 @@ export function registerTTS(api, kv, complete, prompts, logger) { let lastSpokenMessageID = null; let wasBusy = false; - api.event.on("session.status", (event) => { - if (event.properties?.status?.type === "busy") wasBusy = true; - }); - - api.event.on("session.idle", async (event) => { - if (kv.get("tts.mode", "off") !== "on") return; - if (!wasBusy) return; - wasBusy = false; - - const sessionID = event.properties?.sessionID; - const result = await getTurnAssistantText(client, api); - if (!result || !result.text) return; - - if (result.lastMessageID === lastSpokenMessageID) return; - lastSpokenMessageID = result.lastMessageID; - - toast("Normalizing response..."); - const llmResult = await normalizeForSpeech(result.text, systemAuto); - if (!llmResult.text) { - logger?.log?.("TTS", `Auto normalization failed: ${llmResult.error}`, "warn"); - toast(`TTS normalization failed: ${llmResult.error}`, "warning"); - return; - } + const unsubscribers = []; + + unsubscribers.push( + context.data.on("session.status", (event) => { + if (event.data?.status?.type === "busy") wasBusy = true; + }), + ); + + unsubscribers.push( + context.data.on("session.idle", async (event) => { + if (kv.get("tts.mode", "off") !== "on") return; + if (!wasBusy) return; + wasBusy = false; + + const sessionID = event.data?.sessionID; + const result = await getTurnAssistantText(context); + if (!result || !result.text) return; + + if (result.lastMessageID === lastSpokenMessageID) return; + lastSpokenMessageID = result.lastMessageID; + + toast("Normalizing response..."); + const llmResult = await normalizeForSpeech(result.text, systemAuto); + if (!llmResult.text) { + logger?.log?.("TTS", `Auto normalization failed: ${llmResult.error}`, "warn"); + toast(`TTS normalization failed: ${llmResult.error}`, "warning"); + return; + } - logger?.log?.("TTS", `Auto normalization succeeded chars=${llmResult.text.length}`, "debug"); - await speakWithSessionPrefix(sessionID, llmResult.text, "Ready for your input."); - }); - - api.event.on("permission.asked", async (event) => { - if (kv.get("tts.mode", "off") !== "on") return; - await speakWithSessionPrefix( - event.properties?.sessionID, - "Permission requested. Please check your screen.", - ); - }); - - api.event.on("question.asked", async (event) => { - if (kv.get("tts.mode", "off") !== "on") return; - await speakWithSessionPrefix( - event.properties?.sessionID, - "A question needs your answer. Please check your screen.", - ); - }); + logger?.log?.("TTS", `Auto normalization succeeded chars=${llmResult.text.length}`, "debug"); + await speakWithSessionPrefix(sessionID, llmResult.text, "Ready for your input."); + }), + ); + + unsubscribers.push( + context.data.on("permission.asked", async (event) => { + if (kv.get("tts.mode", "off") !== "on") return; + await speakWithSessionPrefix( + event.data?.sessionID, + "Permission requested. Please check your screen.", + ); + }), + ); + + unsubscribers.push( + context.data.on("form.created", async (event) => { + if (kv.get("tts.mode", "off") !== "on") return; + await speakWithSessionPrefix( + event.data?.form?.sessionID, + "A question needs your answer. Please check your screen.", + ); + }), + ); // ---- Manual mode ---- async function speakLastResponse() { - const result = await getTurnAssistantText(client, api); + const result = await getTurnAssistantText(context); if (!result || !result.text) { toast("No assistant response to speak", "warning"); return; @@ -340,24 +360,28 @@ export function registerTTS(api, kv, complete, prompts, logger) { // ---- Commands ---- - return [ + const commands = [ { + id: "opencode-voice.speak", title: "TTS: speak last response", - value: "tts.speak-last", + group: "Voice", + palette: true, description: "Read the last assistant response aloud (detailed)", - keybind: "s", + bind: speakKeybind, slash: { name: "tts-speak" }, - onSelect() { - speakLastResponse(); + async run() { + await speakLastResponse(); }, }, { + id: "opencode-voice.tts-toggle", title: "TTS: toggle", - value: "tts.mode", + group: "Voice", + palette: true, description: "Toggle auto text-to-speech on/off", - keybind: "v", + bind: toggleKeybind, slash: { name: "tts-mode" }, - onSelect() { + run() { const current = kv.get("tts.mode", "off"); const next = current === "on" ? "off" : "on"; kv.set("tts.mode", next); @@ -368,38 +392,43 @@ export function registerTTS(api, kv, complete, prompts, logger) { }, }, { + id: "opencode-voice.tts-stop", title: "TTS: stop playback", - value: "tts.stop", + group: "Voice", + palette: true, description: "Stop current TTS playback", - keybind: "escape", + bind: stopKeybind, slash: { name: "tts-stop" }, - onSelect() { + run() { if (stopSpeech()) toast("TTS stopped"); }, }, { + id: "opencode-voice.tts-voice", title: "TTS: select voice", - value: "tts.voice", + group: "Voice", + palette: true, description: "Choose TTS voice", slash: { name: "tts-voice" }, - onSelect() { + async run() { const current = kv.get("tts.voice", DEFAULT_TTS_VOICE); - api.ui.dialog.replace(() => - api.ui.DialogSelect({ - title: "Select voice", - current, - options: Object.entries(TTS_VOICES).map(([key, v]) => ({ - title: v.label, - value: key, - onSelect() { - kv.set("tts.voice", key); - toast(`Voice: ${v.label}`); - api.ui.dialog.clear(); - }, - })), - }), - ); + const selected = await context.ui.dialog.select({ + title: "Select voice", + current, + options: Object.entries(TTS_VOICES).map(([key, v]) => ({ title: v.label, value: key })), + }); + if (selected === undefined) return; + kv.set("tts.voice", selected); + toast(`Voice: ${TTS_VOICES[selected]?.label || selected}`); }, }, ]; + + return { + commands, + dispose() { + for (const unsubscribe of unsubscribers) unsubscribe(); + killProcs(); + }, + }; } diff --git a/package.json b/package.json index 551b3a1..fb09faa 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ }, "files": [ "index.js", + "tui.js", "lib" ], "type": "module", diff --git a/test/v2-smoke.test.js b/test/v2-smoke.test.js new file mode 100644 index 0000000..45010f8 --- /dev/null +++ b/test/v2-smoke.test.js @@ -0,0 +1,184 @@ +// V2 port smoke tests. +// +// They validate the plugin definition, command registration, storage wiring, +// and the TTS idle path against a fake plugin context. The definition itself +// has no host import, so these run anywhere. One extra test verifies the +// module export consumed by OpenCode; it needs "@opencode/plugin/tui" (or a +// stub) under node_modules and is skipped otherwise. + +import assert from "node:assert/strict"; +import test from "node:test"; + +import { createPluginDefinition } from "../lib/plugin.js"; + +let moduleExport = null; +try { + moduleExport = (await import("../index.js")).default; +} catch { + // The OpenCode runtime provides "@opencode/plugin/tui"; plain Node needs a stub. +} + +function createFakeContext(options = {}) { + const store = {}; + const registered = []; + const eventTypes = []; + const unsubscribeCalls = []; + const toasts = []; + + const context = { + options, + location: undefined, + app: { version: "0.0.0", channel: "test" }, + client: { + session: { + create: async () => ({ id: "ses_test" }), + prompt: async () => ({}), + message: { get: async () => ({ content: [] }) }, + }, + }, + data: { + on: (type, handler) => { + assert.equal(typeof handler, "function"); + eventTypes.push(type); + return () => unsubscribeCalls.push(type); + }, + session: { + list: () => [], + get: () => undefined, + message: { list: () => [] }, + }, + location: { default: () => ({ directory: process.cwd() }) }, + }, + keymap: { + layer(factory) { + const layer = factory(); + registered.push(...(layer.commands ?? [])); + }, + }, + storage: { + store: () => [ + store, + (mutation) => { + mutation(store); + return Promise.resolve(); + }, + ], + }, + ui: { + toast: { show: (toast) => toasts.push(toast) }, + dialog: { + select: async () => undefined, + prompt: async () => undefined, + clear: () => {}, + }, + router: { + current: () => ({ type: "session", sessionID: "ses_test" }), + navigate: () => {}, + }, + }, + attention: { notify: async () => ({ ok: true }) }, + renderer: {}, + theme: {}, + themeMode: "dark", + markdown: { registerCodeBlockRenderer: () => () => {} }, + }; + + return { context, store, registered, eventTypes, unsubscribeCalls, toasts }; +} + +test( + "index.js exports a V2 plugin definition", + { skip: moduleExport ? false : "host module not resolvable" }, + () => { + assert.equal(moduleExport.id, "opencode-voice"); + assert.equal(typeof moduleExport.setup, "function"); + }, +); + +test("definition registers every command and subscribes to TTS events", async () => { + const { context, registered, eventTypes, unsubscribeCalls } = createFakeContext(); + const plugin = createPluginDefinition(); + const cleanup = await plugin.setup(context); + + const ids = registered.map((command) => command.id).sort(); + assert.deepEqual(ids, [ + "opencode-voice.cancel", + "opencode-voice.language", + "opencode-voice.mic", + "opencode-voice.model", + "opencode-voice.record", + "opencode-voice.speak", + "opencode-voice.submit", + "opencode-voice.tts-stop", + "opencode-voice.tts-toggle", + "opencode-voice.tts-voice", + ]); + + for (const command of registered) { + assert.equal(typeof command.run, "function", `${command.id} has a run function`); + assert.ok(command.slash?.name, `${command.id} keeps its slash command`); + assert.ok( + command.bind === undefined || command.bind === false || typeof command.bind === "string", + ); + } + + assert.deepEqual(eventTypes.sort(), [ + "form.created", + "permission.asked", + "session.idle", + "session.status", + ]); + + assert.equal(typeof cleanup, "function"); + await cleanup(); + assert.equal(unsubscribeCalls.length, eventTypes.length); +}); + +test("selecting a model persists the choice through storage", async () => { + const { context, store, registered } = createFakeContext(); + const plugin = createPluginDefinition(); + await plugin.setup(context); + + // The record keybind is the configured default. + const record = registered.find((command) => command.id === "opencode-voice.record"); + assert.equal(record.bind, "ctrl+r"); + + context.ui.dialog.select = async () => "tiny.en"; + const model = registered.find((command) => command.id === "opencode-voice.model"); + await model.run(); + assert.equal(store["stt.model"], "tiny.en"); +}); + +test("auto TTS reacts to idle with the last assistant turn", async () => { + const { context, store, toasts } = createFakeContext(); + const handlers = new Map(); + context.data.on = (type, handler) => { + handlers.set(type, handler); + return () => {}; + }; + context.data.session.message = { + list: () => [ + { type: "user", id: "msg_user", text: "hello", time: { created: 1 } }, + { + type: "assistant", + id: "msg_assistant", + content: [{ type: "text", text: "hello from the assistant" }], + time: { created: 2 }, + }, + ], + }; + + const plugin = createPluginDefinition(); + await plugin.setup(context); + store["tts.mode"] = "on"; + + handlers.get("session.status")({ type: "session.status", data: { status: { type: "busy" } } }); + await handlers.get("session.idle")({ type: "session.idle", data: { sessionID: "ses_test" } }); + + // Without an LLM endpoint the normalization fails; the handler must report + // it instead of silently speaking. + assert.ok( + toasts.some((toast) => String(toast.message).includes("TTS normalization failed")), + "idle handler reports normalization failure", + ); +}); diff --git a/tui.js b/tui.js new file mode 100644 index 0000000..4eb27e8 --- /dev/null +++ b/tui.js @@ -0,0 +1,8 @@ +// TUI entrypoint for local (path-based) plugin loading. +// +// OpenCode V2 resolves the TUI entry of a local plugin directory by looking +// for a `tui` file (tui.ts/tui.tsx/tui.js) instead of the package.json +// "exports" field, which only applies to package-name targets. This file +// re-exports the implementation so both loading styles work. + +export { default } from "./index.js";