dictawhisper 0.0.13 → 0.0.14

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.
Files changed (60) hide show
  1. package/README.md +10 -2
  2. package/bin/dictawhisper.mjs +14 -0
  3. package/config.example.json +41 -0
  4. package/dist/ui/_app/immutable/assets/0.C6M3gHo0.css +1 -0
  5. package/dist/ui/_app/immutable/assets/2.C96vgj_4.css +1 -0
  6. package/dist/ui/_app/immutable/chunks/BSs9MmST.js +3 -0
  7. package/dist/ui/_app/immutable/chunks/Bjy-W4x2.js +81 -0
  8. package/dist/ui/_app/immutable/chunks/BslYtab-.js +1 -0
  9. package/dist/ui/_app/immutable/chunks/xihTtKlq.js +1 -0
  10. package/dist/ui/_app/immutable/entry/app.BJlRju4c.js +2 -0
  11. package/dist/ui/_app/immutable/entry/start.C5XBbXTT.js +1 -0
  12. package/dist/ui/_app/immutable/nodes/0.D23pkrHr.js +1 -0
  13. package/dist/ui/_app/immutable/nodes/1.C5T-U4uV.js +1 -0
  14. package/dist/ui/_app/immutable/nodes/2.59uAq_ko.js +5 -0
  15. package/dist/ui/_app/version.json +1 -0
  16. package/dist/ui/favicon.png +0 -0
  17. package/dist/ui/favicon.svg +3 -0
  18. package/dist/ui/index.html +38 -0
  19. package/dist/ui/logo.png +0 -0
  20. package/package.json +12 -3
  21. package/scripts/transcribe_faster_whisper.py +428 -0
  22. package/src/apiRoutes.ts +464 -0
  23. package/src/classes/Queue.ts +77 -0
  24. package/src/classes/Watcher.ts +117 -0
  25. package/src/cli.ts +132 -0
  26. package/src/config.ts +238 -0
  27. package/src/dev.ts +63 -0
  28. package/src/doctor.ts +12 -0
  29. package/src/lib/alignLib.ts +154 -0
  30. package/src/lib/audioLib.ts +202 -0
  31. package/src/lib/audioProbeLib.ts +112 -0
  32. package/src/lib/cleanupProvenanceLib.ts +80 -0
  33. package/src/lib/downloadLib.ts +8 -0
  34. package/src/lib/fileSettleLib.ts +213 -0
  35. package/src/lib/fsLib.ts +37 -0
  36. package/src/lib/healthLib.ts +377 -0
  37. package/src/lib/inboxUrl.ts +123 -0
  38. package/src/lib/journalEmbedLib.ts +127 -0
  39. package/src/lib/journalIndexLib.ts +923 -0
  40. package/src/lib/journalQueryLib.ts +269 -0
  41. package/src/lib/journalService.ts +287 -0
  42. package/src/lib/jsonLib.ts +71 -0
  43. package/src/lib/localberthGet.ts +14 -0
  44. package/src/lib/ollanetLib.ts +117 -0
  45. package/src/lib/ollanetReadyLib.ts +7 -0
  46. package/src/lib/organizationLib.ts +182 -0
  47. package/src/lib/pathAllowLib.ts +60 -0
  48. package/src/lib/queueLib.ts +30 -0
  49. package/src/lib/speechCleanupLib.ts +14 -0
  50. package/src/lib/tagConsolidateLib.ts +431 -0
  51. package/src/lib/tailscaleLib.ts +78 -0
  52. package/src/lib/transcriptionLib.ts +484 -0
  53. package/src/lib/whisperLib.ts +409 -0
  54. package/src/mcp.ts +151 -0
  55. package/src/prompts/cleanTranscription.ts +62 -0
  56. package/src/prompts/consolidateTags.ts +38 -0
  57. package/src/prompts/whisperInitial.ts +11 -0
  58. package/src/server.ts +220 -0
  59. package/src/socketEvents.ts +72 -0
  60. package/src/types/transcription.ts +56 -0
@@ -0,0 +1,409 @@
1
+ import { spawn, type ChildProcess } from 'child_process';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import readline from 'readline';
5
+ import { fileURLToPath } from 'url';
6
+ import { config } from '../config.ts';
7
+ import { buildWhisperInitialPrompt } from '../prompts/whisperInitial.ts';
8
+
9
+ const WINDOWS_CUDA_TEARDOWN = 3221226505;
10
+ const WORKER_READY_MS = 180_000;
11
+ const JOB_TIMEOUT_MS = 45 * 60 * 1000;
12
+ const SHUTDOWN_MS = 8_000;
13
+
14
+ export type WhisperWorkerStatus = 'off' | 'starting' | 'ready' | 'down';
15
+
16
+ type WhisperCallback = (payload: {
17
+ err: Error | null;
18
+ result?: { transcriptionFile: string; elapsed: string };
19
+ }) => void;
20
+
21
+ type PendingJob = {
22
+ id: string;
23
+ transcriptionFile: string;
24
+ startTime: number;
25
+ resolve: (elapsed: string) => void;
26
+ reject: (error: Error) => void;
27
+ };
28
+
29
+ function transcriptionLooksComplete(transcriptionFile: string): boolean {
30
+ try {
31
+ if (!fs.existsSync(transcriptionFile)) return false;
32
+ const json = JSON.parse(fs.readFileSync(transcriptionFile, 'utf-8'));
33
+ return typeof json?.text === 'string' && json.text.trim().length > 0 && Array.isArray(json.segments);
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
40
+ const transcribeScript = path.resolve(__dirname, '../../scripts/transcribe_faster_whisper.py');
41
+
42
+ function pythonEnv(): NodeJS.ProcessEnv {
43
+ return {
44
+ ...process.env,
45
+ PYTHONUNBUFFERED: '1',
46
+ PYTHONIOENCODING: 'utf-8',
47
+ PYTHONUTF8: '1',
48
+ };
49
+ }
50
+
51
+ export type WhisperModelAlias = 'large-v3' | 'large' | 'turbo' | 'large-v3-turbo';
52
+
53
+ const MODEL_ALIASES: Record<string, WhisperModelAlias> = {
54
+ large: 'large-v3',
55
+ 'large-v3': 'large-v3',
56
+ turbo: 'turbo',
57
+ 'large-v3-turbo': 'turbo',
58
+ };
59
+
60
+ export function resolveWhisperModel(raw?: string | null): WhisperModelAlias {
61
+ const key = (raw ?? config.whisper.model ?? 'large-v3').trim().toLowerCase();
62
+ const resolved = MODEL_ALIASES[key];
63
+ if (!resolved) {
64
+ console.warn(`[whisper] Unknown model="${key}", falling back to large-v3`);
65
+ return 'large-v3';
66
+ }
67
+ return resolved;
68
+ }
69
+
70
+ function workerKey(model: string, device: string, computeType: string): string {
71
+ return `${model}|${device}|${computeType}`;
72
+ }
73
+
74
+ function forwardLines(label: 'stdout' | 'stderr', data: Buffer): void {
75
+ for (const line of data.toString().split(/\r?\n/)) {
76
+ if (line.length) console.log(`[whisper] ${label}: ${line}`);
77
+ }
78
+ }
79
+
80
+ function spawnOneShot(
81
+ audioFile: string,
82
+ transcriptionFile: string,
83
+ model: WhisperModelAlias,
84
+ callback: WhisperCallback
85
+ ): void {
86
+ const python = config.whisper.python;
87
+ const computeType = config.whisper.computeType;
88
+ const device = config.whisper.device;
89
+ const startTime = new Date();
90
+ const whisperArgs = [
91
+ transcribeScript,
92
+ '--audio', audioFile,
93
+ '--output', transcriptionFile,
94
+ '--model', model,
95
+ '--device', device,
96
+ '--compute-type', computeType,
97
+ '--initial-prompt', buildWhisperInitialPrompt(config.whisper.promptTerms),
98
+ ];
99
+
100
+ console.log(`[whisper] one-shot ${python} ${whisperArgs.map((arg) => JSON.stringify(arg)).join(' ')}`);
101
+
102
+ const child = spawn(python, ['-u', ...whisperArgs], {
103
+ windowsHide: true,
104
+ env: pythonEnv(),
105
+ });
106
+
107
+ child.stdout.on('data', (data: Buffer) => forwardLines('stdout', data));
108
+ child.stderr.on('data', (data: Buffer) => forwardLines('stderr', data));
109
+
110
+ child.on('error', (error: Error) => {
111
+ console.log(`[whisper] error: ${error.message}`);
112
+ callback({ err: error });
113
+ });
114
+
115
+ child.on('close', (code: number) => {
116
+ const elapsed = `${(Date.now() - startTime.getTime()) / 1000}s`;
117
+ console.log(`[whisper] child process exited with code ${code}`);
118
+ console.log(`[whisper] Total Elapsed: ${elapsed}`);
119
+ if (code === 0) {
120
+ callback({ err: null, result: { transcriptionFile, elapsed } });
121
+ return;
122
+ }
123
+ if (transcriptionLooksComplete(transcriptionFile)) {
124
+ const hint = code === WINDOWS_CUDA_TEARDOWN ? ' (CUDA teardown crash; transcript is complete)' : '';
125
+ console.log(`[whisper] process crashed with ${code}${hint}; keeping existing JSON`);
126
+ callback({ err: null, result: { transcriptionFile, elapsed } });
127
+ return;
128
+ }
129
+ callback({
130
+ err: new Error(`faster-whisper exited with code ${code}`),
131
+ result: { transcriptionFile, elapsed },
132
+ });
133
+ });
134
+ }
135
+
136
+ let worker: ChildProcess | null = null;
137
+ let workerRl: readline.Interface | null = null;
138
+ let status: WhisperWorkerStatus = 'off';
139
+ let currentKey = '';
140
+ let startPromise: Promise<void> | null = null;
141
+ let jobChain: Promise<void> = Promise.resolve();
142
+ let jobSeq = 0;
143
+ const pending = new Map<string, PendingJob>();
144
+
145
+ export function getWhisperWorkerStatus(): WhisperWorkerStatus {
146
+ return status;
147
+ }
148
+
149
+ function failPending(error: Error): void {
150
+ const jobs = [...pending.values()];
151
+ pending.clear();
152
+ for (const job of jobs) job.reject(error);
153
+ }
154
+
155
+ function handleWorkerMessage(raw: string): void {
156
+ let message: Record<string, unknown>;
157
+ try {
158
+ message = JSON.parse(raw) as Record<string, unknown>;
159
+ } catch {
160
+ if (raw.length) console.log(`[whisper] stdout: ${raw}`);
161
+ return;
162
+ }
163
+
164
+ const type = String(message.type || '');
165
+ if (type === 'ready') {
166
+ console.log(`[whisper] worker ready model=${message.model} device=${message.device}`);
167
+ return;
168
+ }
169
+ if (type === 'progress') {
170
+ const pct = message.pct == null ? '?' : message.pct;
171
+ const text = typeof message.text === 'string' ? message.text : '';
172
+ console.log(`[whisper] ${pct}% (${message.start}-${message.end}s) ${text}`);
173
+ return;
174
+ }
175
+ if (type === 'error') {
176
+ console.warn(`[whisper] worker: ${message.error || 'unknown error'}`);
177
+ return;
178
+ }
179
+ if (type !== 'done') return;
180
+
181
+ const id = String(message.id || '');
182
+ const job = pending.get(id);
183
+ if (!job) return;
184
+ pending.delete(id);
185
+ const elapsed = `${(Date.now() - job.startTime) / 1000}s`;
186
+ if (message.ok) {
187
+ console.log(`[whisper] worker done ${elapsed} chars=${message.chars} segments=${message.segments}`);
188
+ job.resolve(elapsed);
189
+ return;
190
+ }
191
+ job.reject(new Error(String(message.error || 'whisper worker job failed')));
192
+ }
193
+
194
+ function attachWorker(child: ChildProcess): void {
195
+ workerRl = readline.createInterface({ input: child.stdout!, crlfDelay: Infinity });
196
+ workerRl.on('line', handleWorkerMessage);
197
+ child.stderr?.on('data', (data: Buffer) => forwardLines('stderr', data));
198
+ child.on('error', (error: Error) => {
199
+ console.warn(`[whisper] worker error: ${error.message}`);
200
+ status = 'down';
201
+ failPending(error);
202
+ });
203
+ child.on('close', (code: number) => {
204
+ console.log(`[whisper] worker exited with code ${code}`);
205
+ workerRl?.close();
206
+ workerRl = null;
207
+ worker = null;
208
+ currentKey = '';
209
+ startPromise = null;
210
+ status = 'down';
211
+ const jobs = [...pending.values()];
212
+ pending.clear();
213
+ for (const job of jobs) {
214
+ if (transcriptionLooksComplete(job.transcriptionFile)) {
215
+ const hint = code === WINDOWS_CUDA_TEARDOWN ? ' (CUDA teardown crash; transcript is complete)' : '';
216
+ console.log(`[whisper] worker crashed with ${code}${hint}; keeping existing JSON`);
217
+ job.resolve(`${(Date.now() - job.startTime) / 1000}s`);
218
+ continue;
219
+ }
220
+ job.reject(new Error(`whisper worker exited with code ${code}`));
221
+ }
222
+ });
223
+ }
224
+
225
+ function sendWorker(payload: Record<string, unknown>): void {
226
+ if (!worker?.stdin?.writable) throw new Error('whisper worker stdin is not writable');
227
+ worker.stdin.write(`${JSON.stringify(payload)}\n`);
228
+ }
229
+
230
+ export async function startWhisperWorker(
231
+ modelSize: WhisperModelAlias = resolveWhisperModel()
232
+ ): Promise<void> {
233
+ const model = resolveWhisperModel(modelSize);
234
+ const device = config.whisper.device;
235
+ const computeType = config.whisper.computeType;
236
+ const key = workerKey(model, device, computeType);
237
+
238
+ if (status === 'ready' && worker && currentKey === key) return;
239
+ if (startPromise && currentKey === key) return startPromise;
240
+ if (worker && currentKey !== key) await stopWhisperWorker();
241
+
242
+ currentKey = key;
243
+ status = 'starting';
244
+ startPromise = new Promise<void>((resolve, reject) => {
245
+ console.log(`[whisper] starting worker (${model} ${device} ${computeType})`);
246
+ const child = spawn(
247
+ config.whisper.python,
248
+ [
249
+ '-u',
250
+ transcribeScript,
251
+ '--worker',
252
+ '--model',
253
+ model,
254
+ '--device',
255
+ device,
256
+ '--compute-type',
257
+ computeType,
258
+ ],
259
+ {
260
+ windowsHide: true,
261
+ stdio: ['pipe', 'pipe', 'pipe'],
262
+ env: pythonEnv(),
263
+ }
264
+ );
265
+ worker = child;
266
+ attachWorker(child);
267
+
268
+ const timer = setTimeout(() => {
269
+ cleanup();
270
+ reject(new Error(`whisper worker did not become ready in ${WORKER_READY_MS / 1000}s`));
271
+ void stopWhisperWorker();
272
+ }, WORKER_READY_MS);
273
+
274
+ const onLine = (line: string) => {
275
+ try {
276
+ const message = JSON.parse(line) as { type?: string };
277
+ if (message.type !== 'ready') return;
278
+ cleanup();
279
+ status = 'ready';
280
+ resolve();
281
+ } catch {
282
+ // non-JSON during load is forwarded by handleWorkerMessage
283
+ }
284
+ };
285
+
286
+ const onClose = (code: number | null) => {
287
+ cleanup();
288
+ reject(new Error(`whisper worker exited during startup (code ${code})`));
289
+ };
290
+
291
+ function cleanup() {
292
+ clearTimeout(timer);
293
+ workerRl?.off('line', onLine);
294
+ child.off('close', onClose);
295
+ }
296
+
297
+ workerRl?.on('line', onLine);
298
+ child.once('close', onClose);
299
+ child.once('error', (error) => {
300
+ cleanup();
301
+ reject(error);
302
+ });
303
+ }).finally(() => {
304
+ if (status !== 'ready') startPromise = null;
305
+ });
306
+
307
+ return startPromise;
308
+ }
309
+
310
+ export async function stopWhisperWorker(): Promise<void> {
311
+ const child = worker;
312
+ if (!child) {
313
+ if (status === 'ready' || status === 'starting') status = 'off';
314
+ return;
315
+ }
316
+ try {
317
+ sendWorker({ cmd: 'shutdown' });
318
+ } catch {
319
+ // process already gone
320
+ }
321
+ await new Promise<void>((resolve) => {
322
+ const timer = setTimeout(() => {
323
+ if (!child.killed) child.kill();
324
+ resolve();
325
+ }, SHUTDOWN_MS);
326
+ child.once('close', () => {
327
+ clearTimeout(timer);
328
+ resolve();
329
+ });
330
+ });
331
+ worker = null;
332
+ workerRl = null;
333
+ currentKey = '';
334
+ startPromise = null;
335
+ status = 'off';
336
+ }
337
+
338
+ async function transcribeViaWorker(
339
+ audioFile: string,
340
+ transcriptionFile: string,
341
+ model: WhisperModelAlias
342
+ ): Promise<string> {
343
+ await startWhisperWorker(model);
344
+ const id = String(++jobSeq);
345
+ const elapsed = await new Promise<string>((resolve, reject) => {
346
+ const timer = setTimeout(() => {
347
+ pending.delete(id);
348
+ reject(new Error(`whisper worker job timed out after ${JOB_TIMEOUT_MS / 1000}s`));
349
+ }, JOB_TIMEOUT_MS);
350
+ pending.set(id, {
351
+ id,
352
+ transcriptionFile,
353
+ startTime: Date.now(),
354
+ resolve: (value) => {
355
+ clearTimeout(timer);
356
+ resolve(value);
357
+ },
358
+ reject: (error) => {
359
+ clearTimeout(timer);
360
+ reject(error);
361
+ },
362
+ });
363
+ try {
364
+ sendWorker({
365
+ id,
366
+ cmd: 'transcribe',
367
+ audio: audioFile,
368
+ output: transcriptionFile,
369
+ model,
370
+ device: config.whisper.device,
371
+ compute_type: config.whisper.computeType,
372
+ initial_prompt: buildWhisperInitialPrompt(config.whisper.promptTerms),
373
+ });
374
+ } catch (error) {
375
+ pending.delete(id);
376
+ clearTimeout(timer);
377
+ reject(error instanceof Error ? error : new Error(String(error)));
378
+ }
379
+ });
380
+ return elapsed;
381
+ }
382
+
383
+ function enqueueJob<T>(fn: () => Promise<T>): Promise<T> {
384
+ const run = jobChain.then(fn, fn);
385
+ jobChain = run.then(
386
+ () => undefined,
387
+ () => undefined
388
+ );
389
+ return run;
390
+ }
391
+
392
+ export async function whisperTranscribe(
393
+ audioFile: string,
394
+ transcriptionFile: string,
395
+ callback: WhisperCallback,
396
+ modelSize: WhisperModelAlias = resolveWhisperModel()
397
+ ): Promise<void> {
398
+ const model = resolveWhisperModel(modelSize);
399
+ console.log(`[whisper] TRANSCRIBING FILE (${model})`, audioFile);
400
+
401
+ try {
402
+ const elapsed = await enqueueJob(() => transcribeViaWorker(audioFile, transcriptionFile, model));
403
+ callback({ err: null, result: { transcriptionFile, elapsed } });
404
+ } catch (error) {
405
+ const message = error instanceof Error ? error.message : String(error);
406
+ console.warn(`[whisper] worker failed (${message}); falling back to one-shot`);
407
+ spawnOneShot(audioFile, transcriptionFile, model, callback);
408
+ }
409
+ }
package/src/mcp.ts ADDED
@@ -0,0 +1,151 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { z } from 'zod';
4
+ import { config } from './config.ts';
5
+ import { allowedRoots } from './lib/pathAllowLib.ts';
6
+ import { dictawhisperVersion } from './lib/cleanupProvenanceLib.ts';
7
+ import {
8
+ getJournalNote,
9
+ listJournalTags,
10
+ loadJournalNotes,
11
+ recentJournal,
12
+ searchJournal,
13
+ } from './lib/journalQueryLib.ts';
14
+ import {
15
+ getJournalIndex,
16
+ initJournalIndex,
17
+ journalTags,
18
+ recentJournalIndex,
19
+ searchJournalIndex,
20
+ } from './lib/journalService.ts';
21
+
22
+ const readOnly = {
23
+ readOnlyHint: true,
24
+ destructiveHint: false,
25
+ openWorldHint: false,
26
+ } as const;
27
+
28
+ function jsonText(value: unknown) {
29
+ return { content: [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }] };
30
+ }
31
+
32
+ function loadNotes() {
33
+ return loadJournalNotes(allowedRoots());
34
+ }
35
+
36
+ function readyIndex() {
37
+ try {
38
+ const index = getJournalIndex() || initJournalIndex();
39
+ return index.stats().notes > 0 ? index : null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ function createServer(): McpServer {
46
+ const server = new McpServer({
47
+ name: 'dictawhisper',
48
+ version: dictawhisperVersion(),
49
+ description:
50
+ 'Read-only voice journal. Search and fetch notes from sidecar JSON on disk. There are no write tools.',
51
+ });
52
+
53
+ server.registerTool(
54
+ 'dictawhisper_search',
55
+ {
56
+ description:
57
+ 'Search voice notes by words, tags, or filename. Returns paths, dates, tags, and a short preview. Use dictawhisper_get_note for the full cleaned text.',
58
+ inputSchema: {
59
+ query: z.string().optional().describe('Words to search in cleaned text, tags, or filename'),
60
+ tags: z.array(z.string()).optional().describe('AND filter: note must have all of these tags'),
61
+ since: z.string().optional().describe('Inclusive start day YYYY-MM-DD'),
62
+ until: z.string().optional().describe('Inclusive end day YYYY-MM-DD'),
63
+ limit: z.number().int().min(1).max(50).optional().describe('Max hits (default 10)'),
64
+ mode: z.enum(['lex', 'semantic', 'hybrid']).optional().describe('Search mode (default from config)'),
65
+ },
66
+ annotations: readOnly,
67
+ },
68
+ async ({ query, tags, since, until, limit, mode }) => {
69
+ if (!String(query || '').trim() && !(tags && tags.length)) {
70
+ return jsonText({ error: 'provide query and/or tags' });
71
+ }
72
+ const hits = readyIndex()
73
+ ? await searchJournalIndex({ query, tags, since, until, limit, mode })
74
+ : searchJournal(loadNotes(), { query, tags, since, until, limit });
75
+ return jsonText({ count: hits.length, hits });
76
+ }
77
+ );
78
+
79
+ server.registerTool(
80
+ 'dictawhisper_get_note',
81
+ {
82
+ description:
83
+ 'Fetch one note by sidecar path (from search/recent) or a unique basename. Returns cleaned text and tags. Set includeRaw for the Whisper transcript.',
84
+ inputSchema: {
85
+ file: z.string().describe('Absolute sidecar path, or unique basename like 2026-08-15.json'),
86
+ includeRaw: z.boolean().optional().describe('Include the raw Whisper transcript'),
87
+ },
88
+ annotations: readOnly,
89
+ },
90
+ async ({ file, includeRaw }) => {
91
+ const resolved = readyIndex()?.findJsonFile(file) || file;
92
+ const result = getJournalNote(loadNotes(), resolved, { includeRaw });
93
+ if (!result.ok) return jsonText({ error: result.error });
94
+ return jsonText(result.note);
95
+ }
96
+ );
97
+
98
+ server.registerTool(
99
+ 'dictawhisper_list_tags',
100
+ {
101
+ description: 'List tags in the journal with counts. Singletons are hidden unless includeSingletons is true.',
102
+ inputSchema: {
103
+ includeSingletons: z.boolean().optional(),
104
+ limit: z.number().int().min(1).max(500).optional().describe('Max tags (default 200)'),
105
+ },
106
+ annotations: readOnly,
107
+ },
108
+ async ({ includeSingletons, limit }) => {
109
+ const tags = readyIndex()
110
+ ? journalTags({ includeSingletons, limit })
111
+ : listJournalTags(loadNotes(), { includeSingletons, limit });
112
+ return jsonText({ count: tags.length, tags });
113
+ }
114
+ );
115
+
116
+ server.registerTool(
117
+ 'dictawhisper_recent',
118
+ {
119
+ description: 'Newest notes first. Optional tag and day range filters.',
120
+ inputSchema: {
121
+ limit: z.number().int().min(1).max(50).optional().describe('Max notes (default 20)'),
122
+ tags: z.array(z.string()).optional(),
123
+ since: z.string().optional().describe('Inclusive start day YYYY-MM-DD'),
124
+ until: z.string().optional().describe('Inclusive end day YYYY-MM-DD'),
125
+ },
126
+ annotations: readOnly,
127
+ },
128
+ async ({ limit, tags, since, until }) => {
129
+ const hits = readyIndex()
130
+ ? recentJournalIndex({ limit, tags, since, until })
131
+ : recentJournal(loadNotes(), { limit, tags, since, until });
132
+ return jsonText({ count: hits.length, hits });
133
+ }
134
+ );
135
+
136
+ return server;
137
+ }
138
+
139
+ async function main() {
140
+ if (!config.watch.roots.length && !config.watch.browserDropFolder) {
141
+ console.error('[mcp] no watch roots in config.json');
142
+ }
143
+ const transport = new StdioServerTransport();
144
+ const server = createServer();
145
+ await server.connect(transport);
146
+ }
147
+
148
+ main().catch((error) => {
149
+ console.error(error instanceof Error ? error.message : error);
150
+ process.exit(1);
151
+ });
@@ -0,0 +1,62 @@
1
+ export { CLEAN_PROMPT_VERSION } from '../types/transcription.ts';
2
+
3
+ export function buildCleanTranscriptionPrompt(rawText: string, preferredTags: string[] = []): string {
4
+ const preferred =
5
+ preferredTags.length > 0
6
+ ? `
7
+ <PREFERRED_TAGS>
8
+ When a topic already has a tag below, reuse it instead of inventing a close variant (plural, hyphen, or synonym).
9
+ Only add a new tag when none of these cover the topic.
10
+ ${preferredTags.join(', ')}
11
+ </PREFERRED_TAGS>
12
+ `
13
+ : '';
14
+
15
+ return `
16
+ <AGENT_ROLE>
17
+ You are an expert transcription editor specializing in audio journals.
18
+ Clean the raw Whisper transcript in RAW_TRANSCRIPTION so it is readable, then return cleanedTranscription and tags.
19
+ This is a cleanup pass only. It is not a summary, rewrite, or interpretation.
20
+ </AGENT_ROLE>
21
+
22
+ <KEY_RULES>
23
+ - Keep every idea, fact, name, number, emotion, and tangent. Length is not a concern.
24
+ - Do not add information. Do not guess what the speaker probably meant.
25
+ - If a phrase is garbled, implausible, or only half a word, leave those words as they appear. Do not replace them with a fluent guess.
26
+ - Do not change names, places, or uncommon words to more common lookalikes.
27
+ - Always remove vocalized pauses: uh, um, umm, hmm. Do not leave them in.
28
+ - "Yeah", "yes", and "no" are content when they answer something. Keep those.
29
+ - Drop "like" and "you know" when they are only pacing, not meaning.
30
+ - Collapse immediate repeats from speech or ASR: "the the the" → "the", "it's, it's, it's" → "it's", "very very very very" → "very".
31
+ - If two consecutive sentences or lines say the same thing, keep one.
32
+ - Do not keep Whisper hallucination loops (the same word or clause pasted many times).
33
+ - Fix punctuation, capitalization, and broken grammar from speech so it reads cleanly, keeping the original words.
34
+ - Keep the speaker's tone and stream-of-consciousness, including jumps.
35
+ - Insert a blank line at each topic shift, roughly every 2–4 sentences. Do not emit one unbroken paragraph.
36
+ - No commentary outside the JSON.
37
+ </KEY_RULES>
38
+
39
+ <TOPIC_TAGS>
40
+ Generate topic tags based solely on the content. Tags MUST:
41
+ - Cover key elements like locations, topics, people (use names as spoken), subjects, events, emotions, or themes.
42
+ - Be in lower-dash-case format (e.g., "new-york-city", "personal-reflection", "family-discussion").
43
+ - Be concise, relevant, and non-redundant (aim for 5-15 tags, depending on content length).
44
+ </TOPIC_TAGS>
45
+ ${preferred}
46
+
47
+ <OUTPUT_JSON_FORMAT>
48
+ {
49
+ "cleanedTranscription": "Cleaned transcription text here",
50
+ "tags": ["tag-one", "tag-two", "tag-three"]
51
+ }
52
+ </OUTPUT_JSON_FORMAT>
53
+
54
+ <FINAL_OUTPUT_RULES>
55
+ - Return only the JSON object in OUTPUT_JSON_FORMAT. No fence, no extra fields, no commentary.
56
+ </FINAL_OUTPUT_RULES>
57
+
58
+ <RAW_TRANSCRIPTION>
59
+ ${rawText}
60
+ </RAW_TRANSCRIPTION>
61
+ `;
62
+ }
@@ -0,0 +1,38 @@
1
+ export function buildConsolidateTagsPrompt(
2
+ tags: { tag: string; count: number }[],
3
+ localGroups: { keep: string; drop: string[] }[]
4
+ ): string {
5
+ const inventory = tags.map((item) => `${item.tag}\t${item.count}`).join('\n');
6
+ const already = localGroups.length
7
+ ? localGroups.map((group) => `${group.keep} <- ${group.drop.join(', ')}`).join('\n')
8
+ : '(none)';
9
+
10
+ return `
11
+ <AGENT_ROLE>
12
+ You consolidate topic tags from a personal voice journal.
13
+ The inventory is existing tags with how many notes use them.
14
+ A local pass already merged obvious spelling, hyphen, and plural twins.
15
+ Your job is only the leftovers that are the same topic in different words.
16
+ </AGENT_ROLE>
17
+
18
+ <RULES>
19
+ - Merge only when a person would treat the tags as one filter: typos the local pass missed, obvious synonyms, or the same phrase with a tiny wording change.
20
+ - Do not merge related-but-different topics. family-discussion and family-conflict stay separate. new-york and new-york-city stay separate. work and workplace-conflict stay separate.
21
+ - Do not invent a new canonical name. keep must be one of the existing tags in that group, usually the more common one.
22
+ - Do not repeat merges already listed in LOCAL_MERGES.
23
+ - If nothing else should merge, return {"merges":[]}.
24
+ </RULES>
25
+
26
+ <OUTPUT_JSON_FORMAT>
27
+ {"merges":[{"keep":"canonical-tag","drop":["alias-one","alias-two"]}]}
28
+ </OUTPUT_JSON_FORMAT>
29
+
30
+ <LOCAL_MERGES>
31
+ ${already}
32
+ </LOCAL_MERGES>
33
+
34
+ <TAG_INVENTORY>
35
+ ${inventory}
36
+ </TAG_INVENTORY>
37
+ `;
38
+ }
@@ -0,0 +1,11 @@
1
+ const BASE_INITIAL_PROMPT =
2
+ 'This is a personal audio journal spoken in English. ' +
3
+ 'Transcribe the speech accurately with natural punctuation and capitalization. ' +
4
+ 'Keep filler words, false starts, and repetitions as spoken. ' +
5
+ 'Do not paraphrase. Prefer unusual names and terms over common words that sound similar.';
6
+
7
+ export function buildWhisperInitialPrompt(promptTerms: string[] = []): string {
8
+ const terms = promptTerms.map((term) => String(term || '').trim()).filter(Boolean);
9
+ if (!terms.length) return BASE_INITIAL_PROMPT;
10
+ return `${BASE_INITIAL_PROMPT} Names and terms that may appear: ${terms.join(', ')}.`;
11
+ }