@senad-d/micme 0.3.5 → 0.3.6

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/src/config.ts CHANGED
@@ -1,41 +1,92 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
- import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { createRequire } from "node:module";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join, resolve } from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
7
8
  import type { MicmeConfigState, TranscribeBackend, TranscriptionMode } from "./types.ts";
8
9
  import {
10
+ DEFAULT_AUTO_DOWNLOAD_MODEL,
9
11
  DEFAULT_MACOS_PRINTABLE_SHORTCUT,
12
+ DEFAULT_MIN_MAX_VOLUME_DB,
13
+ DEFAULT_RECORD_SYNC,
10
14
  DEFAULT_SHORTCUT,
15
+ DEFAULT_STREAM_CAPTURE,
16
+ DEFAULT_STREAM_FLUSH_MS,
11
17
  DEFAULT_STREAM_KEEP_MS,
12
18
  DEFAULT_STREAM_LENGTH_MS,
13
19
  DEFAULT_STREAM_MAX_TOKENS,
14
20
  DEFAULT_STREAM_STEP_MS,
15
21
  DEFAULT_STREAM_VAD_THRESHOLD,
16
- DEFAULT_STREAM_FLUSH_MS,
22
+ DEFAULT_STREAM_WORDS_PER_CHUNK,
17
23
  DEFAULT_TRANSCRIBE_BACKEND,
18
24
  DEFAULT_TRANSCRIBE_SAMPLE_RATE,
19
25
  DEFAULT_TRANSCRIBE_TIMEOUT_MS,
20
- DEFAULT_MIN_MAX_VOLUME_DB,
26
+ MAX_AUDIO_SAMPLE_RATE,
27
+ MAX_STREAM_CAPTURE,
28
+ MAX_STREAM_FLUSH_MS,
29
+ MAX_STREAM_KEEP_MS,
30
+ MAX_STREAM_LENGTH_MS,
31
+ MAX_STREAM_MAX_TOKENS,
32
+ MAX_STREAM_STEP_MS,
33
+ MAX_STREAM_VAD_THRESHOLD,
34
+ MAX_STREAM_WORDS_PER_CHUNK,
35
+ MAX_TRANSCRIBE_TIMEOUT_MS,
36
+ MIN_AUDIO_SAMPLE_RATE,
37
+ MIN_STREAM_CAPTURE,
38
+ MIN_STREAM_FLUSH_MS,
39
+ MIN_STREAM_KEEP_MS,
40
+ MIN_STREAM_LENGTH_MS,
41
+ MIN_STREAM_MAX_TOKENS,
42
+ MIN_STREAM_STEP_MS,
43
+ MIN_STREAM_VAD_THRESHOLD,
44
+ MIN_STREAM_WORDS_PER_CHUNK,
45
+ MIN_TRANSCRIBE_TIMEOUT_MS,
46
+ STREAM_PROFILE_FLUSH_MS,
21
47
  STREAM_PROFILE_KEEP_MS,
22
48
  STREAM_PROFILE_LENGTH_MS,
23
49
  STREAM_PROFILE_MAX_TOKENS,
24
50
  STREAM_PROFILE_STEP_MS,
25
51
  STREAM_PROFILE_VAD_THRESHOLD,
26
52
  STREAM_PROFILE_WORDS_PER_CHUNK,
27
- STREAM_PROFILE_FLUSH_MS,
28
53
  } from "./constants.ts";
29
54
 
30
55
  const MICME_CONFIG_FILE = "micme.json";
31
56
  const MICME_SCHEMA_URL = "https://raw.githubusercontent.com/senad-d/micme/main/micme.schema.json";
57
+ const CONFIG_LOCK_TIMEOUT_MS = 5_000;
58
+ const CONFIG_LOCK_RETRY_MS = 25;
32
59
  const requireModule = createRequire(import.meta.url);
33
60
 
34
61
  type JsonObject = Record<string, unknown>;
62
+ type NumericSettingBounds = { minimum: number; maximum: number };
63
+ type ConfigLockLease = { path: string; ownerPath: string; token: string };
64
+
65
+ export type MicmeConfigWriteOptions = {
66
+ signal?: AbortSignal;
67
+ lockTimeoutMs?: number;
68
+ lockRetryMs?: number;
69
+ };
70
+
71
+ export const NUMERIC_CONFIG_BOUNDS = {
72
+ MICME_TRANSCRIBE_TIMEOUT_MS: { minimum: MIN_TRANSCRIBE_TIMEOUT_MS, maximum: MAX_TRANSCRIBE_TIMEOUT_MS },
73
+ MICME_STREAM_CAPTURE: { minimum: MIN_STREAM_CAPTURE, maximum: MAX_STREAM_CAPTURE },
74
+ MICME_STREAM_STEP_MS: { minimum: MIN_STREAM_STEP_MS, maximum: MAX_STREAM_STEP_MS },
75
+ MICME_STREAM_LENGTH_MS: { minimum: MIN_STREAM_LENGTH_MS, maximum: MAX_STREAM_LENGTH_MS },
76
+ MICME_STREAM_KEEP_MS: { minimum: MIN_STREAM_KEEP_MS, maximum: MAX_STREAM_KEEP_MS },
77
+ MICME_STREAM_MAX_TOKENS: { minimum: MIN_STREAM_MAX_TOKENS, maximum: MAX_STREAM_MAX_TOKENS },
78
+ MICME_STREAM_FLUSH_MS: { minimum: MIN_STREAM_FLUSH_MS, maximum: MAX_STREAM_FLUSH_MS },
79
+ MICME_STREAM_WORDS_PER_CHUNK: { minimum: MIN_STREAM_WORDS_PER_CHUNK, maximum: MAX_STREAM_WORDS_PER_CHUNK },
80
+ MICME_STREAM_VAD_THRESHOLD: { minimum: MIN_STREAM_VAD_THRESHOLD, maximum: MAX_STREAM_VAD_THRESHOLD },
81
+ MICME_RECORD_SAMPLE_RATE: { minimum: MIN_AUDIO_SAMPLE_RATE, maximum: MAX_AUDIO_SAMPLE_RATE },
82
+ MICME_TRANSCRIBE_SAMPLE_RATE: { minimum: MIN_AUDIO_SAMPLE_RATE, maximum: MAX_AUDIO_SAMPLE_RATE },
83
+ MICME_AVFOUNDATION_INPUT_SAMPLE_RATE: { minimum: MIN_AUDIO_SAMPLE_RATE, maximum: MAX_AUDIO_SAMPLE_RATE },
84
+ } as const satisfies Record<string, NumericSettingBounds>;
35
85
 
36
86
  let piAgentDirChecked = false;
37
87
  let piAgentDir: string | undefined;
38
88
  let micmeConfigState: MicmeConfigState = loadMicmeJson();
89
+ const configWriteTails = new Map<string, Promise<void>>();
39
90
 
40
91
  export function getMicmeAgentDir() {
41
92
  const configured = process.env.PI_CODING_AGENT_DIR?.trim();
@@ -56,6 +107,12 @@ export function reloadMicmeConfig() {
56
107
  return micmeConfigState;
57
108
  }
58
109
 
110
+ export function requireValidMicmeConfig() {
111
+ const state = reloadMicmeConfig();
112
+ if (!state.error) return state;
113
+ throw new Error(`Micme config is invalid at ${state.path}: ${state.error}. Fix or remove it before using Micme operational commands.`);
114
+ }
115
+
59
116
  export function loadMicmeJson(): MicmeConfigState {
60
117
  const path = getMicmeConfigPath();
61
118
  if (!existsSync(path)) return { path, values: {} };
@@ -66,25 +123,50 @@ export function loadMicmeJson(): MicmeConfigState {
66
123
  return { path, values: {}, error: "top-level value must be a JSON object" };
67
124
  }
68
125
  return { path, values: extractMicmeValues(parsed) };
69
- } catch (error) {
70
- return { path, values: {}, error: error instanceof Error ? error.message : String(error) };
126
+ } catch {
127
+ return { path, values: {}, error: "file is not valid JSON" };
71
128
  }
72
129
  }
73
130
 
74
- export async function writeMicmeConfigValue(key: string, value: string) {
75
- await writeMicmeConfigValues({ [key]: value });
131
+ export async function writeMicmeConfigValue(key: string, value: string, options: MicmeConfigWriteOptions = {}) {
132
+ await writeMicmeConfigValues({ [key]: value }, options);
76
133
  }
77
134
 
78
- export async function writeMicmeConfigValues(values: Record<string, string | undefined>) {
135
+ export function writeMicmeConfigValues(values: Record<string, string | undefined>, options: MicmeConfigWriteOptions = {}) {
79
136
  for (const key of Object.keys(values)) {
80
- if (!key.startsWith("MICME_")) throw new Error(`Micme config keys must start with MICME_: ${key}`);
137
+ if (!key.startsWith("MICME_")) return Promise.reject(new Error(`Micme config keys must start with MICME_: ${key}`));
81
138
  }
82
139
 
83
140
  const configPath = getMicmeConfigPath();
141
+ const previous = configWriteTails.get(configPath) ?? Promise.resolve();
142
+ const writeOperation = commitMicmeConfigValues.bind(undefined, configPath, values, options);
143
+ const pending = previous.catch(ignoreConfigWriteFailure).then(writeOperation);
144
+ configWriteTails.set(configPath, pending);
145
+ return pending.finally(removeConfigWriteTail.bind(undefined, configPath, pending));
146
+ }
147
+
148
+ async function commitMicmeConfigValues(configPath: string, values: Record<string, string | undefined>, options: MicmeConfigWriteOptions) {
84
149
  const configDir = dirname(configPath);
85
- const existing = readMicmeJsonObjectForWrite(configPath);
86
- const next: JsonObject = { ...existing };
150
+ await mkdir(configDir, { recursive: true });
151
+ const lease = await acquireMicmeConfigLock(configPath, options);
152
+ const tempPath = join(configDir, `.micme.${process.pid}.${Date.now()}.${randomUUID()}.tmp`);
153
+
154
+ try {
155
+ options.signal?.throwIfAborted();
156
+ const existing = readMicmeJsonObjectForWrite(configPath);
157
+ const next = mergeMicmeConfigValues(existing, values);
158
+ await writeFile(tempPath, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", mode: 0o600, signal: options.signal });
159
+ options.signal?.throwIfAborted();
160
+ await rename(tempPath, configPath);
161
+ reloadMicmeConfig();
162
+ } finally {
163
+ await rm(tempPath, { force: true }).catch(ignoreConfigWriteFailure);
164
+ await releaseMicmeConfigLock(lease);
165
+ }
166
+ }
87
167
 
168
+ function mergeMicmeConfigValues(existing: JsonObject, values: Record<string, string | undefined>) {
169
+ const next: JsonObject = { ...existing };
88
170
  for (const [key, value] of Object.entries(values)) {
89
171
  if (value === undefined) {
90
172
  delete next[key];
@@ -92,18 +174,75 @@ export async function writeMicmeConfigValues(values: Record<string, string | und
92
174
  next[key] = String(value);
93
175
  }
94
176
  }
177
+ return next;
178
+ }
179
+
180
+ async function acquireMicmeConfigLock(configPath: string, options: MicmeConfigWriteOptions): Promise<ConfigLockLease> {
181
+ const lockPath = `${configPath}.lock`;
182
+ const ownerPath = join(lockPath, "owner.json");
183
+ const token = randomUUID();
184
+ const timeoutMs = positiveDuration(options.lockTimeoutMs, CONFIG_LOCK_TIMEOUT_MS, "lockTimeoutMs");
185
+ const retryMs = positiveDuration(options.lockRetryMs, CONFIG_LOCK_RETRY_MS, "lockRetryMs");
186
+ const deadline = Date.now() + timeoutMs;
187
+
188
+ while (true) {
189
+ options.signal?.throwIfAborted();
190
+ try {
191
+ await mkdir(lockPath, { mode: 0o700 });
192
+ } catch (error) {
193
+ if (!isNodeError(error, "EEXIST")) throw error;
194
+ const remainingMs = deadline - Date.now();
195
+ if (remainingMs <= 0) {
196
+ throw new Error(`Timed out waiting ${timeoutMs} ms for Micme config lock at ${lockPath}. The lock may be active or stale; Micme will not remove a lock owned by another writer.`, { cause: error });
197
+ }
198
+ await delay(Math.min(retryMs, remainingMs), undefined, { signal: options.signal });
199
+ continue;
200
+ }
95
201
 
96
- await mkdir(configDir, { recursive: true });
97
- const tempPath = join(configDir, `.micme.${process.pid}.${Date.now()}.${randomUUID()}.tmp`);
202
+ const lease = { path: lockPath, ownerPath, token };
203
+ try {
204
+ options.signal?.throwIfAborted();
205
+ await writeFile(ownerPath, `${JSON.stringify({ pid: process.pid, token, createdAt: new Date().toISOString() }, null, 2)}\n`, {
206
+ encoding: "utf8",
207
+ mode: 0o600,
208
+ signal: options.signal,
209
+ });
210
+ return lease;
211
+ } catch (error) {
212
+ await rm(lockPath, { recursive: true, force: true }).catch(ignoreConfigWriteFailure);
213
+ throw error;
214
+ }
215
+ }
216
+ }
217
+
218
+ async function releaseMicmeConfigLock(lease: ConfigLockLease) {
219
+ let owner: unknown;
98
220
  try {
99
- await writeFile(tempPath, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
100
- await rename(tempPath, configPath);
221
+ owner = JSON.parse(await readFile(lease.ownerPath, "utf8"));
101
222
  } catch (error) {
102
- await rm(tempPath, { force: true }).catch(() => undefined);
223
+ if (isNodeError(error, "ENOENT")) return;
103
224
  throw error;
104
225
  }
226
+ if (!isJsonObject(owner) || owner.token !== lease.token) return;
227
+ await rm(lease.path, { recursive: true, force: true });
228
+ }
105
229
 
106
- reloadMicmeConfig();
230
+ function positiveDuration(value: number | undefined, fallback: number, name: string) {
231
+ if (value === undefined) return fallback;
232
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive finite number`);
233
+ return Math.ceil(value);
234
+ }
235
+
236
+ function isNodeError(error: unknown, code: string) {
237
+ return error instanceof Error && "code" in error && error.code === code;
238
+ }
239
+
240
+ function ignoreConfigWriteFailure() {
241
+ // Best-effort cleanup must not replace the config write failure already being handled.
242
+ }
243
+
244
+ function removeConfigWriteTail(configPath: string, pending: Promise<void>) {
245
+ if (configWriteTails.get(configPath) === pending) configWriteTails.delete(configPath);
107
246
  }
108
247
 
109
248
  export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<string, string> {
@@ -129,7 +268,7 @@ export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<str
129
268
  MICME_STREAM_LENGTH_MS: String(DEFAULT_STREAM_LENGTH_MS),
130
269
  MICME_STREAM_KEEP_MS: String(DEFAULT_STREAM_KEEP_MS),
131
270
  MICME_STREAM_MAX_TOKENS: String(DEFAULT_STREAM_MAX_TOKENS),
132
- MICME_STREAM_WORDS_PER_CHUNK: "10",
271
+ MICME_STREAM_WORDS_PER_CHUNK: String(DEFAULT_STREAM_WORDS_PER_CHUNK),
133
272
  MICME_STREAM_FLUSH_MS: String(DEFAULT_STREAM_FLUSH_MS),
134
273
  MICME_STREAM_KEEP_CONTEXT: "0",
135
274
  MICME_STREAM_FINALIZE_WITH_CLIP: "1",
@@ -171,8 +310,11 @@ export function getTerminalShortcut() {
171
310
  return DEFAULT_SHORTCUT;
172
311
  }
173
312
 
313
+ const TRANSCRIPTION_MODES = ["clip", "stream"] as const;
314
+ const TRANSCRIBE_BACKENDS = ["auto", "whisper.cpp", "python", "custom"] as const;
315
+
174
316
  export function getTranscriptionMode() {
175
- return env("MICME_TRANSCRIPTION_MODE") === "stream" ? "stream" : "clip";
317
+ return parseConfiguredChoice(env("MICME_TRANSCRIPTION_MODE"), TRANSCRIPTION_MODES, "clip");
176
318
  }
177
319
 
178
320
  export function getTranslateToEnglishLanguage() {
@@ -182,12 +324,15 @@ export function getTranslateToEnglishLanguage() {
182
324
  }
183
325
 
184
326
  export function getTranscribeBackend(): TranscribeBackend {
185
- const value = env("MICME_TRANSCRIBE_BACKEND")?.trim();
186
- return isTranscribeBackend(value) ? value : DEFAULT_TRANSCRIBE_BACKEND;
327
+ return parseConfiguredChoice(env("MICME_TRANSCRIBE_BACKEND")?.trim(), TRANSCRIBE_BACKENDS, DEFAULT_TRANSCRIBE_BACKEND);
187
328
  }
188
329
 
189
330
  export function isTranscribeBackend(value: string | undefined): value is TranscribeBackend {
190
- return value === "auto" || value === "whisper.cpp" || value === "python" || value === "custom";
331
+ return value !== undefined && TRANSCRIBE_BACKENDS.includes(value as TranscribeBackend);
332
+ }
333
+
334
+ function parseConfiguredChoice<T extends string>(value: string | undefined, choices: readonly T[], fallback: T) {
335
+ return value !== undefined && choices.includes(value as T) ? (value as T) : fallback;
191
336
  }
192
337
 
193
338
  const NAMED_TERMINAL_KEYS = new Set([
@@ -265,65 +410,61 @@ function splitShortcutValues(value: string) {
265
410
  }
266
411
 
267
412
  export function getTranscribeTimeoutMs() {
268
- const value = Number(env("MICME_TRANSCRIBE_TIMEOUT_MS"));
269
- return Number.isFinite(value) && value > 0 ? value : DEFAULT_TRANSCRIBE_TIMEOUT_MS;
413
+ return parseBoundedInteger(env("MICME_TRANSCRIBE_TIMEOUT_MS"), NUMERIC_CONFIG_BOUNDS.MICME_TRANSCRIBE_TIMEOUT_MS) ?? DEFAULT_TRANSCRIBE_TIMEOUT_MS;
414
+ }
415
+
416
+ export function getStreamCapture() {
417
+ return parseBoundedInteger(env("MICME_STREAM_CAPTURE"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_CAPTURE) ?? DEFAULT_STREAM_CAPTURE;
270
418
  }
271
419
 
272
420
  export function getStreamStepMs() {
273
- const value = Number(env("MICME_STREAM_STEP_MS"));
274
- return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_STEP_MS;
421
+ return parseBoundedInteger(env("MICME_STREAM_STEP_MS"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_STEP_MS) ?? DEFAULT_STREAM_STEP_MS;
275
422
  }
276
423
 
277
424
  export function getStreamLengthMs() {
278
- const value = Number(env("MICME_STREAM_LENGTH_MS"));
279
- return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_LENGTH_MS;
425
+ return parseBoundedInteger(env("MICME_STREAM_LENGTH_MS"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_LENGTH_MS) ?? DEFAULT_STREAM_LENGTH_MS;
280
426
  }
281
427
 
282
428
  export function getStreamKeepMs() {
283
- const value = Number(env("MICME_STREAM_KEEP_MS"));
284
- return Number.isFinite(value) && value >= 0 ? Math.round(value) : DEFAULT_STREAM_KEEP_MS;
429
+ return parseBoundedInteger(env("MICME_STREAM_KEEP_MS"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_KEEP_MS) ?? DEFAULT_STREAM_KEEP_MS;
285
430
  }
286
431
 
287
432
  export function getStreamMaxTokens() {
288
- const value = Number(env("MICME_STREAM_MAX_TOKENS"));
289
- return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_MAX_TOKENS;
433
+ return parseBoundedInteger(env("MICME_STREAM_MAX_TOKENS"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_MAX_TOKENS) ?? DEFAULT_STREAM_MAX_TOKENS;
290
434
  }
291
435
 
292
436
  export function getStreamVadThreshold() {
293
- const value = Number(env("MICME_STREAM_VAD_THRESHOLD"));
294
- return Number.isFinite(value) && value > 0 && value < 1 ? value : DEFAULT_STREAM_VAD_THRESHOLD;
437
+ return parseBoundedNumber(env("MICME_STREAM_VAD_THRESHOLD"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_VAD_THRESHOLD) ?? DEFAULT_STREAM_VAD_THRESHOLD;
295
438
  }
296
439
 
297
440
  export function getStreamKeepContext() {
298
- const value = env("MICME_STREAM_KEEP_CONTEXT");
299
- return value === undefined ? false : /^(1|true|yes|on)$/i.test(value);
441
+ return getFlagSetting("MICME_STREAM_KEEP_CONTEXT", false);
300
442
  }
301
443
 
302
444
  export function getStreamFlushMs() {
303
- const value = Number(env("MICME_STREAM_FLUSH_MS"));
304
- return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_FLUSH_MS;
445
+ return parseBoundedInteger(env("MICME_STREAM_FLUSH_MS"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_FLUSH_MS) ?? DEFAULT_STREAM_FLUSH_MS;
305
446
  }
306
447
 
307
448
  export function getStreamFinalizeWithClip() {
308
- const value = env("MICME_STREAM_FINALIZE_WITH_CLIP");
309
- return value === undefined ? false : /^(1|true|yes|on)$/i.test(value);
449
+ return getFlagSetting("MICME_STREAM_FINALIZE_WITH_CLIP", false);
310
450
  }
311
451
 
312
452
  export function getStreamWordsPerChunk() {
313
- const value = Number(env("MICME_STREAM_WORDS_PER_CHUNK"));
314
- return Number.isFinite(value) && value > 0 ? Math.min(10, Math.round(value)) : 10;
453
+ return parseBoundedInteger(env("MICME_STREAM_WORDS_PER_CHUNK"), NUMERIC_CONFIG_BOUNDS.MICME_STREAM_WORDS_PER_CHUNK) ?? DEFAULT_STREAM_WORDS_PER_CHUNK;
315
454
  }
316
455
 
317
456
  export function getRecordSampleRate() {
318
457
  const configured = env("MICME_RECORD_SAMPLE_RATE")?.trim();
319
458
  if (!configured || /^auto$/i.test(configured)) return undefined;
320
- const value = Number(configured);
321
- return Number.isFinite(value) && value > 0 ? Math.round(value) : undefined;
459
+ return parseBoundedInteger(configured, NUMERIC_CONFIG_BOUNDS.MICME_RECORD_SAMPLE_RATE);
322
460
  }
323
461
 
324
462
  export function getTranscribeSampleRate() {
325
- const value = Number(env("MICME_TRANSCRIBE_SAMPLE_RATE"));
326
- return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_TRANSCRIBE_SAMPLE_RATE;
463
+ return parseBoundedInteger(env("MICME_TRANSCRIBE_SAMPLE_RATE"), NUMERIC_CONFIG_BOUNDS.MICME_TRANSCRIBE_SAMPLE_RATE) ?? DEFAULT_TRANSCRIBE_SAMPLE_RATE;
464
+ }
465
+
466
+ export function getAutoDownloadModel() {
467
+ return getFlagSetting("MICME_AUTO_DOWNLOAD_MODEL", DEFAULT_AUTO_DOWNLOAD_MODEL);
327
468
  }
328
469
 
329
470
  export function getRecordMeter() {
@@ -331,8 +472,7 @@ export function getRecordMeter() {
331
472
  }
332
473
 
333
474
  export function getRecordSync() {
334
- const value = env("MICME_RECORD_SYNC");
335
- return value === undefined ? true : /^(1|true|yes|on)$/i.test(value);
475
+ return getFlagSetting("MICME_RECORD_SYNC", DEFAULT_RECORD_SYNC);
336
476
  }
337
477
 
338
478
  export function getAvfoundationDropLateFrames() {
@@ -340,8 +480,7 @@ export function getAvfoundationDropLateFrames() {
340
480
  }
341
481
 
342
482
  export function getAvfoundationInputSampleRate() {
343
- const value = Number(env("MICME_AVFOUNDATION_INPUT_SAMPLE_RATE"));
344
- return Number.isFinite(value) && value > 0 ? Math.round(value) : undefined;
483
+ return parseBoundedInteger(env("MICME_AVFOUNDATION_INPUT_SAMPLE_RATE"), NUMERIC_CONFIG_BOUNDS.MICME_AVFOUNDATION_INPUT_SAMPLE_RATE);
345
484
  }
346
485
 
347
486
  export function getAudioFilter() {
@@ -375,7 +514,32 @@ export function getMeterGain() {
375
514
  }
376
515
 
377
516
  export function envFlag(name: string) {
378
- return /^(1|true|yes|on)$/i.test(env(name) || "");
517
+ return getFlagSetting(name, false);
518
+ }
519
+
520
+ function getFlagSetting(name: string, fallback: boolean) {
521
+ const value = env(name)?.trim();
522
+ if (/^(1|true|yes|on)$/i.test(value ?? "")) return true;
523
+ if (/^(0|false|no|off)$/i.test(value ?? "")) return false;
524
+ return fallback;
525
+ }
526
+
527
+ function parseBoundedInteger(value: string | undefined, bounds: NumericSettingBounds) {
528
+ const number = parseFiniteNumber(value);
529
+ if (number === undefined) return undefined;
530
+ const normalized = Math.round(number);
531
+ return normalized >= bounds.minimum && normalized <= bounds.maximum ? normalized : undefined;
532
+ }
533
+
534
+ function parseBoundedNumber(value: string | undefined, bounds: NumericSettingBounds) {
535
+ const number = parseFiniteNumber(value);
536
+ return number !== undefined && number >= bounds.minimum && number <= bounds.maximum ? number : undefined;
537
+ }
538
+
539
+ function parseFiniteNumber(value: string | undefined) {
540
+ if (!value?.trim()) return undefined;
541
+ const number = Number(value);
542
+ return Number.isFinite(number) ? number : undefined;
379
543
  }
380
544
 
381
545
  function readMicmeJsonObjectForWrite(configPath: string): JsonObject {
package/src/constants.ts CHANGED
@@ -5,6 +5,11 @@ export const DEFAULT_MACOS_PRINTABLE_SHORTCUT = "§";
5
5
  export const DEFAULT_TRANSCRIBE_TIMEOUT_MS = 120_000;
6
6
  export const DEFAULT_RECORD_SAMPLE_RATE = "auto";
7
7
  export const DEFAULT_TRANSCRIBE_SAMPLE_RATE = 16_000;
8
+ export const DEFAULT_AUTO_DOWNLOAD_MODEL = true;
9
+ export const MODEL_DOWNLOAD_INACTIVITY_TIMEOUT_MS = 120_000;
10
+ export const DEFAULT_RECORD_SYNC = true;
11
+ export const DEFAULT_STREAM_CAPTURE = -1;
12
+ export const DEFAULT_STREAM_WORDS_PER_CHUNK = 10;
8
13
  export const RECORDER_STARTUP_GRACE_MS = 700;
9
14
  export const RECORDER_STOP_GRACE_MS = 3_000;
10
15
  export const MIN_AUDIO_BYTES = 512;
@@ -16,6 +21,26 @@ export const DEFAULT_STREAM_KEEP_MS = 500;
16
21
  export const DEFAULT_STREAM_MAX_TOKENS = 64;
17
22
  export const DEFAULT_STREAM_VAD_THRESHOLD = 0.45;
18
23
  export const DEFAULT_STREAM_FLUSH_MS = 700;
24
+ export const MIN_TRANSCRIBE_TIMEOUT_MS = 1_000;
25
+ export const MAX_TRANSCRIBE_TIMEOUT_MS = 3_600_000;
26
+ export const MIN_STREAM_STEP_MS = 100;
27
+ export const MAX_STREAM_STEP_MS = 60_000;
28
+ export const MIN_STREAM_LENGTH_MS = 1_000;
29
+ export const MAX_STREAM_LENGTH_MS = 120_000;
30
+ export const MIN_STREAM_KEEP_MS = 0;
31
+ export const MAX_STREAM_KEEP_MS = 60_000;
32
+ export const MIN_STREAM_MAX_TOKENS = 1;
33
+ export const MAX_STREAM_MAX_TOKENS = 4_096;
34
+ export const MIN_STREAM_FLUSH_MS = 100;
35
+ export const MAX_STREAM_FLUSH_MS = 60_000;
36
+ export const MIN_STREAM_WORDS_PER_CHUNK = 1;
37
+ export const MAX_STREAM_WORDS_PER_CHUNK = 10;
38
+ export const MIN_STREAM_CAPTURE = -1;
39
+ export const MAX_STREAM_CAPTURE = 255;
40
+ export const MIN_STREAM_VAD_THRESHOLD = 0.01;
41
+ export const MAX_STREAM_VAD_THRESHOLD = 0.99;
42
+ export const MIN_AUDIO_SAMPLE_RATE = 8_000;
43
+ export const MAX_AUDIO_SAMPLE_RATE = 384_000;
19
44
  export const STREAM_PROFILE_STEP_MS = 500;
20
45
  export const STREAM_PROFILE_LENGTH_MS = 3_000;
21
46
  export const STREAM_PROFILE_KEEP_MS = 300;
package/src/editor.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CustomEditor, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { type AutocompleteProvider, decodeKittyPrintable } from "@earendil-works/pi-tui";
3
- import { matchesPrintableMicmeShortcut } from "./config.ts";
3
+ import { getPrintableShortcuts, matchesPrintableMicmeShortcut } from "./config.ts";
4
4
 
5
5
  type CustomEditorArgs = ConstructorParameters<typeof CustomEditor>;
6
6
  // Printable Option-key fallbacks auto-repeat while held; debounce them so one hold is one toggle.
@@ -13,13 +13,11 @@ export type MicmeEditorInputHandlers = {
13
13
  };
14
14
 
15
15
  class MicmeEditor extends CustomEditor {
16
- constructor(
17
- tui: CustomEditorArgs[0],
18
- theme: CustomEditorArgs[1],
19
- keybindings: CustomEditorArgs[2],
20
- private readonly micmeHandlers: MicmeEditorInputHandlers,
21
- ) {
16
+ private readonly micmeHandlers: MicmeEditorInputHandlers;
17
+
18
+ constructor(tui: CustomEditorArgs[0], theme: CustomEditorArgs[1], keybindings: CustomEditorArgs[2], micmeHandlers: MicmeEditorInputHandlers) {
22
19
  super(tui, theme, keybindings);
20
+ this.micmeHandlers = micmeHandlers;
23
21
  }
24
22
 
25
23
  override handleInput(data: string): void {
@@ -53,7 +51,7 @@ function isPrintableShortcutAutoRepeat(printableShortcut: string) {
53
51
  }
54
52
 
55
53
  export function installMicmeEditorFallback(ctx: ExtensionContext, micmeHandlers: MicmeEditorInputHandlers) {
56
- if (ctx.mode !== "tui") return;
54
+ if (ctx.mode !== "tui" || getPrintableShortcuts().length === 0) return;
57
55
 
58
56
  const previousEditor = ctx.ui.getEditorComponent();
59
57
  if (previousEditor) {