refactor(text): extract shared summarization service with tts/note/notification modes

Move server-side summarization out of lib/tts/summarization.js into a shared
lib/text module exposing tts, note and notification modes. TTS and notification
runtimes now delegate to the shared service, note mode is used to distill a
selected excerpt into a short project note. Expose the new endpoint via
/api/text/summarize and route it through the common request middleware.

Client voice/summarize.ts accepts a mode option and points at the new
endpoint with an absolute URL that respects the desktop server origin.
VS Code webview swaps the stubbed tts summarize path for /api/text/summarize
and hardens URL parsing with window.location.href as the base.
This commit is contained in:
Bohdan Triapitsyn
2026-04-18 13:46:51 +03:00
parent 4901cf60b8
commit a9c51f115e
11 changed files with 357 additions and 229 deletions
+11 -6
View File
@@ -1,14 +1,14 @@
# TTS Module Documentation
## Purpose
This module provides server-side Text-to-Speech services using OpenAI's TTS API, along with text summarization and sanitization utilities for preparing content for speech synthesis.
This module provides server-side Text-to-Speech services using OpenAI's TTS API. Shared text summarization now lives in `packages/web/server/lib/text/` and is consumed here in `tts` mode.
## Entrypoints and structure
- `packages/web/server/lib/tts/index.js`: Public entrypoint imported by `packages/web/server/index.js`.
- `packages/web/server/lib/tts/routes.js`: Express route registration for `/api/voice/*`, `/api/tts/*`, and `/api/stt/*` endpoints.
- `packages/web/server/lib/tts/capability-runtime.js`: runtime helper for probing local macOS `say` TTS voice capability.
- `packages/web/server/lib/tts/service.js`: TTS service implementation with OpenAI integration.
- `packages/web/server/lib/tts/summarization.js`: Text summarization and sanitization utilities using opencode.ai zen API.
- `packages/web/server/lib/text/summarization.js`: Shared text summarization and sanitization utilities using opencode.ai zen API.
- `packages/web/server/lib/tts/stt.js`: STT proxy for OpenAI-compatible transcription endpoints.
- `packages/web/server/lib/tts/base-url.js`: shared base URL validation and normalization for custom OpenAI-compatible endpoints.
@@ -19,9 +19,10 @@ This module provides server-side Text-to-Speech services using OpenAI's TTS API,
- `TTSService`: TTS service class for OpenAI audio generation.
- `TTS_VOICES`: Array of supported OpenAI voice identifiers.
### Summarization (from summarization.js)
- `summarizeText({ text, threshold, maxLength, zenModel })`: Summarizes text for TTS output using opencode.ai zen API.
### Shared text summarization (re-exported from ../text/summarization.js)
- `summarizeText({ text, threshold, maxLength, zenModel, mode })`: Shared text summarizer. TTS uses `mode: 'tts'`.
- `sanitizeForTTS(text)`: Sanitizes text by removing markdown, URLs, file paths, and other non-speakable content.
- `sanitizeForNote(text)`: Re-exported for note-mode callers that still import through the TTS surface.
### Capability runtime (capability-runtime.js)
- `detectSayTtsCapability(processLike)`: probes local `say -v "?"` support and returns `{ available, voices, reason }`.
@@ -35,7 +36,7 @@ This module provides server-side Text-to-Speech services using OpenAI's TTS API,
- `SUMMARIZE_TIMEOUT_MS`: 30000 (30 seconds timeout for zen API requests).
### Default values
- `summarizeText` defaults: `threshold` = 200, `maxLength` = 500, `zenModel` = 'gpt-5-nano'.
- `summarizeText` defaults: `threshold` = 200, `maxLength` = 500, `zenModel` = 'gpt-5-nano', `mode` = 'tts'.
- `generateSpeechStream` defaults: `voice` = 'coral', `model` = 'gpt-4o-mini-tts', `speed` = 1.0.
- `generateSpeechBuffer` defaults: `voice` = 'coral', `model` = 'gpt-4o-mini-tts', `speed` = 1.0.
@@ -66,6 +67,8 @@ Returns object with:
- `originalLength`: Optional number for original text length.
- `summaryLength`: Optional number for summarized text length.
The route-level text summarize API is now `/api/text/summarize`.
### `sanitizeForTTS`
Returns sanitized string with markdown, URLs, file paths, and special characters removed.
@@ -90,6 +93,8 @@ The TTS module is used by `packages/web/server/index.js` for:
- Summarizing long messages before TTS synthesis.
- Sanitizing text to remove non-speakable content.
The summarization logic itself is shared with notifications and notes, but this module uses it only in `tts` mode.
The server-side TTS approach bypasses mobile Safari's audio context restrictions by generating audio on the server and streaming to clients.
## Notes for contributors
@@ -108,7 +113,7 @@ The server-side TTS approach bypasses mobile Safari's audio context restrictions
### Error handling
- `generateSpeechStream` and `generateSpeechBuffer` throw descriptive errors for missing API keys or empty text.
- `summarizeText` catches zen API errors and falls back to original text with `summarized: false`.
- `summarizeText` catches zen API errors and returns mode-specific fallback text with `summarized: false`.
- All errors are logged to console with `[TTSService]` or `[Summarize]` prefix.
### API key management
+2 -1
View File
@@ -13,6 +13,7 @@ export {
export {
summarizeText,
sanitizeForTTS,
} from './summarization.js';
sanitizeForNote,
} from '../text/summarization.js';
export { transcribeAudio } from './stt.js';
+14 -8
View File
@@ -1,5 +1,6 @@
import express from 'express';
import { normalizeCustomOpenAIBaseURL } from './base-url.js';
import { summarizeText, sanitizeForTTS, sanitizeForNote } from '../text/summarization.js';
export function registerTtsRoutes(app, { resolveZenModel, sayTTSCapability }) {
let ttsModulePromise = null;
@@ -76,9 +77,8 @@ export function registerTtsRoutes(app, { resolveZenModel, sayTTSCapability }) {
// Optionally summarize long text before speaking using zen API
if (summarize && textToSpeak.length > threshold) {
try {
const { summarizeText } = await getTtsModule();
const speakZenModel = await resolveZenModel(typeof req.body?.zenModel === 'string' ? req.body.zenModel : undefined);
const result = await summarizeText({ text: textToSpeak, threshold, maxLength, zenModel: speakZenModel });
const result = await summarizeText({ text: textToSpeak, threshold, maxLength, zenModel: speakZenModel, mode: 'tts' });
if (result.summarized && result.summary) {
textToSpeak = result.summary;
@@ -115,23 +115,29 @@ export function registerTtsRoutes(app, { resolveZenModel, sayTTSCapability }) {
}
});
app.post('/api/tts/summarize', async (req, res) => {
app.post('/api/text/summarize', async (req, res) => {
try {
const { summarizeText } = await getTtsModule();
const { text, threshold = 200, maxLength = 500 } = req.body || {};
const { text, threshold = 200, maxLength = 500, mode } = req.body || {};
if (!text || typeof text !== 'string' || !text.trim()) {
return res.status(400).json({ error: 'Text is required' });
}
const sumZenModel = await resolveZenModel(typeof req.body?.zenModel === 'string' ? req.body.zenModel : undefined);
const result = await summarizeText({ text, threshold, maxLength, zenModel: sumZenModel });
const result = await summarizeText({
text,
threshold,
maxLength,
zenModel: sumZenModel,
mode: typeof mode === 'string' ? mode : 'tts',
});
return res.json(result);
} catch (error) {
console.error('[Summarize] Error:', error);
const { sanitizeForTTS } = await getTtsModule();
const sanitized = sanitizeForTTS(req.body?.text || '');
const sanitized = typeof req.body?.mode === 'string' && req.body.mode === 'note'
? sanitizeForNote(req.body?.text || '')
: sanitizeForTTS(req.body?.text || '');
return res.json({ summary: sanitized, summarized: false, reason: error.message });
}
});
@@ -1,171 +0,0 @@
/**
* Text Summarization Service
*
* Uses the opencode.ai zen API with gpt-5-nano for fast, lightweight summarization.
* Used by all TTS implementations (Browser, Say, OpenAI).
*/
function buildSummarizationPrompt(maxLength) {
return `You are a text summarizer for text-to-speech output. Create a concise, natural-sounding summary that captures the key points. Keep the summary under ${maxLength} characters.
CRITICAL INSTRUCTIONS:
1. Output ONLY the final summary - no thinking, no reasoning, no explanations
2. Do not show your work or thought process
3. Do not use any special characters, markdown, code, URLs, file paths, or formatting
4. Do not include phrases like "Here's a summary" or "In summary"
5. Just provide clean, speakable text that can be read aloud
6. Stay within the ${maxLength} character limit
Your response should be ready to speak immediately.`;
}
const SUMMARIZE_TIMEOUT_MS = 30_000;
/**
* Sanitize text for TTS output
* Removes markdown, URLs, file paths, and other non-speakable content
*/
export function sanitizeForTTS(text) {
if (!text || typeof text !== 'string') return '';
return text
// Remove markdown formatting
.replace(/[*_~`#]/g, '')
// Remove code blocks
.replace(/```[\s\S]*?```/g, '')
.replace(/`[^`]*`/g, '')
// Remove shell-like command patterns
.replace(/^\s*[$#>]\s*/gm, '')
// Remove common shell operators
.replace(/[|&;<>]/g, ' ')
// Remove backslashes (escape characters)
.replace(/\\/g, '')
// Remove brackets that might be interpreted specially
.replace(/[[\]{}()]/g, '')
// Remove quotes that might cause issues
.replace(/["']/g, '')
// Remove URLs
.replace(/https?:\/\/[^\s]+/g, ' a link ')
// Remove file paths
.replace(/\/[\w\-./]+/g, '')
// Collapse multiple spaces/newlines
.replace(/\s+/g, ' ')
.trim();
}
/**
* Extract text from zen API response
*/
function extractZenOutputText(data) {
if (!data || typeof data !== 'object') return null;
const output = data.output;
if (!Array.isArray(output)) return null;
const messageItem = output.find(
(item) => item && typeof item === 'object' && item.type === 'message'
);
if (!messageItem) return null;
const content = messageItem.content;
if (!Array.isArray(content)) return null;
const textItem = content.find(
(item) => item && typeof item === 'object' && item.type === 'output_text'
);
const text = typeof textItem?.text === 'string' ? textItem.text.trim() : '';
return text || null;
}
/**
* Summarize text using the opencode.ai zen API
*
* @param {Object} options
* @param {string} options.text - The text to summarize
* @param {number} options.threshold - Character threshold (don't summarize if under this length)
* @param {number} options.maxLength - Maximum character length for the summary output (50-2000)
* @param {string} [options.zenModel] - Override zen model (defaults to gpt-5-nano)
* @returns {Promise<{summary: string, summarized: boolean, reason?: string}>}
*/
export async function summarizeText({
text,
threshold = 200,
maxLength = 500,
zenModel,
}) {
// Don't summarize if text is under threshold
if (!text || text.length <= threshold) {
return {
summary: sanitizeForTTS(text || ''),
summarized: false,
reason: text ? 'Text under threshold' : 'No text provided',
};
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), SUMMARIZE_TIMEOUT_MS);
try {
const prompt = buildSummarizationPrompt(maxLength);
const response = await fetch('https://opencode.ai/zen/v1/responses', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: zenModel || 'gpt-5-nano',
input: [
{ role: 'user', content: `${prompt}\n\nText to summarize:\n${text}` },
],
stream: false,
reasoning: { effort: 'low' },
}),
signal: controller.signal,
});
if (!response.ok) {
const errorBody = await response.json().catch(() => ({}));
console.error('[Summarize] zen API error:', response.status, errorBody);
return {
summary: sanitizeForTTS(text),
summarized: false,
reason: `zen API returned ${response.status}`,
};
}
const data = await response.json();
const summary = extractZenOutputText(data);
if (summary) {
const sanitized = sanitizeForTTS(summary);
return {
summary: sanitized,
summarized: true,
originalLength: text.length,
summaryLength: sanitized.length,
};
}
return {
summary: sanitizeForTTS(text),
summarized: false,
reason: 'No response from model',
};
} catch (error) {
if (error.name === 'AbortError') {
console.error('[Summarize] Request timed out');
return {
summary: sanitizeForTTS(text),
summarized: false,
reason: 'Request timed out',
};
}
console.error('[Summarize] Error:', error);
return {
summary: sanitizeForTTS(text),
summarized: false,
reason: error.message,
};
} finally {
clearTimeout(timer);
}
}