@bojackduy/opencode-voice 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,6 +12,105 @@ spoken aloud via Piper TTS. Both directions use an LLM to normalize text for
12
12
  natural speech (fixing homophones, splitting camelCase identifiers, summarizing
13
13
  code-heavy responses, etc.).
14
14
 
15
+ ## OpenCode v1 and v2
16
+
17
+ One package runs on both OpenCode 1.x and 2.x. The plugin detects the host
18
+ by capability (never by version string) and adapts; the v1 path is unchanged.
19
+
20
+ > [!IMPORTANT]
21
+ > **Submit-only mode on v2.** OpenCode v2.0.26 exposes no plugin API for
22
+ > appending text to the composer for editing, so the v1 STT loop of
23
+ > transcribe → append → edit → submit is unimplementable there. On v2 every
24
+ > STT turn **transcribes and submits immediately** via `session.prompt` —
25
+ > both `/stt-record` and `/stt-submit` submit — and the turn toast says
26
+ > submitted, never "added to prompt". A warning toast on first load says the
27
+ > same. There is deliberately no edit step; nothing is faked.
28
+
29
+ ### v1 (OpenCode 1.x)
30
+
31
+ Use the `tui.json` snippet under [Install](#install) — unchanged.
32
+
33
+ ### v2 (OpenCode 2.x)
34
+
35
+ Add the plugin to `cli.json` (create at `~/.config/opencode/cli.json` if it
36
+ doesn't exist):
37
+
38
+ ```json
39
+ {
40
+ "$schema": "https://opencode.ai/v2/cli.json",
41
+ "plugins": [
42
+ {
43
+ "package": "@bojackduy/opencode-voice",
44
+ "options": {
45
+ "endpoint": "https://api.anthropic.com/v1",
46
+ "model": "claude-haiku-4-5",
47
+ "apiKeyEnv": "ANTHROPIC_API_KEY"
48
+ }
49
+ }
50
+ ]
51
+ }
52
+ ```
53
+
54
+ Every plugin option documented below (`sttLanguage`, `ttsEngine`,
55
+ `keybinds`, …) works the same on v2 — options ride `context.options`, and
56
+ the `keybinds` command ids are stable across hosts. To test unpublished
57
+ changes, point `package` at the local repo path instead of the npm name.
58
+
59
+ To verify the plugin loaded: `opencode plugin list` shows it as a `local`
60
+ package (its TUI entrypoint is a literal `tui.js` file — v2 resolves local
61
+ packages by file probe, not by the `exports` map, so that file must exist).
62
+ Then press `Ctrl+P` or type `/` in the composer: all 19 commands are there
63
+ under the `opencode-voice` group with their slash names (`/stt-record`,
64
+ `/tts-speak`, `/voice-cancel`, …), verified live on 2.0.26.
65
+
66
+ > [!NOTE]
67
+ > **Default keybinds on v2.** The defaults (`<leader>[`, `<leader>.`, …)
68
+ > display correctly in the palette (translated to `ctrl+x [` style, since v2
69
+ > bind strings have no `<leader>` token) but multi-key sequences do not
70
+ > dispatch on 2.0.26 — only single-combo binds fire (verified: an overridden
71
+ > `"keybinds": { "voice.cancel": "ctrl+r" }` runs the command, while
72
+ > `ctrl+x .` stays silent). Until the host fixes sequence dispatch, override
73
+ > any keybind you need with a single combo via the `keybinds` option; every
74
+ > command stays reachable via palette and `/slash` regardless.
75
+
76
+ `engines` status: the package declares no `engines.opencode` field, so both
77
+ v1 and v2 load it unconstrained. A version pin was considered and skipped on
78
+ purpose: it could refuse to load on untested hosts for no benefit, since
79
+ capability detection already picks the right path per host.
80
+
81
+ ### Per-feature v2 caveats
82
+
83
+ - **Commands:** all 19 register with the same ids, titles, palette group,
84
+ slash names, and keybinds as v1. On 2.0.26 the `/slash` completion lists
85
+ every one reliably; the `Ctrl+P` palette shows them for matching queries
86
+ but its search occasionally reports no results for queries that should
87
+ match — when in doubt, use `/slash`.
88
+ - **STT (batch):** submits immediately, no edit step (see above). With no
89
+ active session the transcript is kept via warning toast and nothing is
90
+ submitted.
91
+ - **STT (streaming dictation):** live composer previews and finalize-insert
92
+ have no v2 primitive, so finalizing keeps the dictated text via toast
93
+ instead of inserting or submitting. Untested on v2 beyond that — prefer
94
+ batch mode there.
95
+ - **TTS / conversation / live notes / cancel:** same semantics as v1 (auto
96
+ TTS on idle/permission/question gates, conversation barge-in, live-notes
97
+ background saves, one-key cancel).
98
+ - **Reply-streaming triggers:** `message.part.delta` is remapped to v2's
99
+ `session.text.delta`; `session.idle`, `session.status`, and
100
+ `permission.asked` pass through unchanged. `question.asked` has no v2
101
+ equivalent and is mapped best-effort to `form.created`: with several
102
+ sessions open, a form in one session can pause speech in another.
103
+ Single-session use is unaffected.
104
+ - **Pickers** (`/stt-model`, `/stt-language`, `/stt-mic`, `/tts-voice`,
105
+ `/voice-model`): same options through promise dialogs, including the
106
+ nested provider → model pick.
107
+ - **Settings persistence:** stored via v2 storage (survives restarts, syncs
108
+ across windows). If storage is unavailable the plugin keeps working with
109
+ memory-only settings for the session.
110
+ - **Logging:** v2 has no `client.app.log`, so the debug/warn/error
111
+ diagnostics the plugin writes to the OpenCode log on v1 are silent on v2.
112
+ User-facing warnings still arrive as toasts.
113
+
15
114
  ## Install
16
115
 
17
116
  Add to your `tui.json` (create at `~/.config/opencode/tui.json` if it doesn't
package/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // opencode-voice: Speech-to-text and text-to-speech for OpenCode.
2
2
  //
3
3
  // STT: Record voice via sox, transcribe with whisper-cpp, normalize with
4
- // an OpenAI-compatible LLM, append to the TUI prompt.
4
+ // an OpenAI-compatible LLM, append to the TUI prompt (v1) or submit
5
+ // immediately via session.prompt (v2 submit-only mode, see README
6
+ // "OpenCode v1 and v2").
5
7
  //
6
8
  // TTS: Auto-speak assistant responses (or read on demand) via Piper,
7
9
  // with LLM normalization for natural speech.
@@ -38,96 +40,47 @@
38
40
  // Weird keys [ ] ; were chosen because opencode doesn't use them and shift variants were ignored in terminals.
39
41
  // <leader>v is free in opencode defaults (c/e/s/m/a/y/u/r/h etc. are taken) and mnemonic for voice.
40
42
 
41
- import fs from "node:fs";
42
- import os from "node:os";
43
- import { registerSTT } from "./lib/stt.js";
44
- import { registerTTS } from "./lib/tts.js";
45
- import { registerConversation } from "./lib/conversation.js";
46
- import { registerLiveNotes } from "./lib/live-notes.js";
47
- import { registerVoiceCancel } from "./lib/cancel.js";
48
- import { registerVoiceModel, resolveVoiceProviderModel } from "./lib/voice-model.js";
49
- import { createClient } from "./lib/llm-client.js";
50
- import { createLogger } from "./lib/logger.js";
51
-
52
- function loadPromptFile(filePath, logger, name) {
53
- if (!filePath) return null;
54
- const resolved = filePath.replace(/^~(?=\/|$)/, os.homedir());
55
- try {
56
- const prompt = fs.readFileSync(resolved, "utf-8").trim() || null;
57
- logger?.log(
58
- "plugin",
59
- prompt ? `Loaded ${name} prompt: ${resolved}` : `Ignored empty ${name} prompt: ${resolved}`,
60
- "debug",
61
- );
62
- return prompt;
63
- } catch (err) {
64
- logger?.log("Plugin", `Failed to load ${name} prompt ${resolved}: ${err.message}`, "warn");
65
- return null;
66
- }
67
- }
43
+ import { bootVoice } from "./lib/boot.js";
44
+ import { adaptV2Context } from "./lib/v2-compat.js";
68
45
 
46
+ // Dual-compat export: v1's loader reads `tui`, v2's reads `setup`
47
+ // (`Plugin.define` is an identity wrapper, so a plain object carries both).
48
+ // Each host ignores the other's key. The core (`bootVoice`) is shared; v2
49
+ // runs it over the v2-compat adapted api in submit-only mode.
69
50
  export default {
70
51
  id: "opencode-voice",
71
52
  tui: async (api, options) => {
72
- const { kv } = api;
73
- const logger = createLogger(api.client);
74
- logger.log("plugin", "Initializing", "debug");
75
- // Session-scoped gateways (opencode.ai/zen/go) require x-opencode-session.
76
- // Read the live route at call time so normalize works in any session.
77
- // The voice-selected provider (/voice-model) fills endpoint/model only
78
- // when the explicit options leave them out.
79
- const { complete } = createClient(
80
- options,
81
- logger,
82
- () => {
83
- const route = api?.route?.current;
84
- return route?.name === "session" ? route?.params?.sessionID : undefined;
53
+ await bootVoice(api, options);
54
+ },
55
+ setup: async (ctx) => {
56
+ const adapted = adaptV2Context(ctx);
57
+ await bootVoice(adapted.api, ctx.options, {
58
+ submitOnly: true,
59
+ onReady: async ({ logger }) => {
60
+ // First-run submit-only notice (required UX disclosure): v2 has no
61
+ // append-to-composer API, so every STT turn submits immediately.
62
+ const notice =
63
+ "Voice on OpenCode v2: transcripts submit immediately as-is " +
64
+ "(submit-only mode — append-for-edit is unavailable on v2)";
65
+ adapted.api.ui.toast({ message: notice, variant: "warning", duration: 8000 });
66
+ logger?.log?.("plugin", `v2 submit-only mode: ${notice}`, "warn");
67
+ // v2 has no client.app.log, so the logger above is a no-op: compat
68
+ // warnings must surface as a toast or they are lost entirely.
69
+ if (adapted.warnMessages.length > 0) {
70
+ const shown = adapted.warnMessages.slice(0, 3).join(" | ");
71
+ const rest =
72
+ adapted.warnMessages.length > 3 ? ` (+${adapted.warnMessages.length - 3} more)` : "";
73
+ adapted.api.ui.toast({
74
+ message: `Voice v2 compat: ${shown}${rest}`,
75
+ variant: "warning",
76
+ duration: 8000,
77
+ });
78
+ }
79
+ for (const message of adapted.warnMessages) {
80
+ logger?.log?.("plugin", `v2-compat: ${message}`, "warn");
81
+ }
85
82
  },
86
- () => resolveVoiceProviderModel(api, kv),
87
- );
88
-
89
- const prompts = {
90
- stt: loadPromptFile(options?.sttPrompt, logger, "STT"),
91
- ttsAuto: loadPromptFile(options?.ttsAutoPrompt, logger, "TTS auto"),
92
- ttsManual: loadPromptFile(options?.ttsManualPrompt, logger, "TTS manual"),
93
- };
94
-
95
- const shared = {};
96
- const stt = registerSTT(api, kv, complete, prompts, options, logger, {
97
- isConversationActive: () => shared.conversation?.isActive() === true,
98
- onConversationKey: (source) => shared.conversation?.onKey(source),
99
- isLiveNotesActive: () => shared.liveNotes?.isActive() === true,
100
- });
101
- const tts = registerTTS(api, kv, complete, prompts, options, logger, {
102
- isConversationActive: () => shared.conversation?.isActive() === true,
103
- onConversationStopKey: () => shared.conversation?.onTtsStop() === true,
104
83
  });
105
- const conversation = registerConversation(api, options, logger, {
106
- stt: stt.controller,
107
- tts: tts.controller,
108
- isLiveNotesActive: () => shared.liveNotes?.isActive() === true,
109
- });
110
- shared.conversation = conversation.controller;
111
- const liveNotes = registerLiveNotes(api, kv, complete, options, logger, {
112
- tts: tts.controller,
113
- isConversationActive: () => shared.conversation?.isActive() === true,
114
- });
115
- shared.liveNotes = liveNotes.controller;
116
- const voiceModel = registerVoiceModel(api, kv, options, logger);
117
- const cancel = registerVoiceCancel(api, options, logger, {
118
- stt: stt.controller,
119
- tts: tts.controller,
120
- conversation: shared.conversation,
121
- liveNotes: shared.liveNotes,
122
- });
123
-
124
- api.command.register(() => [
125
- ...stt.commands,
126
- ...tts.commands,
127
- ...conversation.commands,
128
- ...liveNotes.commands,
129
- ...voiceModel.commands,
130
- ...cancel.commands,
131
- ]);
84
+ return adapted.cleanup;
132
85
  },
133
86
  };
package/lib/boot.js ADDED
@@ -0,0 +1,106 @@
1
+ // Shared plugin boot for OpenCode v1 (`tui`) and v2 (`setup`).
2
+ //
3
+ // WHY this file exists: v1 and v2 entrypoints differ only in how they obtain
4
+ // an `api` object (raw v1 `TuiPluginApi` vs the v2-compat adapted `Context`).
5
+ // Everything below runs identically on both, so there is exactly one core to
6
+ // maintain. The v1 `tui` path calls `bootVoice(api, options)` with no extras
7
+ // and behaves exactly as before; the v2 `setup` path passes
8
+ // `{ submitOnly: true }` for the first-run notice. No STT/TTS/routing/
9
+ // keybind behavior branches live here.
10
+
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import { registerSTT } from "./stt.js";
14
+ import { registerTTS } from "./tts.js";
15
+ import { registerConversation } from "./conversation.js";
16
+ import { registerLiveNotes } from "./live-notes.js";
17
+ import { registerVoiceCancel } from "./cancel.js";
18
+ import { registerVoiceModel, resolveVoiceProviderModel } from "./voice-model.js";
19
+ import { createClient } from "./llm-client.js";
20
+ import { createLogger } from "./logger.js";
21
+
22
+ function loadPromptFile(filePath, logger, name) {
23
+ if (!filePath) return null;
24
+ const resolved = filePath.replace(/^~(?=\/|$)/, os.homedir());
25
+ try {
26
+ const prompt = fs.readFileSync(resolved, "utf-8").trim() || null;
27
+ logger?.log(
28
+ "plugin",
29
+ prompt ? `Loaded ${name} prompt: ${resolved}` : `Ignored empty ${name} prompt: ${resolved}`,
30
+ "debug",
31
+ );
32
+ return prompt;
33
+ } catch (err) {
34
+ logger?.log("Plugin", `Failed to load ${name} prompt ${resolved}: ${err.message}`, "warn");
35
+ return null;
36
+ }
37
+ }
38
+
39
+ export async function bootVoice(api, options, extras = {}) {
40
+ const { kv } = api;
41
+ const logger = createLogger(api.client);
42
+ logger.log("plugin", "Initializing", "debug");
43
+ // Session-scoped gateways (opencode.ai/zen/go) require x-opencode-session.
44
+ // Read the live route at call time so normalize works in any session.
45
+ // The voice-selected provider (/voice-model) fills endpoint/model only
46
+ // when the explicit options leave them out.
47
+ const { complete } = createClient(
48
+ options,
49
+ logger,
50
+ () => {
51
+ const route = api?.route?.current;
52
+ return route?.name === "session" ? route?.params?.sessionID : undefined;
53
+ },
54
+ () => resolveVoiceProviderModel(api, kv),
55
+ );
56
+
57
+ const prompts = {
58
+ stt: loadPromptFile(options?.sttPrompt, logger, "STT"),
59
+ ttsAuto: loadPromptFile(options?.ttsAutoPrompt, logger, "TTS auto"),
60
+ ttsManual: loadPromptFile(options?.ttsManualPrompt, logger, "TTS manual"),
61
+ };
62
+
63
+ const shared = {};
64
+ const stt = registerSTT(api, kv, complete, prompts, options, logger, {
65
+ isConversationActive: () => shared.conversation?.isActive() === true,
66
+ onConversationKey: (source) => shared.conversation?.onKey(source),
67
+ isLiveNotesActive: () => shared.liveNotes?.isActive() === true,
68
+ });
69
+ const tts = registerTTS(api, kv, complete, prompts, options, logger, {
70
+ isConversationActive: () => shared.conversation?.isActive() === true,
71
+ onConversationStopKey: () => shared.conversation?.onTtsStop() === true,
72
+ });
73
+ const conversation = registerConversation(api, options, logger, {
74
+ stt: stt.controller,
75
+ tts: tts.controller,
76
+ isLiveNotesActive: () => shared.liveNotes?.isActive() === true,
77
+ });
78
+ shared.conversation = conversation.controller;
79
+ const liveNotes = registerLiveNotes(api, kv, complete, options, logger, {
80
+ tts: tts.controller,
81
+ isConversationActive: () => shared.conversation?.isActive() === true,
82
+ });
83
+ shared.liveNotes = liveNotes.controller;
84
+ const voiceModel = registerVoiceModel(api, kv, options, logger);
85
+ const cancel = registerVoiceCancel(api, options, logger, {
86
+ stt: stt.controller,
87
+ tts: tts.controller,
88
+ conversation: shared.conversation,
89
+ liveNotes: shared.liveNotes,
90
+ });
91
+
92
+ api.command.register(() => [
93
+ ...stt.commands,
94
+ ...tts.commands,
95
+ ...conversation.commands,
96
+ ...liveNotes.commands,
97
+ ...voiceModel.commands,
98
+ ...cancel.commands,
99
+ ]);
100
+
101
+ if (extras?.submitOnly && typeof extras?.onReady === "function") {
102
+ await extras.onReady({ logger, stt, tts, conversation, liveNotes, voiceModel, cancel });
103
+ }
104
+
105
+ return { stt, tts, conversation, liveNotes, voiceModel, cancel, logger };
106
+ }
package/lib/stt.js CHANGED
@@ -1373,7 +1373,7 @@ export function insertIntoFocusedInput(renderer, text, submit = false) {
1373
1373
 
1374
1374
  async function appendTranscription(client, renderer, text, submit) {
1375
1375
  if (insertIntoFocusedInput(renderer, text, submit)) {
1376
- return;
1376
+ return true;
1377
1377
  }
1378
1378
 
1379
1379
  let appendResult = await client.tui.appendPrompt({ body: { text } });
@@ -1391,6 +1391,7 @@ async function appendTranscription(client, renderer, text, submit) {
1391
1391
  if (submit) {
1392
1392
  await client.tui.submitPrompt();
1393
1393
  }
1394
+ return appendResult;
1394
1395
  }
1395
1396
 
1396
1397
  // Transcribe the finished recording and normalize it, without touching the
@@ -1500,10 +1501,19 @@ async function submitTurnText(client, renderer, toast, text, logger) {
1500
1501
 
1501
1502
  async function appendTurnText(client, renderer, toast, text, logger) {
1502
1503
  try {
1503
- await appendTranscription(client, renderer, text, false);
1504
+ const appendResult = await appendTranscription(client, renderer, text, false);
1504
1505
  clearProcessingToast();
1505
1506
  logger?.log("STT", `Turn appended chars=${text.length}`, "debug");
1506
- toast("Transcription added to prompt", "success");
1507
+ // Submit-only hosts (OpenCode v2: no append-to-composer API) submit via
1508
+ // the client shim, which marks the result — so the toast must not claim
1509
+ // the text was "added to prompt" for editing there. v1 results carry no
1510
+ // marker and keep the original toast.
1511
+ toast(
1512
+ appendResult?.submitted === true
1513
+ ? "Transcription submitted as-is (submit-only mode)"
1514
+ : "Transcription added to prompt",
1515
+ "success",
1516
+ );
1507
1517
  return { text };
1508
1518
  } catch (err) {
1509
1519
  clearProcessingToast();
@@ -0,0 +1,431 @@
1
+ // OpenCode v2 compatibility shim (submit-only mode).
2
+ //
3
+ // WHY this file exists: v2's TUI plugin `Context` renamed or replaced every
4
+ // v1 `TuiPluginApi` surface this plugin uses (see the drift table in the
5
+ // research goal's progress.md). Rather than forking every lib module, this
6
+ // adapter presents a v1-shaped `api` over a v2 `Context` so the SAME core
7
+ // modules run unmodified. Every mapping is capability-detected (feature
8
+ // presence, never version strings), and every surface with no v2 path
9
+ // degrades loudly (warn log + honest toast), never silently.
10
+ //
11
+ // Non-negotiable product decision (user-accepted): v2 2.0.26 has no
12
+ // plugin-reachable append-to-composer API (`tui.prompt.append` exists only
13
+ // as a server→TUI event type, not a client method). So on v2, STT
14
+ // transcribes and SUBMITS immediately via `session.prompt`. The adapted api
15
+ // passes `renderer: null` so `appendTranscription` skips the focused-input
16
+ // insert path and lands on the client shim below, which submits.
17
+
18
+ // Event renames with no same-named v2 equivalent. Values are the v2 event
19
+ // type to subscribe to instead (both verified present in the v2
20
+ // `OpenCodeEvent` union; `question.asked` has NO v2 counterpart —
21
+ // `form.created` is the closest gate signal and is best-effort, see below).
22
+ const EVENT_REMAP = {
23
+ "message.part.delta": "session.text.delta",
24
+ "question.asked": "form.created",
25
+ };
26
+
27
+ // Capability probe: v2 TUI `Context` has all three of these; v1 `api` has
28
+ // none under these paths. Never version-sniff.
29
+ export function isV2Context(ctx) {
30
+ return (
31
+ !!ctx &&
32
+ typeof ctx?.keymap?.layer === "function" &&
33
+ typeof ctx?.ui?.toast?.show === "function" &&
34
+ !!ctx?.storage
35
+ );
36
+ }
37
+
38
+ // Wrap a v2 event envelope `{type, data}` so v1-style handlers reading
39
+ // `event.properties` keep working. v1 handlers also read renamed fields,
40
+ // normalized per remapped type below.
41
+ function wrapHandler(type, fn) {
42
+ return (event) => {
43
+ const data = event?.data ?? event?.properties ?? {};
44
+ let properties = { ...data };
45
+ if (type === "message.part.delta") {
46
+ // v2 `session.text.delta` data: {sessionID, assistantMessageID, delta}.
47
+ // v1 handler expects {sessionID, messageID, delta, field}.
48
+ properties = {
49
+ ...properties,
50
+ messageID: data.assistantMessageID ?? data.messageID,
51
+ field: "text",
52
+ };
53
+ }
54
+ if (type === "question.asked") {
55
+ // v2 `form.created` data: {form}. The form may not carry a sessionID;
56
+ // an absent sessionID matches the current session in our handlers
57
+ // (`forSession` treats missing as match), which is correct for the
58
+ // common single-session case. Multi-session over-triggering is
59
+ // possible and documented in the README caveat list.
60
+ properties = { ...data, ...data?.form, sessionID: data?.sessionID ?? data?.form?.sessionID };
61
+ }
62
+ try {
63
+ fn({ ...event, properties });
64
+ } catch {
65
+ // Handlers are already internally guarded; never let a mapping throw.
66
+ }
67
+ };
68
+ }
69
+
70
+ // Sync `kv` facade over v2 async `storage`. v2 `storage.store` is a
71
+ // solid-store pair; our lib modules need synchronous get/set, so the facade
72
+ // mirrors values in memory and persists fire-and-forget. Worst case (persist
73
+ // fails or storage shape differs) the in-memory values still work for the
74
+ // session — settings just don't survive restart.
75
+ function createKv(storage, warn) {
76
+ const mem = new Map();
77
+ let update = null;
78
+ try {
79
+ const pair = storage.store("opencode-voice", { initial: { values: {} } });
80
+ const store = pair?.[0];
81
+ update = typeof pair?.[1] === "function" ? pair[1] : null;
82
+ for (const [k, v] of Object.entries(store?.values ?? {})) mem.set(k, v);
83
+ } catch (err) {
84
+ warn?.(`kv seed from v2 storage failed, using memory only: ${err?.message || err}`);
85
+ }
86
+ return {
87
+ get(k, fb) {
88
+ return mem.has(k) ? mem.get(k) : fb;
89
+ },
90
+ set(k, v) {
91
+ mem.set(k, v);
92
+ if (update) {
93
+ const snapshot = Object.fromEntries(mem);
94
+ void Promise.resolve()
95
+ .then(() => update((draft) => void (draft.values = snapshot)))
96
+ .catch(() => {});
97
+ }
98
+ },
99
+ };
100
+ }
101
+
102
+ // `api.ui.dialog.replace(() => api.ui.DialogSelect(props))` over v2 promise
103
+ // `dialog.select`. Our 7 call sites all use option-level `onSelect` (no
104
+ // top-level `onSelect`), but both are honored. `dialog.clear()` inside an
105
+ // option handler is a no-op on v2 (promise dialogs close on resolve).
106
+ function createDialog(dialog, warn) {
107
+ async function runSelect(props) {
108
+ const options = (props?.options || []).map((o) => ({
109
+ title: o?.title,
110
+ value: o?.value,
111
+ description: o?.description,
112
+ footer: o?.footer,
113
+ category: o?.category,
114
+ disabled: o?.disabled,
115
+ }));
116
+ let chosen;
117
+ try {
118
+ chosen = await dialog.select({
119
+ title: props?.title,
120
+ placeholder: props?.placeholder,
121
+ options,
122
+ current: props?.current,
123
+ });
124
+ } catch (err) {
125
+ warn?.(`dialog.select failed: ${err?.message || err}`);
126
+ return;
127
+ }
128
+ if (chosen === undefined) return; // dismissed
129
+ const match = (props?.options || []).find((o) => o?.value === chosen);
130
+ try {
131
+ if (match?.onSelect) await match.onSelect();
132
+ else if (typeof props?.onSelect === "function") await props.onSelect(chosen);
133
+ } catch (err) {
134
+ warn?.(`dialog option handler failed: ${err?.message || err}`);
135
+ }
136
+ }
137
+ return {
138
+ replace(render) {
139
+ let rendered;
140
+ try {
141
+ rendered = render();
142
+ } catch (err) {
143
+ warn?.(`dialog.replace render failed: ${err?.message || err}`);
144
+ return;
145
+ }
146
+ const props = rendered?.__v2DialogSelect ? rendered.props : null;
147
+ if (!props) {
148
+ warn?.("dialog.replace called with non-DialogSelect content (no v2 path), ignored");
149
+ return;
150
+ }
151
+ void runSelect(props);
152
+ },
153
+ clear() {},
154
+ };
155
+ }
156
+
157
+ function DialogSelect(props) {
158
+ return { __v2DialogSelect: true, props: props || {} };
159
+ }
160
+
161
+ export function adaptV2Context(ctx) {
162
+ const disposers = [];
163
+ const warned = new Set();
164
+ const warnMessages = [];
165
+ // Loud degradation: warn logs are collected for evidence and also sent
166
+ // through the real logger once boot creates it (wired via onWarn below).
167
+ let warnSink = null;
168
+ const warn = (message) => {
169
+ if (warned.has(message)) return;
170
+ warned.add(message);
171
+ warnMessages.push(message);
172
+ try {
173
+ warnSink?.(`v2-compat: ${message}`);
174
+ } catch {}
175
+ };
176
+
177
+ const toast = (input) => {
178
+ try {
179
+ const options = typeof input === "string" ? { message: input } : input || {};
180
+ ctx.ui.toast.show({
181
+ title: options.title,
182
+ message: options.message ?? "",
183
+ variant: options.variant,
184
+ duration: options.duration,
185
+ sessionID: options.sessionID,
186
+ });
187
+ } catch {}
188
+ };
189
+
190
+ function currentSessionID() {
191
+ try {
192
+ const route = ctx.ui.router.current();
193
+ return route?.type === "session" ? route?.sessionID : undefined;
194
+ } catch {
195
+ return undefined;
196
+ }
197
+ }
198
+
199
+ async function submitTextAsPrompt(text) {
200
+ const sessionID = currentSessionID();
201
+ if (!sessionID) {
202
+ const kept = String(text || "").slice(0, 120);
203
+ toast({
204
+ message: `Voice: no active session — transcript kept on screen, nothing submitted (${kept})`,
205
+ variant: "warning",
206
+ duration: 5000,
207
+ });
208
+ warn("submit attempted with no active session; transcript not submitted");
209
+ throw new Error("No active session to submit to");
210
+ }
211
+ await ctx.client.session.prompt({ sessionID, text: String(text || "") });
212
+ // No toast here: the caller's turn toast (appendTurnText/submitTurnText)
213
+ // reports the submit, keyed off the `submitted` marker below. One toast
214
+ // per turn, never a faked edit step.
215
+ }
216
+
217
+ // `Object.create` (not spread) so client methods keep their `this`.
218
+ const client = Object.create(ctx.client, {
219
+ // `client.app.log` has no v2 path — silent no-op (pre-existing `?.`
220
+ // tolerance in createLogger already expects absence).
221
+ app: { value: { log: async () => {} } },
222
+ tui: {
223
+ value: {
224
+ // Submit-only: append-for-edit is unimplementable on v2, so append
225
+ // becomes submit. Accepts both v1 call shapes ({body:{text}} and
226
+ // {text}) used by stt.js. The `submitted` marker lets the caller's
227
+ // toast report a submit instead of an edit-step append.
228
+ appendPrompt: async (input) => {
229
+ await submitTextAsPrompt(input?.body?.text ?? input?.text ?? "");
230
+ return { data: null, submitted: true };
231
+ },
232
+ submitPrompt: async () => {},
233
+ },
234
+ },
235
+ });
236
+
237
+ const dialog = createDialog(ctx.ui.dialog, warn);
238
+
239
+ const api = {
240
+ client,
241
+ // Submit-only enforcement: with no renderer, `appendTranscription`
242
+ // skips `insertIntoFocusedInput` and lands on the client shim above,
243
+ // which submits via `session.prompt`. v2 renderer streaming previews
244
+ // are therefore disabled by construction, not by flag.
245
+ renderer: null,
246
+ ui: { toast, dialog, DialogSelect },
247
+ event: {
248
+ on: (type, fn) => {
249
+ const remapped = EVENT_REMAP[type];
250
+ if (remapped) warn(`event "${type}" remapped to v2 "${remapped}"`);
251
+ if (type === "question.asked") {
252
+ warn(
253
+ 'event "question.asked" has no v2 equivalent; best-effort mapping to "form.created" ' +
254
+ "(may over-trigger with multiple sessions)",
255
+ );
256
+ }
257
+ try {
258
+ return ctx.data.on(remapped || type, wrapHandler(type, fn));
259
+ } catch (err) {
260
+ warn(`event subscribe "${type}" failed: ${err?.message || err}`);
261
+ return () => {};
262
+ }
263
+ },
264
+ },
265
+ lifecycle: {
266
+ onDispose: (fn) => void disposers.push(fn),
267
+ },
268
+ kv: createKv(ctx.storage, warn),
269
+ route: {
270
+ get current() {
271
+ const route = ctx.ui.router.current();
272
+ if (route?.type === "session") {
273
+ return { name: "session", params: { sessionID: route.sessionID } };
274
+ }
275
+ return { name: route?.type || "home", params: {} };
276
+ },
277
+ },
278
+ state: {
279
+ session: {
280
+ messages: (sessionID) => {
281
+ try {
282
+ return ctx.data.session.message.list(sessionID) || [];
283
+ } catch {
284
+ return [];
285
+ }
286
+ },
287
+ },
288
+ // v1 `state.part(messageID)` (message parts) has no v2 data path;
289
+ // callers treat a missing part as "not non-text" and proceed.
290
+ part: () => [],
291
+ path: {
292
+ // v2 `location` is a LocationRef, not a directory string.
293
+ get directory() {
294
+ try {
295
+ return ctx.location?.directory || process.cwd();
296
+ } catch {
297
+ return process.cwd();
298
+ }
299
+ },
300
+ },
301
+ },
302
+ command: {
303
+ register: (getCommands) => {
304
+ let commands = [];
305
+ try {
306
+ commands = getCommands() || [];
307
+ } catch (err) {
308
+ warn(`command registration failed: ${err?.message || err}`);
309
+ return;
310
+ }
311
+ // v1 `{title, value, category, description, keybind?, slash?, onSelect}`
312
+ // → v2 `KeymapCommand {id, title, group, bind, palette, slash, run}`
313
+ // + layer `bindings`. Every command joins palette + slash so all
314
+ // stay reachable; keybinds are translated below (invalid binds are
315
+ // reported by the host parser, not here).
316
+ // v1 bind strings use a `<leader>X` token for two-key sequences; v2
317
+ // bind strings have no leader token — sequences are space-separated
318
+ // keys with +-joined modifiers, and the leader is literally ctrl+x
319
+ // (cf the builtin "Switch model ctrl+x m"). Anything else passes
320
+ // through untouched (v2-native "ctrl+r" style binds need no mapping).
321
+ const toV2Bind = (bind) => {
322
+ if (typeof bind !== "string" || bind.length === 0) return false;
323
+ const leader = bind.match(/^<leader>(.+)$/);
324
+ if (leader) return `ctrl+x ${leader[1]}`;
325
+ return bind;
326
+ };
327
+ const mapped = commands.map((c) => ({
328
+ id: c?.value,
329
+ title: c?.title,
330
+ description: c?.description,
331
+ group: c?.category,
332
+ bind: toV2Bind(c?.keybind),
333
+ palette: true,
334
+ slash: c?.slash ? { name: c.slash.name, aliases: c.slash.aliases } : undefined,
335
+ run: (...args) => c?.onSelect?.(...args),
336
+ }));
337
+ const registerLayer = () => {
338
+ try {
339
+ ctx.keymap.layer(() => ({
340
+ mode: "global",
341
+ commands: mapped.map((c) => {
342
+ const cmd = {
343
+ id: c.id,
344
+ title: c.title,
345
+ group: c.group,
346
+ palette: true,
347
+ slash: c.slash,
348
+ run: c.run,
349
+ };
350
+ if (c.description) cmd.description = c.description;
351
+ if (typeof c.bind === "string" && c.bind.length > 0) cmd.bind = c.bind;
352
+ return cmd;
353
+ }),
354
+ // Binds are displayed from command.bind but only become
355
+ // ACTIVE when listed here — verified live: without this the
356
+ // palette shows the shortcut yet the keystroke does nothing.
357
+ // Only ids with a real bind string join (binding a bind-less
358
+ // id is contradictory).
359
+ bindings: mapped
360
+ .filter((c) => typeof c.bind === "string" && c.bind.length > 0)
361
+ .map((c) => c.id),
362
+ }));
363
+ } catch (err) {
364
+ warn(`keymap.layer rejected commands: ${err?.message || err}`);
365
+ }
366
+ };
367
+ // layer() must run inside a component: the host resolves the layer
368
+ // against the ambient Keymap provider, and a direct call in setup()
369
+ // never registers (the failure surfaces only as missing commands,
370
+ // never as an error). So claim the always-mounted "app" slot with
371
+ // a null-render component as the mount point and register once
372
+ // from its render. Unclaiming on dispose removes the layer.
373
+ if (typeof ctx.ui?.slot === "function") {
374
+ let claimed = false;
375
+ try {
376
+ const unclaim = ctx.ui.slot({
377
+ append: "app",
378
+ render: () => {
379
+ if (!claimed) {
380
+ claimed = true;
381
+ registerLayer();
382
+ }
383
+ return null;
384
+ },
385
+ });
386
+ disposers.push(() => {
387
+ try {
388
+ unclaim();
389
+ } catch {}
390
+ });
391
+ return;
392
+ } catch (err) {
393
+ warn(`slot claim for keymap failed, trying direct layer: ${err?.message || err}`);
394
+ }
395
+ }
396
+ registerLayer();
397
+ },
398
+ },
399
+ };
400
+
401
+ // v1 reads `api.state.provider` as an array (`resolveVoiceProviderModel`
402
+ // does `api?.state?.provider || []` then `.find`); v2 lists per location.
403
+ // A getter keeps the array shape without touching callers.
404
+ Object.defineProperty(api.state, "provider", {
405
+ get() {
406
+ try {
407
+ return ctx.data.location.provider.list() || [];
408
+ } catch {
409
+ return [];
410
+ }
411
+ },
412
+ enumerable: true,
413
+ });
414
+
415
+ function cleanup() {
416
+ for (const fn of disposers.splice(0)) {
417
+ try {
418
+ const r = fn();
419
+ if (r?.then) void r.catch(() => {});
420
+ } catch {}
421
+ }
422
+ }
423
+
424
+ return {
425
+ api,
426
+ cleanup,
427
+ submitOnly: true,
428
+ warnMessages,
429
+ onWarn: (sink) => void (warnSink = sink),
430
+ };
431
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bojackduy/opencode-voice",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "Speech-to-text and text-to-speech for OpenCode. Record voice prompts with whisper-cpp, hear responses via Piper TTS, with LLM normalization through any OpenAI-compatible endpoint.",
5
5
  "keywords": [
6
6
  "opencode",
@@ -20,6 +20,7 @@
20
20
  },
21
21
  "files": [
22
22
  "index.js",
23
+ "tui.js",
23
24
  "lib"
24
25
  ],
25
26
  "type": "module",
package/tui.js ADDED
@@ -0,0 +1,14 @@
1
+ // OpenCode v2 TUI entrypoint (file probe, not package exports).
2
+ //
3
+ // WHY this file exists: v2 resolves a package's TUI entrypoint by probing
4
+ // for a literal `./tui` FILE inside the package directory
5
+ // (`resolve({directory})` → `path.resolve(directory, "tui")` in
6
+ // `@opencode/plugin`'s host mirror) — package.json `exports["./tui"]` alone
7
+ // is NOT consulted for path-form packages, so without this file v2 silently
8
+ // skips the package entirely (proven: `plugin list` empty before, listed
9
+ // after). v1 keeps loading via `exports["./tui"]` → `./index.js`, unchanged.
10
+ //
11
+ // Single core: this re-exports the same default object (with both `tui` for
12
+ // v1 and `setup` for v2) — each host reads its own key off the one module
13
+ // instance. See index.js, lib/boot.js, lib/v2-compat.js.
14
+ export { default } from "./index.js";