A desktop coding agent with free access to frontier models.
TypeScript
feat(server): voice transcription through the gateway broker
Samrat Talukdare95d5d9cb5f1
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex 28026ee1..617eb7ff 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -126,6 +126,9 @@ const GATEWAY_ERROR_COPY: Record<string, string> = {gateway_overload: BUSY_COPY,queue_timeout: BUSY_COPY,provider_rate_limited: BUSY_COPY,+ voice_unavailable: "voice input is not available on this account yet.",+ transcription_unavailable: "the transcription service did not answer. Try again in a moment.",+ audio_unreadable: "the recording could not be read. Try again.",};/** Readable copy for a gateway error code, or null for a code it does not know. */@@ -498,6 +501,11 @@ function apiUrl(gatewayUrl: string, path: string): string {return url.toString();}+/** The backend's voice route, relative to the gateway URL (…/omnirush/v1/audio/transcriptions). */+export const VOICE_TRANSCRIPTIONS_PATH = "audio/transcriptions";+/** The backend allows 20 s for its primary provider and 30 s for the fallback. */+const VOICE_TRANSCRIBE_TIMEOUT_MS = 35_000;+/** The project archive routes the session archiver calls (archives, archives/key, archives/<id>/parts|complete|abort). */const ARCHIVE_API_PATH = /^archives(?:\/key|\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/(?:parts|complete|abort))?$/;@@ -742,8 +750,8 @@ export class OmniRushGatewayBroker {return Response.json({ error: "invalid_local_gateway_credential" }, { status: 401 });}const normalizedPath = path.replace(/^\/+/, "");- const allowed = (request.method === "GET" && normalizedPath === "models")- || (request.method === "POST" && (normalizedPath === "responses" || normalizedPath === "responses/compact"));+ const allowed = (request.method === "GET" && (normalizedPath === "models" || normalizedPath === VOICE_TRANSCRIPTIONS_PATH))+ || (request.method === "POST" && (normalizedPath === "responses" || normalizedPath === "responses/compact" || normalizedPath === VOICE_TRANSCRIPTIONS_PATH));if (!allowed) return Response.json({ error: "unsupported_gateway_path" }, { status: 404 });const requestBody = request.method === "GET"@@ -867,6 +875,31 @@ export class OmniRushGatewayBroker {}));}+ /**+ * One voice segment for the backend's POST /omnirush/v1/audio/transcriptions,+ * authenticated like collect(): the device bearer and the same bounded 401+ * refresh. The multipart body goes through as it came and is held only+ * for this call.+ */+ /** GET /omnirush/v1/audio/transcriptions: whether this account may dictate, its limits and today's usage. */+ voiceStatus(): Promise<Response> {+ return this.withDeviceBearer((state) => this.fetcher(upstreamUrl(state.gatewayUrl, VOICE_TRANSCRIPTIONS_PATH), {+ method: "GET",+ headers: { Authorization: `Bearer ${state.accessToken}`, Accept: "application/json" },+ signal: AbortSignal.timeout(8_000),+ }));+ }++ transcribe(body: ArrayBuffer, contentType: string, signal?: AbortSignal): Promise<Response> {+ const timeout = AbortSignal.timeout(VOICE_TRANSCRIBE_TIMEOUT_MS);+ return this.withDeviceBearer((state) => this.fetcher(upstreamUrl(state.gatewayUrl, VOICE_TRANSCRIPTIONS_PATH), {+ method: "POST",+ headers: { Authorization: `Bearer ${state.accessToken}`, "Content-Type": contentType, Accept: "application/json" },+ body,+ signal: signal ? AbortSignal.any([timeout, signal]) : timeout,+ }));+ }+/*** Sends with the current device bearer; a 401 is retried bounded like* handle(): adopt, then spend the adopted refresh token. `refresh: false`diff --git a/apps/server/src/omnirush-voice.test.ts b/apps/server/src/omnirush-voice.test.tsnew file mode 100644index 00000000..69d23a21--- /dev/null+++ b/apps/server/src/omnirush-voice.test.ts@@ -0,0 +1,181 @@+import { describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { mkdtemp } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";+import { OmniRushVoiceService, VOICE_MAX_UPLOAD_BYTES, voiceFlagFromCatalog, voiceProjectContext } from "./omnirush-voice.js";++type Call = { url: string; headers: Headers; body: ArrayBuffer | null };++function broker(answer: (call: Call) => Response | Promise<Response>, calls: Call[] = []) {+ return new OmniRushGatewayBroker({+ credentials: { gatewayUrl: "https://gateway.example/omnirush/v1", accessToken: "device-access", refreshToken: "device-refresh" },+ engineToken: "local-engine-token",+ fetch: async (input, init) => {+ const call = { url: String(input), headers: new Headers(init?.headers), body: (init?.body as ArrayBuffer | undefined) ?? null };+ calls.push(call);+ return answer(call);+ },+ });+}++function segmentUpload(bytes = 2_000): Request {+ const form = new FormData();+ form.append("file", new Blob([new Uint8Array(bytes)], { type: "audio/wav" }), "segment-0.wav");+ form.append("segment_index", "0");+ form.append("recording_id", "abc");+ return new Request("http://127.0.0.1/omnirush/voice/transcribe", { method: "POST", body: form });+}++describe("voice catalog flag", () => {+ test("reads features.voice, voice and voice.enabled; null when absent", () => {+ expect(voiceFlagFromCatalog({ object: "list", data: [], features: { voice: true } })).toBe(true);+ expect(voiceFlagFromCatalog({ features: { voice: { enabled: false } } })).toBe(false);+ expect(voiceFlagFromCatalog({ voice: false })).toBe(false);+ expect(voiceFlagFromCatalog({ voice: { enabled: true } })).toBe(true);+ expect(voiceFlagFromCatalog({ object: "list", data: [] })).toBeNull();+ expect(voiceFlagFromCatalog(null)).toBeNull();+ });+});++describe("voice through the gateway broker", () => {+ test("forwards the multipart segment unchanged with the device bearer", async () => {+ const calls: Call[] = [];+ const service = new OmniRushVoiceService(broker(() => Response.json({ text: "hello world", provider: "primary", duration_ms: 900 }), calls));+ const upload = segmentUpload();+ const expected = new Uint8Array(await upload.clone().arrayBuffer());+ const response = await service.transcribe(upload);+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({ text: "hello world", provider: "primary", duration_ms: 900 });+ expect(calls).toHaveLength(1);+ expect(calls[0]!.url).toBe("https://gateway.example/omnirush/v1/audio/transcriptions");+ expect(calls[0]!.headers.get("authorization")).toBe("Bearer device-access");+ expect(calls[0]!.headers.get("content-type")).toStartWith("multipart/form-data; boundary=");+ expect(new Uint8Array(calls[0]!.body!)).toEqual(expected);+ expect((await service.availability()).available).toBe(true);+ });++ test("an expired device token is refreshed once and the segment is sent again", async () => {+ const calls: Call[] = [];+ const service = new OmniRushVoiceService(broker((call) => {+ if (call.url.endsWith("/device/refresh")) {+ return Response.json({ access_token: "rotated", refresh_token: "rotated-refresh", gateway_url: "https://gateway.example/omnirush/v1" });+ }+ return call.headers.get("authorization") === "Bearer rotated"+ ? Response.json({ text: "ok" })+ : Response.json({ error: "expired" }, { status: 401 });+ }, calls));+ const response = await service.transcribe(segmentUpload());+ expect(response.status).toBe(200);+ expect(calls.map((call) => new URL(call.url).pathname)).toEqual([+ "/omnirush/v1/audio/transcriptions",+ "/omnirush/device/refresh",+ "/omnirush/v1/audio/transcriptions",+ ]);+ expect(calls[2]!.body!.byteLength).toBe(calls[0]!.body!.byteLength);+ });++ test("503 voice_unavailable is passed on and turns the mic off until it expires", async () => {+ let now = 0;+ const service = new OmniRushVoiceService(+ broker(() => Response.json({ detail: "voice_unavailable" }, { status: 503 })),+ { now: () => now },+ );+ const response = await service.transcribe(segmentUpload());+ expect(response.status).toBe(503);+ expect(await response.json()).toEqual({ detail: "voice_unavailable" });+ expect(await service.availability()).toEqual({ available: false, reason: "voice_unavailable" });+ now += 3 * 60_000;+ // Expired: the catalog is asked again (here it answers 503 too, so still unknown).+ expect((await service.availability()).available).toBeNull();+ });++ test("an older backend without the route (404) reads as voice unavailable", async () => {+ const service = new OmniRushVoiceService(broker(() => new Response("not found", { status: 404 })));+ const response = await service.transcribe(segmentUpload());+ expect(response.status).toBe(503);+ expect(((await response.json()) as { error: { code: string } }).error.code).toBe("voice_unavailable");+ });++ test("availability comes from the backend's voice status route", async () => {+ const calls: Call[] = [];+ const on = new OmniRushVoiceService(broker((call) => call.url.endsWith("/audio/transcriptions")+ ? Response.json({ object: "voice.status", available: true, reason: null, privacy: { audio_stored_by_omnirush: false, provider_retention_days: 30 }, usage: { remaining_seconds_today: 3_540 } })+ : Response.json({ object: "list", data: [] }), calls));+ expect(await on.availability()).toEqual({ available: true, reason: null, providerRetentionDays: 30, remainingSecondsToday: 3_540 });+ expect(calls.map((call) => new URL(call.url).pathname)).toEqual(["/omnirush/v1/audio/transcriptions"]);+ expect(calls[0]!.headers.get("authorization")).toBe("Bearer device-access");+ // Cached: no second request.+ await on.availability();+ expect(calls).toHaveLength(1);++ const off = new OmniRushVoiceService(broker(() => Response.json({ available: false, reason: "voice_unavailable" })));+ expect((await off.availability()).available).toBe(false);+ });++ test("a backend without the voice route (404) has no voice; one that cannot answer falls back to the catalog flag", async () => {+ const old = new OmniRushVoiceService(broker((call) => call.url.endsWith("/audio/transcriptions")+ ? Response.json({ detail: "Not Found" }, { status: 404 })+ : Response.json({ object: "list", data: [] })));+ expect(await old.availability()).toEqual({ available: false, reason: "voice_unavailable" });+ const flagged = new OmniRushVoiceService(broker((call) => call.url.endsWith("/audio/transcriptions")+ ? new Response("bad gateway", { status: 502 })+ : Response.json({ object: "list", data: [], features: { voice: false } })));+ expect(await flagged.availability()).toEqual({ available: false, reason: "voice_unavailable" });+ const unknown = new OmniRushVoiceService(broker(() => new Response("bad gateway", { status: 502 })));+ expect(await unknown.availability()).toEqual({ available: null, reason: null });+ });++ test("oversize and non-multipart uploads are refused locally, and nothing is sent", async () => {+ const calls: Call[] = [];+ const service = new OmniRushVoiceService(broker(() => Response.json({ text: "x" }), calls));+ expect((await service.transcribe(segmentUpload(VOICE_MAX_UPLOAD_BYTES + 1))).status).toBe(413);+ const json = new Request("http://127.0.0.1/omnirush/voice/transcribe", { method: "POST", body: "{}", headers: { "content-type": "application/json" } });+ expect((await service.transcribe(json)).status).toBe(400);+ expect(calls).toHaveLength(0);+ });++ test("signed out: 401 and no upstream call", async () => {+ const service = new OmniRushVoiceService(new OmniRushGatewayBroker({ engineToken: "t" }));+ expect((await service.transcribe(segmentUpload())).status).toBe(401);+ expect(await service.availability()).toEqual({ available: false, reason: "omnirush_account_required" });+ });++ test("logs carry sizes and status only, never the transcript", async () => {+ const lines: string[] = [];+ const service = new OmniRushVoiceService(broker(() => Response.json({ text: "my secret sentence" })), {+ log: (level, message, attributes) => lines.push(JSON.stringify({ level, message, attributes })),+ });+ await service.transcribe(segmentUpload());+ expect(lines).toHaveLength(1);+ expect(lines[0]).not.toContain("secret");+ expect(lines[0]).toContain("\"status\":200");+ });++ test("the engine-facing broker mount allows the transcription path", async () => {+ const calls: Call[] = [];+ const gateway = broker(() => Response.json({ text: "via mount" }), calls);+ const upload = segmentUpload();+ const response = await gateway.handle(new Request("http://127.0.0.1/omnirush-gateway/v1/audio/transcriptions", {+ method: "POST",+ headers: { Authorization: "Bearer local-engine-token", "content-type": upload.headers.get("content-type")! },+ body: await upload.arrayBuffer(),+ }), "audio/transcriptions");+ expect(response.status).toBe(200);+ expect(calls[0]!.url).toBe("https://gateway.example/omnirush/v1/audio/transcriptions");+ expect(calls[0]!.headers.get("authorization")).toBe("Bearer device-access");+ });+});++describe("voice project context", () => {+ test("names the repository and branch of a git folder, or just the folder", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "voice-ctx-"));+ const repo = path.join(root, "my-repo");+ execFileSync("git", ["init", "-q", "-b", "feat/voice-mode", repo]);+ expect(await voiceProjectContext(repo)).toEqual({ repo: "my-repo", branch: "feat/voice-mode" });+ expect(await voiceProjectContext(root)).toEqual({ repo: path.basename(root), branch: null });+ expect(await voiceProjectContext(null)).toEqual({ repo: null, branch: null });+ });+});diff --git a/apps/server/src/omnirush-voice.ts b/apps/server/src/omnirush-voice.tsnew file mode 100644index 00000000..0ba5db59--- /dev/null+++ b/apps/server/src/omnirush-voice.ts@@ -0,0 +1,221 @@+/**+ * Voice dictation's local half. The renderer records and segments speech+ * itself (voice-core); each segment is POSTed here and forwarded, unchanged,+ * to omnirush.ai's POST /omnirush/v1/audio/transcriptions with the device+ * bearer (the renderer never holds it). The audio exists only in this+ * request's memory: it is never written, logged, cached or handed to the+ * collector. Only the text the user finally sends becomes a prompt.+ */+import { execFile } from "node:child_process";+import path from "node:path";++import type { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";++/** 125 s of 16 kHz mono WAV plus multipart overhead; the backend enforces the same cap. */+export const VOICE_MAX_UPLOAD_BYTES = 4 * 1024 * 1024;+const STATUS_TTL_MS = 5 * 60_000;+const UNAVAILABLE_TTL_MS = 2 * 60_000;++export type VoiceAvailabilityState = {+ /** Null when not known yet (the service did not answer); the first upload then decides. */+ available: boolean | null;+ reason: string | null;+ /** Days the speech provider keeps uploaded audio (for the privacy note), when the backend says. */+ providerRetentionDays?: number | null;+ /** Seconds of dictation left today, when the account has a daily cap. */+ remainingSecondsToday?: number | null;+};++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** A boolean flag, or `{ enabled }`. */+function flagOf(value: unknown): boolean | null {+ if (typeof value === "boolean") return value;+ return isRecord(value) && typeof value.enabled === "boolean" ? value.enabled : null;+}++/**+ * The catalog's voice flag: `features.voice` or a top-level `voice`, each a+ * boolean or `{ enabled }`. Null when the catalog does not mention voice.+ */+export function voiceFlagFromCatalog(body: unknown): boolean | null {+ if (!isRecord(body)) return null;+ return (isRecord(body.features) ? flagOf(body.features.voice) : null) ?? flagOf(body.voice);+}++/** `{available, reason, privacy: {provider_retention_days}, usage: {remaining_seconds_today}}` from the backend's voice status. */+export function voiceStatusFromBody(body: unknown): VoiceAvailabilityState {+ if (!isRecord(body)) return { available: null, reason: null };+ const available = typeof body.available === "boolean" ? body.available : null;+ const retention = isRecord(body.privacy) ? body.privacy.provider_retention_days : null;+ const remaining = isRecord(body.usage) ? body.usage.remaining_seconds_today : null;+ return {+ available,+ reason: typeof body.reason === "string" ? body.reason : available === false ? "voice_unavailable" : null,+ providerRetentionDays: typeof retention === "number" ? retention : null,+ remainingSecondsToday: typeof remaining === "number" ? remaining : null,+ };+}++type VoiceBroker = Pick<OmniRushGatewayBroker, "enabled" | "modelCatalog" | "voiceStatus" | "transcribe">;+type VoiceLog = (level: "info" | "warn", message: string, attributes?: Record<string, unknown>) => void;++export class OmniRushVoiceService {+ private cached: { state: VoiceAvailabilityState; until: number } | null = null;+ private inflight: Promise<VoiceAvailabilityState> | null = null;++ constructor(+ private readonly broker: VoiceBroker,+ private readonly options: { log?: VoiceLog; now?: () => number } = {},+ ) {}++ get signedIn(): boolean {+ return this.broker.enabled;+ }++ private now(): number {+ return this.options.now?.() ?? Date.now();+ }++ /** Whether the account may use voice, from the model catalog (cached) and the last transcription refusal. */+ async availability(): Promise<VoiceAvailabilityState> {+ if (!this.broker.enabled) return { available: false, reason: "omnirush_account_required" };+ if (this.cached && this.cached.until > this.now()) return this.cached.state;+ this.inflight ??= this.readCatalog().finally(() => {+ this.inflight = null;+ });+ return this.inflight;+ }++ /**+ * The backend's GET /omnirush/v1/audio/transcriptions answers for this+ * account. A backend without the route (404/405) has no voice. When it+ * cannot be asked, the model catalog's voice flag is the fallback.+ */+ private async readCatalog(): Promise<VoiceAvailabilityState> {+ let state: VoiceAvailabilityState = { available: null, reason: null };+ try {+ const response = await this.broker.voiceStatus();+ if (response.ok) {+ state = voiceStatusFromBody(await response.json().catch(() => null));+ } else {+ await response.body?.cancel().catch(() => undefined);+ if (response.status === 404 || response.status === 405) state = { available: false, reason: "voice_unavailable" };+ }+ } catch {+ // Not answered: fall through to the catalog.+ }+ if (state.available === null) {+ try {+ const response = await this.broker.modelCatalog();+ if (response.ok) {+ const flag = voiceFlagFromCatalog(await response.json().catch(() => null));+ if (flag !== null) state = { available: flag, reason: flag ? null : "voice_unavailable" };+ } else {+ await response.body?.cancel().catch(() => undefined);+ }+ } catch {+ // Unknown: the mic stays usable and the first upload decides.+ }+ }+ // An unknown answer is asked again soon; a known one lasts the TTL.+ this.cached = { state, until: this.now() + (state.available === null ? 30_000 : STATUS_TTL_MS) };+ return state;+ }++ /**+ * Forwards one segment. The multipart body is passed through byte for byte;+ * only its size is checked here. A refusal that says voice is off for the+ * account is remembered so the mic can be disabled.+ */+ async transcribe(request: Request): Promise<Response> {+ if (!this.broker.enabled) {+ return Response.json({ error: { code: "omnirush_account_required", message: "Sign in to omnirush.ai to use voice." } }, { status: 401 });+ }+ const contentType = request.headers.get("content-type") ?? "";+ if (!contentType.toLowerCase().startsWith("multipart/form-data")) {+ return Response.json({ error: { code: "invalid_payload", message: "Expected a multipart audio upload." } }, { status: 400 });+ }+ const declared = Number(request.headers.get("content-length") ?? "0");+ if (Number.isFinite(declared) && declared > VOICE_MAX_UPLOAD_BYTES) return tooLarge();+ const body = await request.arrayBuffer();+ if (body.byteLength > VOICE_MAX_UPLOAD_BYTES) return tooLarge();+ const started = this.now();+ let response: Response;+ try {+ response = await this.broker.transcribe(body, contentType, request.signal);+ } catch (error) {+ if (request.signal.aborted) throw error;+ this.options.log?.("warn", "omnirush.ai voice transcription unreachable", { bytes: body.byteLength });+ return Response.json(+ { error: { code: "transcription_unreachable", message: "The transcription service could not be reached." } },+ { status: 503, headers: { "retry-after": "1" } },+ );+ }+ const text = await response.text();+ const code = errorCodeOf(text);+ if (code === "voice_unavailable" || code === "voice_disabled" || (response.status === 404 && !code)) {+ this.cached = { state: { available: false, reason: "voice_unavailable" }, until: this.now() + UNAVAILABLE_TTL_MS };+ } else if (response.ok && this.cached?.state.available !== true) {+ this.cached = { state: { ...this.cached?.state, available: true, reason: null }, until: this.now() + STATUS_TTL_MS };+ }+ // Sizes, status and latency only: never the audio, never the text.+ this.options.log?.(response.ok ? "info" : "warn", "omnirush.ai voice segment transcribed", {+ status: response.status,+ bytes: body.byteLength,+ ms: this.now() - started,+ ...(code ? { code } : {}),+ });+ const headers = new Headers({ "content-type": response.headers.get("content-type") ?? "application/json" });+ const retryAfter = response.headers.get("retry-after");+ if (retryAfter) headers.set("retry-after", retryAfter);+ // A 404 from an older backend means the route does not exist yet.+ if (response.status === 404 && !code) {+ return Response.json({ error: { code: "voice_unavailable", message: "Voice input is not available on this account yet." } }, { status: 503 });+ }+ return new Response(text, { status: response.status, headers });+ }+}++function tooLarge(): Response {+ return Response.json({ error: { code: "audio_too_large", message: "That recording is too long to transcribe." } }, { status: 413 });+}++function errorCodeOf(text: string): string | null {+ let body: unknown;+ try {+ body = JSON.parse(text);+ } catch {+ return null;+ }+ if (!isRecord(body)) return null;+ for (const value of [body.detail, body.error, body.code]) {+ if (typeof value === "string" && value.trim()) return value.trim();+ if (isRecord(value) && typeof value.code === "string" && value.code.trim()) return value.code.trim();+ }+ return null;+}++function gitLine(directory: string, args: string[]): Promise<string | null> {+ return new Promise((resolve) => {+ execFile(+ "git",+ ["-C", directory, ...args],+ { timeout: 1_500, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" } },+ (error, stdout) => resolve(error ? null : String(stdout).trim() || null),+ );+ });+}++/** The repository name and branch of a folder, for the transcription hint. Best effort, bounded. */+export async function voiceProjectContext(directory: string | null | undefined): Promise<{ repo: string | null; branch: string | null }> {+ if (!directory) return { repo: null, branch: null };+ const [top, branch] = await Promise.all([+ gitLine(directory, ["rev-parse", "--show-toplevel"]),+ gitLine(directory, ["symbolic-ref", "--short", "-q", "HEAD"]),+ ]);+ const folder = path.basename(path.resolve(directory));+ return { repo: top ? path.basename(top) : folder || null, branch: top ? branch : null };+}diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 10991e71..0b760f05 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -181,6 +181,7 @@ import { startCaptureService, type CaptureService } from "./capture-client.js";import { buildOpencodeProxyUrl, engineTarget } from "./collector-observer.js";import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";import { startOmniRushModelCatalogSync } from "./omnirush-model-catalog-sync.js";+import { OmniRushVoiceService, voiceProjectContext } from "./omnirush-voice.js";import { PROJECT_ARCHIVE_BASE_IDLE_MS, PROJECT_ARCHIVE_BASE_MAX_DEFER_MS, projectArchiveSettings } from "./project-archive.js";import type { ArchiveApiRequestInit } from "./session-archive/upload.js";import { runtimeStorageDir } from "./runtime-db.js";@@ -202,6 +203,8 @@ const agentDiagnosticsLastRunByServer = new WeakMap<ServerConfig, Map<string, nuconst agentDiagnosticsInFlightByServer = new WeakMap<ServerConfig, Set<string>>();const commandAdmissionsByServer = new WeakMap<ServerConfig, Map<string, { fingerprint: string; admittedAt: number }>>();const captureServicesByServer = new WeakMap<ServerConfig, CaptureService>();+/** Voice dictation's broker hop (omnirush-voice.ts), per server. */+const voiceServicesByServer = new WeakMap<ServerConfig, OmniRushVoiceService>();/** Recent gateway fallbacks per sub-agent session, for the swarm plugin's task-result note. */const subagentGatewayFallbacks = new WeakMap<ServerConfig, Map<string, Array<Record<string, unknown>>>>();@@ -927,6 +930,9 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {});},});+ voiceServicesByServer.set(config, new OmniRushVoiceService(gatewayBroker, {+ log: (level, message, attributes) => logger.log(level, message, attributes),+ }));// Under the desktop the embedding host passes the Electron app version// through ServerConfig; a standalone server reports its own version.const appVersion = config.appVersion?.trim()@@ -3613,6 +3619,26 @@ function createRoutes(});});+ // Voice dictation (omnirush-voice.ts): whether the account may use it, and+ // one speech segment at a time forwarded to omnirush.ai. Audio is never+ // stored, logged or captured; only the text the user sends is a prompt.+ addRoute(routes, "GET", "/omnirush/voice/status", "client", async (ctx) => {+ const voice = voiceServicesByServer.get(config);+ const workspaceId = ctx.url.searchParams.get("workspace")?.trim();+ const workspace = workspaceId ? config.workspaces.find((entry) => entry.id === workspaceId) : undefined;+ const [availability, project] = await Promise.all([+ voice ? voice.availability() : Promise.resolve({ available: false, reason: "voice_unavailable" }),+ workspace && workspace.workspaceType !== "remote" ? voiceProjectContext(workspace.path) : Promise.resolve({ repo: null, branch: null }),+ ]);+ return jsonResponse({ signedIn: voice?.signedIn ?? false, ...availability, ...project });+ });++ addRoute(routes, "POST", "/omnirush/voice/transcribe", "client", async (ctx) => {+ const voice = voiceServicesByServer.get(config);+ if (!voice) throw new ApiError(503, "voice_unavailable", "Voice input is not available.");+ return voice.transcribe(ctx.request);+ });+addRoute(routes, "GET", "/managed-policy", "client", async () =>jsonResponse({ policy: await managedDesktopPolicy(config).current() }));addRoute(routes, "POST", "/managed-policy/evaluate", "policy", async (ctx) => {