@luxass/pi-voice 0.1.0 → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lucas Nørgård
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -8,22 +8,24 @@ Record speech and paste the transcription into [Pi](https://github.com/badlogic/
8
8
  pi install npm:@luxass/pi-voice
9
9
  ```
10
10
 
11
- Recording requires `sox` on your `PATH`. For local transcription, you also need `whisper-cli` and a compatible Whisper model. Alternatively, add an API transcription profile; that does not require a local Whisper installation.
11
+ Requires Node.js 24+ and microphone access. Linux also needs `libasound.so.2`. Run `/voice setup` to choose a local or API transcription profile and an input device. Local transcription uses GGUF models; the model picker can download Whisper or Parakeet models.
12
12
 
13
13
  ## Use
14
14
 
15
- Press **Ctrl+Shift+V** or run `/voice-record` to start recording. Press it again to stop, transcribe, and paste the result into the composer. The extension does not send your message for you.
15
+ Press **Ctrl+Shift+V** or run `/voice` to start recording. Requirements are checked before the microphone starts. If something is missing, Voice explains it and offers to open setup. Completing setup does not start recording; press the shortcut or run `/voice` again when you are ready. Press it again to stop, transcribe, and paste the result into the composer. The extension does not send your message for you.
16
16
 
17
- | Command | Purpose |
18
- | ---------------------- | ----------------------------------------------- |
19
- | `/voice-record` | Start or stop recording and transcribe on stop. |
20
- | `/voice-cancel` | Discard the current recording. |
21
- | `/voice-device` | Choose an input device or the system default. |
22
- | `/voice-profile add` | Create a local or API transcription profile. |
23
- | `/voice-profile` | Switch between saved profiles. |
24
- | `/voice-profile model` | Change the active API profile's model. |
25
- | `/voice-status` | Show the current profile and input device. |
17
+ | Command | Purpose |
18
+ | ---------------------- | ---------------------------------------------------- |
19
+ | `/voice` | Start or stop recording and transcribe on stop. |
20
+ | `/voice cancel` | Discard the current recording. |
21
+ | `/voice setup` | Choose a profile and input, then check requirements. |
22
+ | `/voice device` | Choose an input device or the system default. |
23
+ | `/voice profile add` | Create a local or API transcription profile. |
24
+ | `/voice profile` | Switch between saved profiles. |
25
+ | `/voice profile model` | Change the active profile's model. |
26
+ | `/voice status` | Show the current profile and input device. |
27
+ | `/voice doctor` | Check recording and transcription setup. |
26
28
 
27
- Without a saved profile, transcription uses automatic local model discovery. For API transcription, `/voice-profile add` asks for the endpoint, model, request format, and **name of an environment variable** holding the API key. Keep the key in your environment, not in the settings file.
29
+ A local profile without an explicit model uses the first GGUF model in `~/.cache/agent-voice`. Set `AGENT_VOICE_MODEL_DIR` to keep models elsewhere. For API transcription, `/voice profile add` asks for the endpoint, model, request format, and **name of an environment variable** holding the API key. Keep the key in your environment, not in the settings file.
28
30
 
29
- Settings are saved to Pi's agent directory as `voice-settings.json`. Set `AGENT_VOICE_SETTINGS` to use a different settings file.
31
+ Settings are loaded once at boot from Pi's agent directory, using `voice-settings.json`. Set `AGENT_VOICE_SETTINGS` to use a different file. TypeBox validates known fields, while extra keys are accepted without warnings. If the file is missing, Voice shows a setup hint. If it cannot be loaded or validated, Voice shows the errors and keeps `/voice setup` available. Loading never rewrites the file. Setup saves a complete configuration and updates it in memory; manual file edits require `/reload`. A recording keeps the profile it started with.
package/package.json CHANGED
@@ -1,10 +1,18 @@
1
1
  {
2
2
  "name": "@luxass/pi-voice",
3
- "version": "0.1.0",
4
- "description": "Voice recording and transcription for Pi",
3
+ "version": "0.3.0",
4
+ "description": "Record voice input with /voice, transcribe locally or through an API, and paste it into Pi's composer.",
5
5
  "keywords": [
6
- "pi-package"
6
+ "dictation",
7
+ "pi",
8
+ "pi-extension",
9
+ "pi-package",
10
+ "speech-to-text",
11
+ "transcription",
12
+ "voice",
13
+ "whisper"
7
14
  ],
15
+ "license": "MIT",
8
16
  "repository": {
9
17
  "type": "git",
10
18
  "url": "https://github.com/luxass/pi-extensions",
@@ -12,26 +20,34 @@
12
20
  },
13
21
  "files": [
14
22
  "src",
15
- "README.md"
23
+ "README.md",
24
+ "LICENSE"
16
25
  ],
17
26
  "type": "module",
18
27
  "publishConfig": {
19
28
  "access": "public"
20
29
  },
21
30
  "dependencies": {
22
- "@luxass/agent-voice": "0.1.0"
31
+ "@luxass/agent-voice": "0.5.0"
23
32
  },
24
33
  "peerDependencies": {
25
34
  "@earendil-works/pi-ai": "*",
26
35
  "@earendil-works/pi-coding-agent": "*",
27
36
  "@earendil-works/pi-tui": "*"
28
37
  },
38
+ "engines": {
39
+ "node": ">=24"
40
+ },
29
41
  "pi": {
30
42
  "extensions": [
31
43
  "./src/index.ts"
32
44
  ]
33
45
  },
34
46
  "scripts": {
35
- "typecheck": "tsc --noEmit -p tsconfig.json"
47
+ "lint": "oxlint --deny-warnings .",
48
+ "lint:fix": "oxlint --fix --deny-warnings .",
49
+ "fmt": "oxfmt .",
50
+ "fmt:check": "oxfmt --check .",
51
+ "typecheck": "tsc -p tsconfig.json"
36
52
  }
37
53
  }
package/src/index.ts CHANGED
@@ -9,60 +9,165 @@ import { Key } from "@earendil-works/pi-tui";
9
9
  import {
10
10
  createRecorder,
11
11
  getActiveProfile,
12
- listInputDevices,
13
12
  loadVoiceSettings,
13
+ runDoctor,
14
14
  saveVoiceSettings,
15
15
  transcribe,
16
+ type DoctorCheck,
17
+ type DoctorCheckId,
18
+ type Recorder,
19
+ type VoiceSettings,
16
20
  } from "@luxass/agent-voice";
17
21
 
18
- import { promptProfile } from "./profile";
22
+ import { pickLocalModel, promptProfile } from "./profile";
23
+ import { promptInputDevice, promptSetup } from "./setup";
24
+
25
+ const SUBCOMMANDS = [
26
+ { value: "record", description: "start/stop recording, transcribe on stop" },
27
+ { value: "cancel", description: "discard the in-progress recording" },
28
+ { value: "setup", description: "configure transcription and input, then check requirements" },
29
+ { value: "device", description: "select input device" },
30
+ { value: "profile", description: "select transcription profile" },
31
+ { value: "profile add", description: "create a transcription profile" },
32
+ { value: "profile model", description: "change the active profile's model" },
33
+ { value: "doctor", description: "check recording and transcription setup" },
34
+ { value: "status", description: "show profile and input" },
35
+ ];
36
+
37
+ const DOCTOR_FIXES: Partial<Record<DoctorCheckId, string>> = {
38
+ device: "run /voice device",
39
+ model: "run /voice profile model",
40
+ };
41
+
42
+ function formatChecks(checks: DoctorCheck[]): string {
43
+ return checks
44
+ .map(({ id, ok, detail, fix }) =>
45
+ ok ? `✓ ${id}: ${detail}` : `✗ ${id}: ${detail} → ${DOCTOR_FIXES[id] ?? fix}`,
46
+ )
47
+ .join("\n");
48
+ }
49
+
50
+ function statusText(settings: VoiceSettings, state = "idle"): string {
51
+ const { name, transcription } = getActiveProfile(settings);
52
+ const model =
53
+ transcription.type === "api"
54
+ ? transcription.model
55
+ : basename(transcription.model ?? "auto model", ".gguf");
56
+ return `voice ${state} · ${name} · ${model} · ${settings.inputDevice?.name ?? "system default"}`;
57
+ }
19
58
 
20
59
  export default function voice(pi: ExtensionAPI) {
21
60
  const path = process.env.AGENT_VOICE_SETTINGS ?? join(getAgentDir(), "voice-settings.json");
22
- const settings = loadVoiceSettings(path);
23
- const recorder = createRecorder();
24
-
25
- function statusText(state = recorder.isRecording ? "● recording" : "ready"): string {
26
- const { name, transcription } = getActiveProfile(settings);
27
- const model =
28
- transcription.type === "api"
29
- ? transcription.model
30
- : transcription.model === undefined
31
- ? "auto model"
32
- : basename(transcription.model, ".bin");
33
- return `voice ${state} · ${name} · ${model} · ${settings.inputDevice?.name ?? "system default"}`;
61
+ let configuration = loadVoiceSettings(path);
62
+ let recorder: Recorder | undefined;
63
+ let recording: { settings: VoiceSettings; recorder: Recorder } | undefined;
64
+ let busy = false;
65
+
66
+ function setupMessage(): string {
67
+ return [
68
+ "Voice needs setup. Run /voice setup.",
69
+ ...configuration.errors.map(({ path, message }) => `${path}: ${message}`),
70
+ ].join("\n");
34
71
  }
35
72
 
36
- function showStatus(ui: ExtensionContext["ui"], state?: string): void {
37
- ui.setStatus("voice", statusText(state));
73
+ function save(settings: VoiceSettings): void {
74
+ saveVoiceSettings(path, settings);
75
+ configuration = { settings, errors: [] };
38
76
  }
39
77
 
40
- // Errors thrown from command and shortcut handlers are reported by Pi.
41
- async function toggle(ctx: ExtensionContext): Promise<void> {
42
- if (!recorder.isRecording) {
43
- recorder.start(settings.inputDevice, (error) => {
44
- showStatus(ctx.ui);
45
- ctx.ui.notify(`Recording failed: ${error.message}`, "error");
46
- });
47
- showStatus(ctx.ui);
48
- ctx.ui.notify(
49
- `Recording from ${settings.inputDevice?.name ?? "system default"}… run again to transcribe`,
50
- );
78
+ function showStatus(ui: ExtensionContext["ui"], settings: VoiceSettings, state?: string): void {
79
+ ui.setStatus("voice", statusText(settings, state ?? (recording ? "● recording" : "idle")));
80
+ }
81
+
82
+ async function setup(ctx: ExtensionContext): Promise<void> {
83
+ if (!ctx.hasUI) {
84
+ ctx.ui.notify("Run /voice setup in an interactive Pi session", "info");
51
85
  return;
52
86
  }
87
+ if (recording) {
88
+ ctx.ui.notify("Stop recording before running setup", "warning");
89
+ return;
90
+ }
91
+
92
+ const draft = await promptSetup(ctx.ui, configuration.settings);
93
+ if (draft == null) return;
94
+ const checks = await runDoctor(draft);
95
+ save(draft);
96
+ const ready = checks.every(({ ok }) => ok);
97
+ showStatus(ctx.ui, draft, ready ? "ready" : "needs setup");
98
+ ctx.ui.notify(
99
+ ready
100
+ ? "Voice is ready. Press Ctrl+Shift+V or run /voice to record."
101
+ : `Voice profile saved. Finish these requirements before recording:\n${formatChecks(checks.filter(({ ok }) => !ok))}`,
102
+ ready ? "info" : "warning",
103
+ );
104
+ }
105
+
106
+ async function offerSetup(ctx: ExtensionContext, message: string): Promise<void> {
107
+ ctx.ui.notify(message, configuration.errors.length > 0 ? "warning" : "info");
108
+ if (ctx.hasUI && (await ctx.ui.confirm("Voice needs setup", "Open voice setup now?"))) {
109
+ await setup(ctx);
110
+ }
111
+ }
53
112
 
54
- showStatus(ctx.ui, "transcribing…");
113
+ // Pi reports recording, transcription and save errors from these handlers.
114
+ async function toggle(ctx: ExtensionContext): Promise<void> {
115
+ if (busy) return;
116
+ busy = true;
55
117
  try {
56
- const file = await recorder.stop();
118
+ if (recording) {
119
+ const active = recording;
120
+ recording = undefined;
121
+ showStatus(ctx.ui, active.settings, "transcribing…");
122
+ try {
123
+ const audio = await active.recorder.stop();
124
+ const text = await transcribe(audio, getActiveProfile(active.settings).transcription);
125
+ ctx.ui.pasteToEditor(text);
126
+ ctx.ui.notify("Transcription pasted into the composer", "info");
127
+ } finally {
128
+ showStatus(ctx.ui, active.settings);
129
+ }
130
+ return;
131
+ }
132
+
133
+ const { settings } = configuration;
134
+ if (!settings) {
135
+ await offerSetup(ctx, setupMessage());
136
+ return;
137
+ }
138
+ const checks = await runDoctor(settings);
139
+ if (checks.some(({ ok }) => !ok)) {
140
+ await offerSetup(ctx, formatChecks(checks.filter(({ ok }) => !ok)));
141
+ return;
142
+ }
143
+
144
+ const active = {
145
+ settings: structuredClone(settings),
146
+ recorder: (recorder ??= await createRecorder()),
147
+ };
148
+ recording = active;
149
+ showStatus(ctx.ui, active.settings, "starting…");
57
150
  try {
58
- const text = await transcribe(file, getActiveProfile(settings).transcription);
59
- ctx.ui.pasteToEditor(text);
60
- ctx.ui.notify("Transcription pasted into the composer", "info");
61
- } finally {
62
- recorder.discard(file);
151
+ await active.recorder.start({
152
+ input: active.settings.inputDevice,
153
+ onError: (error) => {
154
+ recording = undefined;
155
+ showStatus(ctx.ui, active.settings);
156
+ ctx.ui.notify(`Recording failed: ${error.message}`, "error");
157
+ },
158
+ });
159
+ } catch (error) {
160
+ recording = undefined;
161
+ showStatus(ctx.ui, active.settings);
162
+ throw error;
63
163
  }
164
+ if (!active.recorder.isRecording) return;
165
+ showStatus(ctx.ui, active.settings);
166
+ ctx.ui.notify(
167
+ `Recording from ${active.settings.inputDevice?.name ?? "system default"}… run again to transcribe`,
168
+ );
64
169
  } finally {
65
- showStatus(ctx.ui);
170
+ busy = false;
66
171
  }
67
172
  }
68
173
 
@@ -71,108 +176,131 @@ export default function voice(pi: ExtensionAPI) {
71
176
  handler: toggle,
72
177
  });
73
178
 
74
- pi.registerCommand("voice-record", {
75
- description: "start/stop recording, transcribe on stop",
76
- handler: (_args, ctx) => toggle(ctx),
77
- });
78
-
79
- pi.registerCommand("voice-cancel", {
80
- description: "discard the in-progress recording",
81
- // oxlint-disable-next-line require-await
82
- handler: async (_args, ctx) => {
83
- if (!recorder.isRecording) return;
84
- recorder.cancel();
85
- showStatus(ctx.ui);
86
- ctx.ui.notify("Recording discarded");
87
- },
88
- });
89
-
90
- pi.registerCommand("voice-device", {
91
- description: "select input device",
92
- handler: async (_args, ctx) => {
93
- if (recorder.isRecording) {
94
- ctx.ui.notify("Stop recording before changing the input", "warning");
95
- return;
96
- }
97
- const devices = await listInputDevices();
98
- const selected = await ctx.ui.select("Voice input device", [
99
- "System default",
100
- ...devices.map((device) => device.name),
101
- ]);
102
- if (selected === undefined) return;
103
- const device = devices.find((candidate) => candidate.name === selected);
104
- if (device) settings.inputDevice = device;
105
- else delete settings.inputDevice;
106
- saveVoiceSettings(path, settings);
107
- showStatus(ctx.ui);
108
- ctx.ui.notify(`Voice input: ${selected}`);
109
- },
110
- });
111
-
112
- pi.registerCommand("voice-profile", {
113
- description: "select transcription profile, `add` one, or change the API `model`",
179
+ pi.registerCommand("voice", {
180
+ description: "start/stop recording, or `/voice <subcommand>`",
114
181
  getArgumentCompletions: (prefix) => {
115
- const items = [
116
- { value: "add", label: "add", description: "create a transcription profile" },
117
- { value: "model", label: "model", description: "change the active API profile's model" },
118
- ].filter((item) => item.value.startsWith(prefix));
182
+ const items = SUBCOMMANDS.filter(({ value }) => value.startsWith(prefix)).map(
183
+ ({ value, description }) => ({ value, label: value, description }),
184
+ );
119
185
  return items.length > 0 ? items : null;
120
186
  },
121
187
  handler: async (args, ctx) => {
122
- const subcommand = args.trim();
123
- if (subcommand === "model") {
124
- const { name, transcription } = getActiveProfile(settings);
125
- if (transcription.type !== "api") {
126
- ctx.ui.notify(`${name} is a local profile; switch profiles to change models`, "warning");
188
+ const command = args.trim().replaceAll(/\s+/gu, " ");
189
+ switch (command) {
190
+ case "":
191
+ case "record": {
192
+ await toggle(ctx);
193
+ return;
194
+ }
195
+ case "cancel": {
196
+ if (!recording) return;
197
+ const active = recording;
198
+ recording = undefined;
199
+ await active.recorder.cancel();
200
+ showStatus(ctx.ui, active.settings);
201
+ ctx.ui.notify("Recording discarded");
202
+ return;
203
+ }
204
+ case "setup": {
205
+ await setup(ctx);
127
206
  return;
128
207
  }
129
- const model = (await ctx.ui.input(`Model for ${name}`, transcription.model))?.trim();
130
- if (!model) return;
131
- transcription.model = model;
132
- saveVoiceSettings(path, settings);
133
- showStatus(ctx.ui);
134
- ctx.ui.notify(`Voice profile ${name}: ${model}`);
135
- return;
136
- }
137
- if (subcommand === "add") {
138
- const added = await promptProfile(ctx.ui, Object.keys(settings.profiles ?? {}));
139
- if (!added) return;
140
- settings.profiles = { ...settings.profiles, [added.name]: added.profile };
141
- settings.activeProfile = added.name;
142
- saveVoiceSettings(path, settings);
143
- showStatus(ctx.ui);
144
- ctx.ui.notify(`Voice profile: ${added.name}`);
145
- return;
146
208
  }
147
- if (!settings.profiles) {
148
- ctx.ui.notify("No profiles yet; run /voice-profile add", "warning");
209
+
210
+ const { settings } = configuration;
211
+ if (!settings) {
212
+ ctx.ui.notify(setupMessage(), configuration.errors.length > 0 ? "warning" : "info");
149
213
  return;
150
214
  }
151
- const selected = await ctx.ui.select(
152
- "Voice transcription profile",
153
- Object.keys(settings.profiles),
154
- );
155
- if (selected === undefined) return;
156
- settings.activeProfile = selected;
157
- saveVoiceSettings(path, settings);
158
- showStatus(ctx.ui);
159
- ctx.ui.notify(`Voice profile: ${selected}`);
160
- },
161
- });
215
+ switch (command) {
216
+ case "device": {
217
+ if (recording) {
218
+ ctx.ui.notify("Stop recording before changing the input", "warning");
219
+ return;
220
+ }
221
+ const selected = await promptInputDevice(ctx.ui, settings.inputDevice);
222
+ if (selected == null) return;
223
+ settings.inputDevice = selected.inputDevice;
224
+ save(settings);
225
+ showStatus(ctx.ui, settings);
226
+ ctx.ui.notify(`Voice input: ${selected.inputDevice?.name ?? "system default"}`);
227
+ return;
228
+ }
162
229
 
163
- pi.registerCommand("voice-status", {
164
- description: "show profile and input",
165
- // oxlint-disable-next-line require-await
166
- handler: async (_args, ctx) => {
167
- ctx.ui.notify(statusText());
230
+ case "profile": {
231
+ const selected = await ctx.ui.select(
232
+ "Voice transcription profile",
233
+ Object.keys(settings.profiles),
234
+ );
235
+ if (selected == null) return;
236
+ settings.activeProfile = selected;
237
+ save(settings);
238
+ showStatus(ctx.ui, settings);
239
+ ctx.ui.notify(`Voice profile: ${selected}`);
240
+ return;
241
+ }
242
+
243
+ case "profile add": {
244
+ const added = await promptProfile(ctx.ui, Object.keys(settings.profiles));
245
+ if (!added) return;
246
+ settings.profiles = { ...settings.profiles, [added.name]: added.profile };
247
+ settings.activeProfile = added.name;
248
+ save(settings);
249
+ showStatus(ctx.ui, settings);
250
+ ctx.ui.notify(`Voice profile: ${added.name}`);
251
+ return;
252
+ }
253
+
254
+ case "profile model": {
255
+ const { name, transcription } = getActiveProfile(settings);
256
+ const model =
257
+ transcription.type === "api"
258
+ ? (await ctx.ui.input(`Model for ${name}`, transcription.model))?.trim()
259
+ : await pickLocalModel(ctx.ui);
260
+ if (!model) return;
261
+ transcription.model = model;
262
+ save(settings);
263
+ showStatus(ctx.ui, settings);
264
+ ctx.ui.notify(`Voice profile ${name}: ${model}`);
265
+ return;
266
+ }
267
+
268
+ case "doctor": {
269
+ const checks = await runDoctor(settings);
270
+ ctx.ui.notify(formatChecks(checks), checks.every(({ ok }) => ok) ? "info" : "warning");
271
+ return;
272
+ }
273
+
274
+ case "status": {
275
+ ctx.ui.notify(
276
+ statusText(recording?.settings ?? settings, recording ? "● recording" : "idle"),
277
+ );
278
+ return;
279
+ }
280
+
281
+ default: {
282
+ ctx.ui.notify(
283
+ `Usage: /voice [${SUBCOMMANDS.map(({ value }) => value).join(" | ")}]`,
284
+ "warning",
285
+ );
286
+ }
287
+ }
168
288
  },
169
289
  });
170
290
 
171
291
  pi.on("session_start", (_event, ctx) => {
172
- showStatus(ctx.ui);
292
+ const { settings, errors } = configuration;
293
+ if (settings) {
294
+ showStatus(ctx.ui, settings);
295
+ } else {
296
+ ctx.ui.setStatus("voice", "[voice] needs setup · /voice setup");
297
+ }
298
+
299
+ if (errors.length > 0) ctx.ui.notify(setupMessage(), "warning");
173
300
  });
174
301
 
175
- pi.on("session_shutdown", () => {
176
- recorder.cancel();
302
+ pi.on("session_shutdown", async () => {
303
+ recording = undefined;
304
+ await recorder?.cancel();
177
305
  });
178
306
  }
package/src/profile.ts CHANGED
@@ -1,25 +1,48 @@
1
- import { basename } from "node:path";
2
-
3
1
  import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
4
- import { discoverLocalModels, type TranscriptionProfile } from "@luxass/agent-voice";
2
+ import {
3
+ downloadModel,
4
+ listLocalModels,
5
+ type LocalModel,
6
+ type TranscriptionProfile,
7
+ } from "@luxass/agent-voice";
8
+
9
+ const label = ({ name, installed, approxMB }: LocalModel) =>
10
+ installed ? name : `Download ${name} (${approxMB} MB)`;
11
+
12
+ function download(ui: ExtensionUIContext, name: string): Promise<string> {
13
+ let shown = -1;
14
+ return downloadModel(name, {
15
+ // Without a Content-Length, treat what arrived as the whole file.
16
+ onProgress: (received, total = received) => {
17
+ const percent = Math.floor((received / total) * 100);
18
+ if (percent === shown) return;
19
+ shown = percent;
20
+ ui.setStatus("voice-download", `downloading ${name}… ${percent}%`);
21
+ },
22
+ }).finally(() => {
23
+ ui.setStatus("voice-download", undefined);
24
+ });
25
+ }
5
26
 
6
- const AUTO_MODEL = "Auto-detect when transcribing";
27
+ /**
28
+ * Pick an installed GGUF model or download one from the catalog.
29
+ */
30
+ export async function pickLocalModel(ui: ExtensionUIContext): Promise<string | undefined> {
31
+ const models = listLocalModels();
32
+ const picked = await ui.select(
33
+ "Local GGUF model",
34
+ models.map((model) => label(model)),
35
+ );
36
+ const model = models.find((candidate) => label(candidate) === picked);
37
+ return model == null || model.installed ? model?.path : download(ui, model.name);
38
+ }
7
39
 
8
40
  async function promptLocal(ui: ExtensionUIContext): Promise<TranscriptionProfile | undefined> {
9
- const models = discoverLocalModels();
10
- const picked = await ui.select("Whisper model", [
11
- AUTO_MODEL,
12
- ...models.map((model) => basename(model)),
13
- ]);
14
- if (picked === undefined) return undefined;
41
+ const model = await pickLocalModel(ui);
42
+ if (model == null) return undefined;
15
43
  const language = await ui.input("Language code (blank for auto)", "en");
16
- if (language === undefined) return undefined;
17
-
18
- const profile: TranscriptionProfile = { type: "local" };
19
- const model = models.find((candidate) => basename(candidate) === picked);
20
- if (model) profile.model = model;
21
- if (language.trim()) profile.language = language.trim();
22
- return profile;
44
+ if (language == null) return undefined;
45
+ return { type: "local", model, language: language.trim() || undefined };
23
46
  }
24
47
 
25
48
  async function promptApi(ui: ExtensionUIContext): Promise<TranscriptionProfile | undefined> {
@@ -31,16 +54,21 @@ async function promptApi(ui: ExtensionUIContext): Promise<TranscriptionProfile |
31
54
  "API key environment variable (blank for none)",
32
55
  "OPENAI_API_KEY",
33
56
  );
34
- if (apiKeyEnv === undefined) return undefined;
57
+ if (apiKeyEnv == null) return undefined;
35
58
  const format = await ui.select("Request format", ["multipart", "openrouter"]);
36
- if (format !== "multipart" && format !== "openrouter") return undefined;
37
-
38
- const profile: TranscriptionProfile = { type: "api", endpoint, model, format };
39
- if (apiKeyEnv.trim()) profile.apiKeyEnv = apiKeyEnv.trim();
40
- return profile;
59
+ if (format == null) return undefined;
60
+ return {
61
+ type: "api",
62
+ endpoint,
63
+ model,
64
+ format: format === "openrouter" ? "openrouter" : "multipart",
65
+ apiKeyEnv: apiKeyEnv.trim() || undefined,
66
+ };
41
67
  }
42
68
 
43
- /** Ask for a profile name and its transcription settings. Returns undefined when the user backs out. */
69
+ /**
70
+ * Ask for a profile name and transcription settings. Cancellation returns undefined.
71
+ */
44
72
  export async function promptProfile(
45
73
  ui: ExtensionUIContext,
46
74
  existing: readonly string[],
@@ -51,7 +79,7 @@ export async function promptProfile(
51
79
  return undefined;
52
80
 
53
81
  const type = await ui.select("Transcription", ["local", "api"]);
54
- const profile =
55
- type === "local" ? await promptLocal(ui) : type === "api" ? await promptApi(ui) : undefined;
82
+ if (type == null) return undefined;
83
+ const profile = type === "local" ? await promptLocal(ui) : await promptApi(ui);
56
84
  return profile && { name, profile };
57
85
  }
package/src/setup.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
+ import { listInputDevices, type InputDevice, type VoiceSettings } from "@luxass/agent-voice";
3
+
4
+ import { promptProfile } from "./profile";
5
+
6
+ /**
7
+ * An undefined result means cancellation, not selection of the system default.
8
+ */
9
+ export async function promptInputDevice(
10
+ ui: ExtensionUIContext,
11
+ current?: InputDevice,
12
+ ): Promise<{ inputDevice: InputDevice | undefined } | undefined> {
13
+ const keep = current == null ? undefined : `Keep ${current.name}`;
14
+ const selected = await ui.select("Voice input", [
15
+ ...(keep == null ? [] : [keep]),
16
+ "System default",
17
+ "Choose input device",
18
+ ]);
19
+ if (selected == null) return undefined;
20
+ if (selected === keep) return { inputDevice: current };
21
+ if (selected === "System default") return { inputDevice: undefined };
22
+
23
+ const devices = await listInputDevices();
24
+ const picked = await ui.select(
25
+ "Voice input device",
26
+ devices.map(({ name, id }) => `${name} · ${id}`),
27
+ );
28
+ const inputDevice = devices.find(({ name, id }) => `${name} · ${id}` === picked);
29
+ return inputDevice == null ? undefined : { inputDevice };
30
+ }
31
+
32
+ /**
33
+ * Collect a setup draft. The caller checks and saves it after every dialog completes.
34
+ */
35
+ export async function promptSetup(
36
+ ui: ExtensionUIContext,
37
+ settings?: VoiceSettings,
38
+ ): Promise<VoiceSettings | undefined> {
39
+ const profiles = settings?.profiles ?? {};
40
+ const existing = Object.keys(profiles);
41
+ let activeProfile: string;
42
+ let nextProfiles = profiles;
43
+ const selected =
44
+ existing.length === 0
45
+ ? "Create new profile"
46
+ : await ui.select("Voice transcription", [
47
+ ...existing.map((name) => `Use ${name}`),
48
+ "Create new profile",
49
+ ]);
50
+ if (selected == null) return undefined;
51
+ if (selected === "Create new profile") {
52
+ const added = await promptProfile(ui, existing);
53
+ if (added == null) return undefined;
54
+ activeProfile = added.name;
55
+ nextProfiles = { ...profiles, [added.name]: added.profile };
56
+ } else {
57
+ activeProfile = selected.slice("Use ".length);
58
+ }
59
+ const input = await promptInputDevice(ui, settings?.inputDevice);
60
+ return input == null
61
+ ? undefined
62
+ : {
63
+ ...settings,
64
+ activeProfile,
65
+ profiles: nextProfiles,
66
+ inputDevice: input.inputDevice,
67
+ };
68
+ }