import { Disposable } from "../../../../../base/common/lifecycle.js"; import { ICommandService } from "../../../../../platform/commands/common/commands.service.js"; import { IContextKeyService } from "../../../../../platform/contextkey/common/contextkey.service.js"; import { IConfigurationService } from "../../../../../platform/configuration/common/configuration.service.js"; import { INotificationService } from "../../../../../platform/notification/common/notification.service.js"; import { IProgressService } from "../../../../../platform/progress/common/progress.service.js"; import { ILogService } from "../../../../../platform/log/common/log.service.js"; import { IStorageService } from "../../../../../platform/storage/common/storage.service.js"; import { ITelemetryService } from "../../../../../platform/telemetry/common/telemetry.service.js"; import { IEnvironmentService } from "../../../../../platform/environment/common/environment.service.js"; import { ILocalTranscriptionService } from "../../../../../platform/localTranscription/common/localTranscription.service.js"; import { IProductService } from "../../../../../platform/product/common/productService.service.js"; import { IAuthenticationService } from "../../../../services/authentication/common/authentication.service.js"; import { IAccessibilitySignalService } from "../../../../../platform/accessibilitySignal/browser/accessibilitySignalService.service.js"; import { IAccessibilityService } from "../../../../../platform/accessibility/common/accessibility.service.js"; import { ILanguageModelsService } from "../../common/languageModels.service.js"; import { IChatUtilityModelService } from "../../common/chatUtilityModelService.service.js"; import { IPromptsService } from "../../common/promptSyntax/service/promptsService.service.js"; import { ChatEntitlement } from "../../../../services/chat/common/chatEntitlementService.js"; import { IChatEntitlementService } from "../../../../services/chat/common/chatEntitlementService.service.js"; import { IVoiceCodeTranscriptionClient } from "./voiceCodeTranscriptionClient.service.js"; import { IChatSpeechToTextService } from "./chatSpeechToTextService.service.js"; /** * Command that imports a locally supplied Foundry Local dictation model package * into the model cache. Registered in the desktop layer * (`installDictationModelAction.ts`); referenced here so a failed download in a * registry-blocked environment can offer the offline install as a next step. */ export declare const INSTALL_DICTATION_MODEL_COMMAND_ID = "workbench.action.chat.installDictationModel"; export declare function stripDictationFillers(text: string): string; export declare function selectAuthoritativeDictationTranscript(liveTranscript: string, backendTranscript: string | undefined): string; export declare function selectFinalDictationTranscript(liveTranscript: string, backendTranscript: string | undefined, preserveLiveTranscript: boolean): string; export declare function createDictationCleanupSystemPrompt(dictationInstructions?: string): string; /** * Selects the dictation model. On-device model ids (e.g. * `nemotron-3.5-asr-streaming-0.6b`) run through {@link ILocalTranscriptionService}; * the sentinel {@link DICTATION_MAI_MODEL_ID} routes to the cloud voice service instead. */ export declare const DICTATION_MODEL_SETTING = "dictation.model"; export declare enum DictationSettingId { ShowTranscript = "dictation.showTranscript", ShowButton = "dictation.showButton" } /** `dictation.model` sentinel selecting the cloud transcription backend. */ export declare const DICTATION_MAI_MODEL_ID = "mai"; /** * Which backend transcribes dictation audio: * - `nemo`: an on-device model via {@link ILocalTranscriptionService} (Foundry Local). * - `mai`: the cloud transcription service. */ type DictationBackend = "nemo" | "mai"; export declare function isDictationEntitled(entitlement: ChatEntitlement, isInternal: boolean, usesMai: boolean): boolean; export declare function resolveDictationBackend(configuredModel: string | undefined, policyModel: string | undefined, web: boolean): DictationBackend; /** * A completed dictation whose text has now left the input (submitted or * cleared), measured to compare what was dictated against what was sent. Only * aggregate character metrics are logged; the transcript text never is. */ export interface IDictationAccuracyMeasurement { /** The text originally inserted by dictation. */ readonly dictatedText: string; /** The text occupying the dictated region at the moment it left the input. */ readonly submittedText: string; /** Backend that produced the dictated text, captured when dictation finished. */ readonly backend: string; /** Surface the dictation ran in, for slicing. */ readonly surface: ChatDictationSurface; /** Whether this was measured at an actual submit versus a clear/teardown. */ readonly submitted: boolean; } export declare enum ChatSpeechToTextState { /** Not recording. */ Idle = "idle", /** Capturing microphone audio and streaming it for transcription. */ Recording = "recording", /** Recording stopped, awaiting the final transcript. */ Transcribing = "transcribing" } /** * The surface a dictation session was started from. Reported in telemetry so * built-in dictation usage can be attributed to the chat input, an editor, or * the terminal. */ export type ChatDictationSurface = "chat" | "editor" | "terminal"; /** A live dictation transcript update. */ export interface IChatDictationTranscript { /** Full cumulative transcript to display. */ readonly text: string; /** * The leading portion of `text` that is finalized (committed) by the * recognizer. Note that streaming backends endpoint segments almost as fast * as they are spoken, so this is not a good signal for how much of the * transcript has settled from the user's point of view. */ readonly finalizedText: string; } export interface IChatSpeechToTextStopOptions { /** Keep the cumulative transcript emitted while recording unless the backend's post-stop hypothesis extends it. */ readonly preserveLiveTranscript?: boolean; } export declare function isDictationActiveOnSurface(service: IChatSpeechToTextService, surface: ChatDictationSurface): boolean; export declare class ChatSpeechToTextService extends Disposable implements IChatSpeechToTextService { private readonly _configurationService; private readonly _notificationService; private readonly _progressService; private readonly _logService; private readonly _commandService; private readonly _storageService; private readonly _telemetryService; private readonly _environmentService; private readonly _localTranscription; private readonly _transcriptionClient; private readonly _authenticationService; private readonly _productService; private readonly _accessibilitySignalService; private readonly _accessibilityService; private readonly _languageModelsService; private readonly _chatUtilityModelService; private readonly _promptsService; private readonly _chatEntitlementService; readonly _serviceBrand: undefined; private readonly _onDidChangeState; readonly onDidChangeState: import("../../../../../base/common/event.js").Event; private readonly _onDidUpdateTranscript; readonly onDidUpdateTranscript: import("../../../../../base/common/event.js").Event; private readonly _onDidChangePreparingModel; readonly onDidChangePreparingModel: import("../../../../../base/common/event.js").Event; private _isPreparingModel; get isPreparingModel(): boolean; private readonly _onDidChangeDownloadingModel; readonly onDidChangeDownloadingModel: import("../../../../../base/common/event.js").Event; private _isDownloadingModel; get isDownloadingModel(): boolean; private readonly _onDidChangeModelDownloadProgress; readonly onDidChangeModelDownloadProgress: import("../../../../../base/common/event.js").Event; private _modelDownloadProgress; get modelDownloadProgress(): number | undefined; /** * Active download-progress notification, shown while the on-device model is * downloading to disk. `report` drives the progress bar, `complete` resolves * the backing task so the notification dismisses. `lastReported` is the last * percentage pushed, so we can translate absolute progress into increments. */ private _downloadNotification; /** Most recent model status, used to re-sync the notification on screen-reader changes. */ private _lastModelStatus; private _state; get state(): ChatSpeechToTextState; private _entitlementCheckScheduled; private _startGeneration; private _startInProgress; private _hasGitHubSession; private _githubSessionGeneration; get isBusy(): boolean; get currentSurface(): ChatDictationSurface; private readonly _recordingContextKey; private readonly _configuredContextKey; private readonly _preparingContextKey; private readonly _usesMaiContextKey; private _mediaStream; private _audioContext; private _sourceNode; private _analyserNode; private _workletNode; private _captureGeneration; private _sessionGeneration; private _pendingStart; private _pendingStop; private _pendingLocalTeardown; /** Drains the capture worklet's trailing buffer; see {@link IPcmCaptureNode.flush}. */ private _flushCapture; private readonly _localSessionDisposables; /** Backend selected for the in-progress session; set at `start`. */ private _activeBackend; /** Disposables for the active MAI session (transcription listener, etc.). */ private readonly _maiSessionDisposables; /** Capture turn id for the active MAI push-to-talk turn. */ private _maiTurnId; /** Resolves when the backend emits the final transcript after `ptt_end`. */ private _maiFinalTranscript; private _maiReceivedFinal; get isConfigured(): boolean; get showTranscriptWhileDictating(): boolean; get analyserNode(): AnalyserNode | undefined; /** Finalized (committed) utterances, space-joined. */ private _finalizedText; /** In-progress text for the current utterance (from delta events). */ private _deltaText; /** Normalized prefix the backend reports as finalized, used to style the in-progress tail. */ private _backendFinalizedText; private _sessionStartMs; private _sessionSegments; private _sessionPartialUpdates; private _sessionErrorCode; private _sessionErrorName; private _sessionCloseCode; private _sessionSurface; /** Timestamp of the first streamed audio chunk, to measure transcription latency. */ private _firstAudioMs; /** Timestamp of the first transcript update, to measure transcription latency. */ private _firstTranscriptMs; /** Milliseconds from stopping recording to the final transcript resolving; -1 until measured. */ private _finalizeMs; private _sessionCleanupModel; /** Cancellation for the in-flight experimental LLM cleanup request, aborted when the session is cancelled or disposed. */ private readonly _cleanupCts; private _prepareStartMs; constructor(_configurationService: IConfigurationService, _notificationService: INotificationService, _progressService: IProgressService, _logService: ILogService, _commandService: ICommandService, contextKeyService: IContextKeyService, _storageService: IStorageService, _telemetryService: ITelemetryService, _environmentService: IEnvironmentService, _localTranscription: ILocalTranscriptionService, _transcriptionClient: IVoiceCodeTranscriptionClient, _authenticationService: IAuthenticationService, _productService: IProductService, _accessibilitySignalService: IAccessibilitySignalService, _accessibilityService: IAccessibilityService, _languageModelsService: ILanguageModelsService, _chatUtilityModelService: IChatUtilityModelService, _promptsService: IPromptsService, _chatEntitlementService: IChatEntitlementService); private _getLlmCleanupModel; /** Read the configured dictation backend, derived from the selected model. */ private _getBackend; private _isEntitledForBackend; get currentBackend(): string; logDictationAccuracy(measurement: IDictationAccuracyMeasurement): void; /** Dedicated transcription websocket endpoint used by the MAI backend. */ private _transcriptionWsUrl; private _updateConfiguredContextKey; private _refreshGitHubSession; private _setPreparingModel; private _setDownloadingModel; private _setModelDownloadProgress; private _logSessionTelemetry; /** * Emit the model-preparation telemetry event once, when the on-device model * reaches a terminal state (ready or error). `_prepareStartMs` guards against * duplicate emission, since `_handleModelStatus` can fire repeatedly. */ private _logModelPrepareTelemetry; private _setState; private get _transcript(); start(window: Window & typeof globalThis, surface?: ChatDictationSurface): Promise; private _start; private _startEntitled; private _isCurrentStart; /** Start the transcription session for the active backend. */ private _startBackendSession; /** * Record a transcript update on the shared cumulative surface and accumulate * the latency/stability telemetry, regardless of backend. `text` is the full * cumulative transcript; `finalizedText` is its committed prefix; `isFinal` * marks the terminal update after the session stops. */ private _emitTranscript; private _startMaiSession; private _handleMaiTranscription; private _failMaiSession; /** Resolve the GitHub access token used to authenticate the voice websocket. */ private _getGitHubToken; /** * Begin an on-device transcription session in the utility process and pipe * its interim/final results onto the shared cumulative-transcript surface. */ private _startLocalSession; private _getModelId; /** * Track model download/load so the toolbar mic can show a spinner until the * model is ready. While the model is downloading to disk (which can be * hundreds of MB on first use) a progress notification is also shown so the * user understands why dictation has not started yet; it dismisses once the * download finishes. Recording proceeds meanwhile and interim transcripts * begin once the model finishes loading. */ private _trackModelPreparation; /** * Drive the progress ring, download notification, and error handling from a * model status. Safe to call repeatedly and from both the status snapshot and * the change listener, since the progress and preparing-state updates are * idempotent. */ private _handleModelStatus; /** * Feed the toolbar progress ring: expose the download fraction while it is * known, and `undefined` (indeterminate ring) before the first byte total * arrives or once the download completes and the model is loading. */ private _updateModelDownloadProgress; /** * Surface model-preparation progress to screen-reader users via a progress * notification that stays visible across the download and load phases. */ private _updateDownloadNotification; private _completeDownloadNotification; /** * Handle a terminal model-preparation error. A download failure caused by a * blocked/unreachable model registry (common on locked-down corporate * networks) is recoverable by importing the model from a locally supplied * package, so in that case the error surfaces an action that launches the * offline install flow. Other failures show a plain error. */ private _failModelSession; /** * Abort the active recording because of an unrecoverable error (e.g. the * model failed to download/load), surfacing a notification instead of * silently returning an empty transcript. An optional recovery action is * attached to the notification when the failure is actionable. */ private _failSession; /** * A `pushAudio` IPC call rejected (e.g. the utility process exited or the * channel failed). Stop the recording once and surface the error rather than * leaving the UI showing an active recording with unhandled rejections. */ private _onAudioPushError; stopAndTranscribe(options?: IChatSpeechToTextStopOptions): Promise; private _stopAndTranscribe; /** * Experimental: run the raw ASR transcript through a small utility language * model to restore punctuation, capitalization, and paragraph breaks that the * streaming model omits. Returns the cleaned text, or `undefined` when cleanup * is skipped or fails (no model available, over-length input, timeout, * cancellation, or a streaming/result error) — in which case the caller keeps * the raw transcript. Only a fully successful response can replace it. */ private _cleanupWithLanguageModel; /** * Finish the active backend's turn and resolve with its final transcript: * the on-device service's `stop()`, or — for MAI — a `ptt_end` followed by a * short wait for the backend's final `transcription`. */ private _finishBackend; cancel(): Promise; /** Abort the active backend's session, discarding any transcript in flight. */ private _cancelBackend; private _startCapture; /** * Stream one captured PCM16 chunk to the active backend, recording the * first-chunk timestamp used for transcription-latency telemetry. */ private _pushAudio; private _stopCapture; switchMicrophone(window: Window & typeof globalThis, deviceId: string): Promise; private _teardown; private _acquireStream; } export {};