Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(speech): add host transcribe and synthesize capability

vastsa9948d078d9ed
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 36c9085e4..564642188 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -684,6 +684,7 @@ const {
browserHost,
browserPane,
announceTurnEnded,
+ speech,
} = pluginServices;
const providerCatalogRuntime = createProviderCatalogRuntime({
@@ -1269,6 +1270,7 @@ function registerIpc() {
persistenceOutbox,
logger,
plugins,
+ speech,
sessionCapabilityContext,
enrichSession,
acquireSessionOperation,
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index b5ddbba20..99fd44992 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -24,6 +24,7 @@ import { fetchSkillMarketDocument, searchSkillMarket } from "../skill-market-cat
import { registerWindowIpc } from "./window-ipc";
import { createComposerTemplateLoader, registerWorkspaceIpc } from "./workspace-ipc";
import { registerComposerIpc } from "./composer-ipc";
+import { registerSpeechIpc } from "./speech-ipc";
import type { IpcRegistrar } from "./types";
export type RegisterIpcDependencies = {
@@ -71,6 +72,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
persistenceOutbox,
logger,
plugins,
+ speech,
sessionCapabilityContext,
enrichSession,
acquireSessionOperation,
@@ -381,6 +383,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getPluginPanelTheme,
});
+ registerSpeechIpc({ registrar, speech });
registerMarketIpc({
registrar,
diff --git a/apps/desktop/electron/main/ipc/speech-ipc.ts b/apps/desktop/electron/main/ipc/speech-ipc.ts
new file mode 100644
index 000000000..b101a9d00
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/speech-ipc.ts
@@ -0,0 +1,30 @@
+import { IPC } from "@pi-desktop/shared";
+import type { SpeechService } from "../services/speech-service";
+import type { IpcRegistrar } from "./types";
+
+export function registerSpeechIpc({
+ registrar,
+ speech,
+}: {
+ registrar: IpcRegistrar;
+ speech: SpeechService;
+}): void {
+ const { handle } = registrar;
+ handle(IPC.invoke.speechGetStatus, () => speech.status());
+ handle(IPC.invoke.speechTranscribe, (input: Record<string, unknown> = {}) =>
+ speech.transcribe({
+ sessionId: typeof input.sessionId === "string" ? input.sessionId : null,
+ path: String(input.path ?? ""),
+ ...(typeof input.mimeType === "string" ? { mimeType: input.mimeType } : {}),
+ ...(typeof input.language === "string" ? { language: input.language } : {}),
+ }),
+ );
+ handle(IPC.invoke.speechSynthesize, (input: Record<string, unknown> = {}) =>
+ speech.synthesize({
+ sessionId: typeof input.sessionId === "string" ? input.sessionId : null,
+ text: String(input.text ?? ""),
+ ...(typeof input.voice === "string" ? { voice: input.voice } : {}),
+ ...(typeof input.format === "string" ? { format: input.format } : {}),
+ }),
+ );
+}
diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs
index 4f54be573..ad624a98b 100644
--- a/apps/desktop/electron/main/plugin-host-process.mjs
+++ b/apps/desktop/electron/main/plugin-host-process.mjs
@@ -150,6 +150,7 @@ function normalizeBytes(value) {
// the broker only ever holds the descriptor plus a proxy back into this process.
const commands = new Map();
const tools = new Map();
+const speechHandles = new Map();
// Resident services declared in the manifest. The broker decides when they run;
// this map only holds the callables and whether they are currently up.
const services = new Map();
@@ -207,6 +208,35 @@ function buildApi() {
await call("commands.unregister", [id]);
},
},
+ speech: {
+ registerAdapter: async (adapter) => {
+ if (!adapter || typeof adapter.protocol !== "string" || !adapter.protocol.trim()) {
+ throw new Error("speech protocol is required");
+ }
+ if (typeof adapter.handle !== "function") {
+ throw new Error("speech handle must be a function");
+ }
+ const protocol = adapter.protocol.trim();
+ const roles = Array.isArray(adapter.roles) ? adapter.roles : [];
+ speechHandles.set(protocol, adapter.handle);
+ try {
+ await call("speech.registerAdapter", [
+ {
+ protocol,
+ label: adapter.label,
+ roles,
+ },
+ ]);
+ } catch (error) {
+ speechHandles.delete(protocol);
+ throw error;
+ }
+ },
+ unregisterAdapter: async (protocol) => {
+ speechHandles.delete(String(protocol ?? ""));
+ await call("speech.unregisterAdapter", [protocol]);
+ },
+ },
ui: {
openPanel: (options) => call("ui.openPanel", [options]),
closePanel: () => call("ui.closePanel"),
@@ -483,6 +513,15 @@ async function handleParentCall(method, payload, invocationId) {
await run();
return { ok: true };
}
+ case "speech.handle": {
+ const handle = speechHandles.get(String(payload?.protocol ?? ""));
+ if (!handle) {
+ const error = new Error(`speech adapter not registered: ${payload?.protocol}`);
+ error.code = "NOT_FOUND";
+ throw error;
+ }
+ return handle(payload ?? {});
+ }
case "tool.execute": {
if (typeof invocationId !== "string" || !invocationId || invocations.has(invocationId)) {
throw toolAbortedError("A unique host tool invocation ID is required");
@@ -543,6 +582,7 @@ async function handleParentCall(method, payload, invocationId) {
}
commands.clear();
tools.clear();
+ speechHandles.clear();
services.clear();
busHandlers.clear();
eventListeners.clear();
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index ecb806638..cbfbb636c 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -70,6 +70,7 @@ import {
type PluginServiceStatus,
type PluginSettingDefinition,
type PluginWorkspaceInfo,
+ BUILTIN_SPEECH_PROTOCOL_IDS,
} from "@pi-desktop/shared";
import {
previewFile,
@@ -1111,9 +1112,65 @@ const spawnUtilityProcess: PluginProcessSpawner = async ({ pluginId, entry }) =>
};
};
+const SPEECH_HTTP_PARSE = new Set([
+ "bytes",
+ "json-text",
+ "json-path",
+ "openai-transcription",
+ "openai-chat-audio",
+]);
+
+function parseSpeechAdapterReply(value: unknown): {
+ kind: "text" | "audio" | "http";
+ text?: string;
+ mimeType?: string;
+ data?: string;
+ call?: Record<string, unknown>;
+} {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ throw apiError("INVALID_ARGUMENT", "speech adapter reply is invalid");
+ }
+ const record = value as Record<string, unknown>;
+ if (record.kind === "text") {
+ const text = typeof record.text === "string" ? record.text.trim() : "";
+ if (!text) throw apiError("PROVIDER_ERROR", "speech adapter returned empty text");
+ return { kind: "text", text };
+ }
+ if (record.kind === "audio") {
+ const data = typeof record.data === "string" ? record.data.trim() : "";
+ const mimeType =
+ typeof record.mimeType === "string" && record.mimeType.trim()
+ ? record.mimeType.trim()
+ : "application/octet-stream";
+ if (!data) throw apiError("PROVIDER_ERROR", "speech adapter returned empty audio");
+ return { kind: "audio", mimeType, data };
+ }
+ if (record.kind === "http") {
+ const call = record.call;
+ if (!call || typeof call !== "object" || Array.isArray(call)) {
+ throw apiError("INVALID_ARGUMENT", "speech adapter http call is invalid");
+ }
+ const spec = call as Record<string, unknown>;
+ if (typeof spec.url !== "string" || !spec.url.trim()) {
+ throw apiError("INVALID_ARGUMENT", "speech adapter http call is invalid");
+ }
+ if (typeof spec.parse !== "string" || !SPEECH_HTTP_PARSE.has(spec.parse)) {
+ throw apiError("INVALID_ARGUMENT", "speech adapter http parse is invalid");
+ }
+ return { kind: "http", call: spec };
+ }
+ throw apiError("INVALID_ARGUMENT", "speech adapter reply kind is invalid");
+}
+
export class PluginRuntime {
private commands = new Map<string, RegisteredCommand>();
private tools = new Map<string, RegisteredPluginTool>();
+ private speechAdapters = new Map<string, {
+ protocol: string;
+ label: string;
+ roles: Array<"transcribe" | "synthesize">;
+ pluginId: string;
+ }>();
private skills = new Map<string, RegisteredPluginSkill>();
private agentExtensions = new Map<string, RegisteredAgentExtension>();
private themes = new Map<string, RegisteredPluginTheme>();
@@ -1217,6 +1274,44 @@ export class PluginRuntime {
return [...this.tools.values()];
}
+ getSpeechAdapter(protocol: string) {
+ return this.speechAdapters.get(protocol);
+ }
+
+ listSpeechAdapters() {
+ return [...this.speechAdapters.values()].map((entry) => ({
+ id: entry.protocol,
+ label: entry.label,
+ roles: [...entry.roles],
+ source: "plugin" as const,
+ pluginId: entry.pluginId,
+ }));
+ }
+
+ async runSpeechAdapter(
+ job: { binding: { protocol: string } } & Record<string, unknown>,
+ payload: Record<string, unknown>,
+ ) {
+ const adapter = this.speechAdapters.get(String(job.binding.protocol));
+ if (!adapter) {
+ throw apiError("SPEECH_PROTOCOL_UNSUPPORTED", `unknown speech protocol: ${job.binding.protocol}`);
+ }
+ const loaded = this.loaded.get(adapter.pluginId);
+ if (!loaded?.child || loaded.disposing) {
+ throw apiError("NOT_FOUND", `plugin not loaded: ${adapter.pluginId}`);
+ }
+ const reply = await this.sendToChild(
+ loaded,
+ {
+ t: "call",
+ method: "speech.handle",
+ payload: { protocol: adapter.protocol, ...payload, role: (job as { role?: string }).role },
+ },
+ 60_000,
+ );
+ return parseSpeechAdapterReply(reply);
+ }
+
/** ExtensionAPI modules from loaded plugins holding `agent.extension`. */
getAgentExtensions(): RegisteredAgentExtension[] {
return [...this.agentExtensions.values()].sort((a, b) => a.id.localeCompare(b.id));
@@ -2354,6 +2449,51 @@ export class PluginRuntime {
this.tools.delete(pluginToolName(pluginId, String(args[0] ?? "")));
return { ok: true };
}
+ case "speech.registerAdapter": {
+ this.assertPermission(loaded, "speech.adapter.register");
+ const descriptor = (args[0] ?? {}) as {
+ protocol?: string;
+ label?: string;
+ roles?: unknown;
+ };
+ const protocol = String(descriptor.protocol ?? "").trim();
+ if (!/^[a-z][a-z0-9._-]{0,63}$/.test(protocol)) {
+ throw apiError("INVALID_ARGUMENT", "speech protocol is invalid");
+ }
+ if ((BUILTIN_SPEECH_PROTOCOL_IDS as readonly string[]).includes(protocol)) {
+ throw apiError("CONFLICT", "speech protocol is reserved");
+ }
+ const existing = this.speechAdapters.get(protocol);
+ if (existing && existing.pluginId !== pluginId) {
+ throw apiError("CONFLICT", `speech protocol in use: ${protocol}`);
+ }
+ const roles = Array.isArray(descriptor.roles)
+ ? descriptor.roles.filter((role): role is "transcribe" | "synthesize" =>
+ role === "transcribe" || role === "synthesize",
+ )
+ : [];
+ if (roles.length === 0) throw apiError("INVALID_ARGUMENT", "speech roles are required");
+ this.speechAdapters.set(protocol, {
+ protocol,
+ label: String(descriptor.label ?? protocol),
+ roles: [...new Set(roles)],
+ pluginId,
+ });
+ this.services.audit?.({
+ pluginId,
+ api: "speech.registerAdapter",
+ ok: true,
+ ts: Date.now(),
+ protocol,
+ });
+ return { ok: true };
+ }
+ case "speech.unregisterAdapter": {
+ const protocol = String(args[0] ?? "").trim();
+ const existing = this.speechAdapters.get(protocol);
+ if (existing?.pluginId === pluginId) this.speechAdapters.delete(protocol);
+ return { ok: true };
+ }
case "models.list": {
this.assertPermission(loaded, "models.list");
const models = (await this.services.listModels?.()) ?? [];
@@ -2751,6 +2891,9 @@ export class PluginRuntime {
for (const [name, tool] of this.tools) {
if (tool.pluginId === pluginId) this.tools.delete(name);
}
+ for (const [protocol, adapter] of this.speechAdapters) {
+ if (adapter.pluginId === pluginId) this.speechAdapters.delete(protocol);
+ }
for (const [id, skill] of this.skills) {
if (skill.pluginId === pluginId) this.skills.delete(id);
}
diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.ts
index 3d9818cfa..6d3c37c5b 100644
--- a/apps/desktop/electron/main/runtime/provider-catalog.ts
+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts
@@ -6,6 +6,7 @@ import {
modelIdsMatch,
resolveBindingContextWindow,
validateNetworkProxy,
+ validateSpeechSettings,
type CommandShellId,
type ModelBinding,
type ThinkingLevel,
@@ -210,6 +211,11 @@ export function createProviderCatalogRuntime({
}
value.networkProxy = proxy.value;
}
+ if (Object.prototype.hasOwnProperty.call(value, "speech")) {
+ (value as T & { speech?: unknown }).speech = validateSpeechSettings(
+ (value as { speech?: unknown }).speech,
+ );
+ }
return settings;
};
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index fa752a081..764f752ba 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -32,6 +32,7 @@ import { createFsConsentService } from "../plugin-fs-consent";
import { pluginWorkspaceInfo } from "../workspace-roots";
import { createDesktopConsentService } from "../plugin-desktop-consent";
import { PluginRuntime } from "../plugin-runtime";
+import { createSpeechService } from "./speech-service";
import { PluginShortcutRegistry } from "../plugin-shortcut-registry";
import { PluginWebSocketRegistry } from "../plugin-websocket";
import { hostGlobalShortcutBindings } from "../bootstrap/launcher";
@@ -592,6 +593,12 @@ export function createPluginServices({
if (pluginId === BROWSER_PLUGIN_ID) browserHost.disposeGuest();
},
});
+ const speech = createSpeechService({
+ dataDir,
+ getHost,
+ plugins,
+ logger,
+ });
return {
plugins,
userMcp,
@@ -604,5 +611,6 @@ export function createPluginServices({
pluginSettingsViews,
browserHost,
browserPane,
+ speech,
};
}
diff --git a/apps/desktop/electron/main/services/speech-service.ts b/apps/desktop/electron/main/services/speech-service.ts
new file mode 100644
index 000000000..c32bc189e
--- /dev/null
+++ b/apps/desktop/electron/main/services/speech-service.ts
@@ -0,0 +1,272 @@
+import { randomUUID } from "node:crypto";
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { basename, extname, isAbsolute, join, relative, resolve } from "node:path";
+import {
+ ErrorCodes,
+ MAX_SPEECH_TTS_DATA_URL_BYTES,
+ assertSpeechInputSize,
+ builtinSpeechProtocols,
+ type AppSettings,
+ type SpeechBinding,
+ type SpeechProtocolInfo,
+ type SpeechRole,
+ type SpeechStatus,
+ type SpeechSynthesizeResult,
+ type SpeechTranscribeResult,
+} from "@pi-desktop/shared";
+import {
+ assertSameOrigin,
+ executeSpeechHttp,
+ runBuiltinSpeech,
+ type SpeechEndpoint,
+ type SpeechHttpCall,
+ type SpeechHttpResult,
+ type SpeechJob,
+} from "@pi-desktop/agent-runtime";
+import type { HostProcess } from "../host-process";
+import type { Logger } from "../logger";
+import type { PluginRuntime } from "../plugin-runtime";
+
+const AUDIO_EXT_MIME: Record<string, string> = {
+ ".wav": "audio/wav",
+ ".mp3": "audio/mpeg",
+ ".m4a": "audio/mp4",
+ ".ogg": "audio/ogg",
+ ".flac": "audio/flac",
+ ".webm": "audio/webm",
+};
+
+function fail(code: string, message: string): never {
+ throw Object.assign(new Error(message), { errorCode: code });
+}
+
+function mimeFor(path: string, fallback?: string): string {
+ return fallback || AUDIO_EXT_MIME[extname(path).toLowerCase()] || "application/octet-stream";
+}
+
+function extensionFor(mimeType: string, format?: string): string {
+ if (format && /^\w+$/.test(format)) return format;
+ if (mimeType.includes("wav")) return "wav";
+ if (mimeType.includes("mpeg") || mimeType.includes("mp3")) return "mp3";
+ if (mimeType.includes("ogg")) return "ogg";
+ return "wav";
+}
+
+export type SpeechService = {
+ status(): Promise<SpeechStatus>;
+ transcribe(input: {
+ sessionId?: string | null;
+ path: string;
+ mimeType?: string;
+ language?: string;
+ }): Promise<SpeechTranscribeResult>;
+ synthesize(input: {
+ sessionId?: string | null;
+ text: string;
+ voice?: string;
+ format?: string;
+ }): Promise<SpeechSynthesizeResult>;
+};
+
+export function createSpeechService(options: {
+ dataDir: string;
+ getHost: () => HostProcess | null;
+ plugins: PluginRuntime;
+ logger: Pick<Logger, "app">;
+}): SpeechService {
+ const { dataDir, getHost, plugins, logger } = options;
+
+ const hostOrThrow = () => {
+ const host = getHost();
+ if (!host) fail(ErrorCodes.HOST_UNAVAILABLE, "host unavailable");
+ return host;
+ };
+
+ const loadSettings = async () => hostOrThrow().call<AppSettings>("settings.get");
+
+ const protocolCatalog = (): SpeechProtocolInfo[] => [
+ ...builtinSpeechProtocols(),
+ ...plugins.listSpeechAdapters(),
+ ];
+
+ const assertProtocol = (binding: SpeechBinding, role: SpeechRole) => {
+ const protocol = protocolCatalog().find((item) => item.id === binding.protocol);
+ if (!protocol || !protocol.roles.includes(role)) {
+ fail(ErrorCodes.SPEECH_PROTOCOL_UNSUPPORTED, `speech protocol does not support ${role}`);
+ }
+ };
+
+ const bindingFor = async (role: SpeechRole): Promise<SpeechBinding> => {
+ const speech = (await loadSettings()).speech;
+ const binding = speech?.[role];
+ if (!binding) fail(ErrorCodes.SPEECH_NOT_CONFIGURED, `${role} is not configured`);
+ assertProtocol(binding, role);
+ return binding;
+ };
+
+ const resolveEndpoint = async (binding: SpeechBinding): Promise<SpeechEndpoint & { providerId: string }> => {
+ const host = hostOrThrow();
+ const result = await host.call<{ provider?: { id: string; baseUrl?: string; enabled?: boolean } }>(
+ "providers.get",
+ { id: binding.providerId },
+ );
+ const provider = result.provider;
+ if (!provider || provider.enabled === false) fail(ErrorCodes.NOT_FOUND, "speech provider is missing");
+ const secret = await host.call<{ value?: string }>("providers.getSecret", { id: provider.id });
+ return {
+ providerId: provider.id,
+ baseUrl: (provider.baseUrl || "").replace(/\/+$/, ""),
+ apiKey: secret.value,
+ };
+ };
+
+ const scratchDir = async (sessionId?: string | null) => {
+ if (!sessionId?.trim()) fail(ErrorCodes.INVALID_ARGUMENT, "sessionId is required");
+ const host = hostOrThrow();
+ const result = await host.call<{ path: string }>("session.getScratchPath", {
+ sessionId: sessionId.trim(),
+ });
+ const scratchPath = resolve(String(result?.path ?? ""));
+ const scratchRoot = resolve(join(dataDir, "scratch"));
+ const rel = relative(scratchRoot, scratchPath);
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
+ fail(ErrorCodes.INVALID_ARGUMENT, "invalid session id");
+ }
+ await mkdir(scratchPath, { recursive: true });
+ return scratchPath;
+ };
+
+ const readAudio = async (path: string, scratchPath: string, mimeType?: string) => {
+ const full = resolve(path);
+ const rel = relative(scratchPath, full);
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
+ fail(ErrorCodes.INVALID_ARGUMENT, "speech input must be a session file");
+ }
+ const info = await stat(full).catch(() => null);
+ if (!info || !info.isFile()) fail(ErrorCodes.NOT_FOUND, "speech input file is missing");
+ assertSpeechInputSize(info.size);
+ return {
+ filename: basename(full),
+ mimeType: mimeFor(full, mimeType),
+ bytes: new Uint8Array(await readFile(full)),
+ };
+ };
+
+ const runJob = async (job: SpeechJob, endpoint: SpeechEndpoint): Promise<SpeechHttpResult> => {
+ const plugin = plugins.getSpeechAdapter(job.binding.protocol);
+ if (plugin) {
+ if (!plugin.roles.includes(job.role)) {
+ fail(ErrorCodes.SPEECH_PROTOCOL_UNSUPPORTED, `speech protocol does not support ${job.role}`);
+ }
+ const reply = await plugins.runSpeechAdapter(job, {
+ modelId: job.binding.modelId,
+ voice: job.binding.voice,
+ format: job.binding.format,
+ extra: job.binding.extra,
+ text: job.text,
+ language: job.role === "transcribe" ? (job as { language?: string }).language : undefined,
+ audio: job.audio
+ ? {
+ mimeType: job.audio.mimeType,
+ data: Buffer.from(job.audio.bytes).toString("base64"),
+ }
+ : undefined,
+ });
+ if (reply.kind === "text") return { kind: "text", text: reply.text ?? "" };
+ if (reply.kind === "audio") {
+ return {
+ kind: "audio",
+ mimeType: reply.mimeType || "application/octet-stream",
+ bytes: Buffer.from(reply.data ?? "", "base64"),
+ };
+ }
+ const call = reply.call as SpeechHttpCall | undefined;
+ if (!call?.url) fail(ErrorCodes.INVALID_ARGUMENT, "speech adapter http call is invalid");
+ if (!endpoint.baseUrl) fail(ErrorCodes.INVALID_ARGUMENT, "speech provider has no base URL");
+ assertSameOrigin(endpoint.baseUrl, call.url);
+ return executeSpeechHttp(call, {
+ apiKey: endpoint.apiKey,
+ audio: job.audio,
+ });
+ }
+ if (!endpoint.baseUrl) fail(ErrorCodes.INVALID_ARGUMENT, "speech provider has no base URL");
+ return runBuiltinSpeech(job, endpoint);
+ };
+
+ return {
+ async status() {
+ const settings = await loadSettings().catch(() => null);
+ const protocols = protocolCatalog();
+ const roleStatus = (role: SpeechRole) => {
+ const binding = settings?.speech?.[role];
+ if (!binding) return { configured: false, available: false };
+ const protocol = protocols.find((item) => item.id === binding.protocol);
+ return {
+ configured: true,
+ available: Boolean(protocol && protocol.roles.includes(role)),
+ providerId: binding.providerId,
+ modelId: binding.modelId,
+ protocol: binding.protocol,
+ };
+ };
+ return {
+ transcribe: roleStatus("transcribe"),
+ synthesize: roleStatus("synthesize"),
+ protocols,
+ };
+ },
+
+ async transcribe(input) {
+ const binding = await bindingFor("transcribe");
+ const endpoint = await resolveEndpoint(binding);
+ const dir = await scratchDir(input.sessionId);
+ const audio = await readAudio(String(input.path ?? ""), dir, input.mimeType);
+ const result = await runJob(
+ {
+ role: "transcribe",
+ binding,
+ language: input.language,
+ audio,
+ },
+ endpoint,
+ );
+ if (result.kind !== "text") fail(ErrorCodes.PROVIDER_ERROR, "speech adapter did not return text");
+ logger.app("provider", "info", "speech transcribed", {
+ data: { protocol: binding.protocol, providerId: binding.providerId },
+ });
+ return { text: result.text };
+ },
+
+ async synthesize(input) {
+ const text = String(input.text ?? "").trim();
+ if (!text) fail(ErrorCodes.INVALID_ARGUMENT, "speech text is required");
+ const binding = await bindingFor("synthesize");
+ const endpoint = await resolveEndpoint(binding);
+ const result = await runJob(
+ {
+ role: "synthesize",
+ binding: {
+ ...binding,
+ ...(input.voice ? { voice: input.voice } : {}),
+ ...(input.format ? { format: input.format } : {}),
+ },
+ text,
+ },
+ endpoint,
+ );
+ if (result.kind !== "audio") fail(ErrorCodes.PROVIDER_ERROR, "speech adapter did not return audio");
+ const dir = await scratchDir(input.sessionId);
+ const ext = extensionFor(result.mimeType, input.format || binding.format);
+ const path = join(dir, `speech-${randomUUID()}.${ext}`);
+ await writeFile(path, result.bytes);
+ const payload: SpeechSynthesizeResult = { path, mimeType: result.mimeType };
+ if (result.bytes.byteLength <= MAX_SPEECH_TTS_DATA_URL_BYTES) {
+ payload.dataUrl = `data:${result.mimeType};base64,${Buffer.from(result.bytes).toString("base64")}`;
+ }
+ logger.app("provider", "info", "speech synthesized", {
+ data: { protocol: binding.protocol, providerId: binding.providerId },
+ });
+ return payload;
+ },
+ };
+}
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index d98a63ca5..b84d93f62 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -56,6 +56,7 @@ import {
import { useComposerAttachments } from "../features/chat/composer/hooks/useComposerAttachments";
import { useComposerDraft } from "../features/chat/composer/hooks/useComposerDraft";
import { useComposerSubmit } from "../features/chat/composer/hooks/useComposerSubmit";
+import { useComposerSpeech } from "../features/chat/composer/hooks/useComposerSpeech";
import { ComposerInput } from "../features/chat/composer/ComposerInput";
import { useComposerModelMenu } from "../features/chat/composer/hooks/useComposerModelMenu";
import { ComposerToolbar } from "../features/chat/composer/ComposerToolbar";
@@ -436,7 +437,16 @@ export function Composer({
submit,
} = submitController;
-
+ const speech = useComposerSpeech({
+ activeSessionId,
+ value,
+ enhancementDraft,
+ activeFileReferences,
+ applyEditorDraft,
+ t,
+ showToast,
+ controlsBlocked,
+ });
const composerAc = useComposerAutocomplete({
value,
cursor,
@@ -607,6 +617,12 @@ export function Composer({
clearEnhancementError={clearEnhancementError}
runActive={runActive}
hasDraftContent={hasDraftContent}
+ transcribeEnabled={speech.transcribeEnabled}
+ speakEnabled={speech.speakEnabled}
+ transcribing={speech.transcribing}
+ speaking={speech.speaking}
+ transcribe={speech.transcribe}
+ speak={speech.speak}
abort={abort}
submit={submit}
/>
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index d2c899052..587e3b886 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -19,6 +19,8 @@ import {
IconSparkles,
IconStop,
IconUndo2,
+ IconMic,
+ IconAudio,
} from "../../../components/icons";
import { ModeIcon } from "./ComposerModeIcon";
import { ComposerModelPicker } from "./ComposerModelPicker";
@@ -62,6 +64,12 @@ export type ComposerToolbarProps = {
clearEnhancementError: () => void;
runActive: boolean;
hasDraftContent: boolean;
+ transcribeEnabled: boolean;
+ speakEnabled: boolean;
+ transcribing: boolean;
+ speaking: boolean;
+ transcribe: () => Promise<void>;
+ speak: () => Promise<void>;
abort: AppState["abort"];
submit: () => Promise<void>;
};
@@ -97,6 +105,12 @@ export function ComposerToolbar({
clearEnhancementError,
runActive,
hasDraftContent,
+ transcribeEnabled,
+ speakEnabled,
+ transcribing,
+ speaking,
+ transcribe,
+ speak,
abort,
submit,
}: ComposerToolbarProps) {
@@ -243,6 +257,28 @@ export function ComposerToolbar({
controlsBlocked={controlsBlocked}
onCloseOtherMenus={() => setPermissionOpen(false)}
/>
+ <TooltipButton
+ type="button"
+ className={`icon-btn icon-btn-square${transcribing ? " is-loading" : ""}`}
+ tooltip={t("chat.transcribe")}
+ ariaLabel={transcribing ? t("chat.transcribing") : t("chat.transcribe")}
+ aria-busy={transcribing}
+ disabled={!transcribeEnabled || transcribing || speaking}
+ onClick={() => void transcribe()}
+ >
+ {transcribing ? <span className="tool-spinner" aria-hidden="true" /> : <IconMic size={15} aria-hidden="true" />}
+ </TooltipButton>
+ <TooltipButton
+ type="button"
+ className={`icon-btn icon-btn-square${speaking ? " is-loading" : ""}`}
+ tooltip={t("chat.speak")}
+ ariaLabel={speaking ? t("chat.speaking") : t("chat.speak")}
+ aria-busy={speaking}
+ disabled={!speakEnabled || speaking || transcribing}
+ onClick={() => void speak()}
+ >
+ {speaking ? <span className="tool-spinner" aria-hidden="true" /> : <IconAudio size={15} aria-hidden="true" />}
+ </TooltipButton>
<TooltipButton
type="button"
className={`icon-btn icon-btn-square composer-enhance-btn${enhancingPrompt ? " is-loading" : ""}`}
diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.ts
index 28ba1bb2f..07eae1ae8 100644
--- a/apps/desktop/src/features/chat/composer/editor.ts
+++ b/apps/desktop/src/features/chat/composer/editor.ts
@@ -12,7 +12,7 @@ const CODE_FILE_PATTERN =
/\.(cjs|css|go|java|js|json|jsx|kt|mjs|php|py|rb|rs|sh|sql|svelte|swift|toml|ts|tsx|vue|ya?ml)$/i;
const ARCHIVE_FILE_PATTERN = /\.(7z|bz2|gz|jar|rar|tar|zip)$/i;
const SHEET_FILE_PATTERN = /\.(csv|ods|xls|xlsx)$/i;
-const AUDIO_FILE_PATTERN = /\.(flac|m4a|mp3|ogg|wav)$/i;
+const AUDIO_FILE_PATTERN = /\.(flac|m4a|mp3|ogg|wav|webm)$/i;
const VIDEO_FILE_PATTERN = /\.(avi|mkv|m4v|mov|mp4|webm)$/i;
/** Paste/scratch files keep absolute paths; `@` entries are workspace-relative. */
@@ -259,6 +259,11 @@ export function isEditableTextReference(reference: ComposerFileReference): boole
return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);
}
+export function isComposerAudioReference(reference: ComposerFileReference): boolean {
+ const mime = reference.mimeType?.toLowerCase() ?? "";
+ return mime.startsWith("audio/") || AUDIO_FILE_PATTERN.test(reference.name);
+}
+
/** Build the atomic inline chip element for one attachment reference. */
function buildChipElement(
reference: ComposerFileReference,
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSpeech.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSpeech.ts
new file mode 100644
index 000000000..2f3ad494f
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSpeech.ts
@@ -0,0 +1,115 @@
+import { useEffect, useRef, useState } from "react";
+import type { TFunction } from "i18next";
+import type { SpeechStatus } from "@pi-desktop/shared";
+import { stripInlineComposerFileReferenceTokens } from "@pi-desktop/shared";
+import { materializeDraftSession } from "../../../../stores/app-store";
+import { api } from "../../../../lib/api";
+import { isComposerAudioReference, type ComposerFileReference } from "../editor";
+
+type SpeechToast = (message: string, options?: { variant?: "error" | "info" }) => void;
+
+export function useComposerSpeech({
+ activeSessionId,
+ value,
+ enhancementDraft,
+ activeFileReferences,
+ applyEditorDraft,
+ t,
+ showToast,
+ controlsBlocked,
+}: {
+ activeSessionId: string | null | undefined;
+ value: string;
+ enhancementDraft: string;
+ activeFileReferences: ComposerFileReference[];
+ applyEditorDraft: (next: string, refs: ComposerFileReference[], cursor: number) => void;
+
+ t: TFunction;
+ showToast: SpeechToast;
+ controlsBlocked: boolean;
+}) {
+ const [status, setStatus] = useState<SpeechStatus | null>(null);
+ const [transcribing, setTranscribing] = useState(false);
+ const [speaking, setSpeaking] = useState(false);
+ const playbackRef = useRef<HTMLAudioElement | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ void api.speechStatus().then(
+ (next) => {
+ if (!cancelled) setStatus(next);
+ },
+ () => {
+ if (!cancelled) setStatus(null);
+ },
+ );
+ return () => {
+ cancelled = true;
+ playbackRef.current?.pause();
+ playbackRef.current = null;
+ };
+ }, []);
+
+ const audioAttachments = activeFileReferences.filter(isComposerAudioReference);
+ const transcribeEnabled = Boolean(status?.transcribe.available) && audioAttachments.length > 0 && !controlsBlocked;
+ const speakEnabled = Boolean(status?.synthesize.available) && Boolean(enhancementDraft.trim()) && !controlsBlocked;
+
+ const transcribe = async () => {
+ if (!transcribeEnabled || transcribing) return;
+ setTranscribing(true);
+ try {
+ const sessionId = activeSessionId ?? (await materializeDraftSession());
+ if (!sessionId) throw new Error("session unavailable");
+ const chunks: string[] = [];
+ for (const file of audioAttachments) {
+ const result = await api.speechTranscribe({
+ sessionId,
+ path: file.path,
+ mimeType: file.mimeType,
+ });
+ if (result.text.trim()) chunks.push(result.text.trim());
+ }
+ if (!chunks.length) return;
+ const insertion = chunks.join("\n");
+ const prefix = value.trim() ? `${value.replace(/\s+$/, "")}\n` : "";
+ const next = `${prefix}${insertion}`;
+ applyEditorDraft(next, activeFileReferences, next.length);
+ } catch (error) {
+ showToast(error instanceof Error ? error.message : t("chat.transcribeFailed"), { variant: "error" });
+ } finally {
+ setTranscribing(false);
+ }
+ };
+
+ const speak = async () => {
+ if (!speakEnabled || speaking) return;
+ const text = stripInlineComposerFileReferenceTokens(enhancementDraft, activeFileReferences).trim();
+ if (!text) return;
+ setSpeaking(true);
+ try {
+ const sessionId = activeSessionId ?? (await materializeDraftSession());
+ if (!sessionId) throw new Error("session unavailable");
+ const result = await api.speechSynthesize({ sessionId, text });
+ if (result.dataUrl) {
+ const audio = new Audio(result.dataUrl);
+ playbackRef.current = audio;
+ await audio.play();
+ } else {
+ showToast(t("chat.speakSaved", { path: result.path }), { variant: "info" });
+ }
+ } catch (error) {
+ showToast(error instanceof Error ? error.message : t("chat.speakFailed"), { variant: "error" });
+ } finally {
+ setSpeaking(false);
+ }
+ };
+
+ return {
+ transcribeEnabled,
+ speakEnabled,
+ transcribing,
+ speaking,
+ transcribe,
+ speak,
+ };
+}
diff --git a/apps/desktop/src/features/plugins/model.ts b/apps/desktop/src/features/plugins/model.ts
index 37a39e5eb..55af2fb89 100644
--- a/apps/desktop/src/features/plugins/model.ts
+++ b/apps/desktop/src/features/plugins/model.ts
@@ -64,6 +64,7 @@ export const PERMISSION_RISK: Record<string, RiskTier> = {
// live audio stream sit at the top tier with the other outbound paths.
"net.websocket": "high",
"audio.capture.background": "high",
+ "speech.adapter.register": "high",
"audio.playback.background": "medium",
"keyboard.globalShortcut": "medium",
"bus.publish": "medium",
diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsx
index a7af233ad..5b85d54c7 100644
--- a/apps/desktop/src/features/settings/SettingsPage.tsx
+++ b/apps/desktop/src/features/settings/SettingsPage.tsx
@@ -54,6 +54,7 @@ import {
ImportSection,
UpdatesRow,
} from "./agent-sections";
+import { VoiceSettingsCard } from "./voice-settings";
import { CloseBehaviorSection, DeveloperSection } from "./developer-sections";
import { PluginSettingsDestination } from "../../components/settings/PluginSettingsDestination";
@@ -368,6 +369,8 @@ export function SettingsPage() {
</SettingsRow>
</SettingsCard>
+ <VoiceSettingsCard settings={settings} saveSettings={saveSettings} />
+
<SettingsCard title={t("settings.defaultsTitle")}>
<SettingsRow title={t("settings.mode")} description={t("settings.modeDesc")}>
<div
diff --git a/apps/desktop/src/features/settings/voice-settings.tsx b/apps/desktop/src/features/settings/voice-settings.tsx
new file mode 100644
index 000000000..83adacaa2
--- /dev/null
+++ b/apps/desktop/src/features/settings/voice-settings.tsx
@@ -0,0 +1,191 @@
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { AppSettings, SpeechBinding, SpeechRole, SpeechStatus } from "@pi-desktop/shared";
+import { useAppStore } from "../../stores/app-store";
+import { api } from "../../lib/api";
+import { Input } from "../../components/ui";
+import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";
+import { SettingsCard, SettingsRow } from "./primitives";
+
+const NONE = "";
+
+function presetFor(role: SpeechRole, haystack: string): Pick<SpeechBinding, "modelId" | "protocol" | "voice"> {
+ const key = haystack.toLowerCase();
+ if (role === "transcribe") {
+ if (key.includes("groq")) return { modelId: "whisper-large-v3", protocol: "openai_audio" };
+ if (key.includes("openai")) return { modelId: "whisper-1", protocol: "openai_audio" };
+ return { modelId: "whisper-1", protocol: "openai_audio" };
+ }
+ if (key.includes("xiaomi") || key.includes("mimo")) {
+ return { modelId: "mimo-v2.5-tts", protocol: "openai_chat_audio", voice: "alloy" };
+ }
+ if (key.includes("openai")) return { modelId: "tts-1", protocol: "openai_audio", voice: "alloy" };
+ return { modelId: "tts-1", protocol: "openai_audio", voice: "alloy" };
+}
+
+function SpeechRoleFields({
+ role,
+ settings,
+ status,
+ saveSettings,
+}: {
+ role: SpeechRole;
+ settings: AppSettings;
+ status: SpeechStatus | null;
+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;
+}) {
+ const { t } = useTranslation();
+ const providers = useAppStore((s) => s.providers);
+ const binding = settings.speech?.[role];
+ const [modelDraft, setModelDraft] = useState(binding?.modelId ?? "");
+ const [voiceDraft, setVoiceDraft] = useState(binding?.voice ?? "");
+
+ useEffect(() => {
+ setModelDraft(binding?.modelId ?? "");
+ setVoiceDraft(binding?.voice ?? "");
+ }, [binding?.modelId, binding?.voice]);
+
+ const protocolOptions = useMemo(() => {
+ const protocols = (status?.protocols ?? []).filter((item) => item.roles.includes(role));
+ return protocols.map((item) => ({ id: item.id, label: item.label }));
+ }, [role, status]);
+
+ const providerOptions = [
+ { id: NONE, label: t("settings.speechNone") },
+ ...providers.filter((provider) => provider.enabled !== false).map((provider) => ({
+ id: provider.id,
+ label: provider.name,
+ })),
+ ];
+
+ const persist = async (next: SpeechBinding | undefined) => {
+ const speech = { ...(settings.speech ?? {}) };
+ if (!next) delete speech[role];
+ else speech[role] = next;
+ await saveSettings({ speech: Object.keys(speech).length ? speech : undefined });
+ };
+
+ const onProvider = async (providerId: string) => {
+ if (!providerId) {
+ await persist(undefined);
+ return;
+ }
+ const provider = providers.find((item) => item.id === providerId);
+ const haystack = `${provider?.vendorKey ?? ""} ${provider?.id ?? ""} ${provider?.name ?? ""}`;
+ const preset = presetFor(role, haystack);
+ const protocol =
+ protocolOptions.some((item) => item.id === preset.protocol) ? preset.protocol : protocolOptions[0]?.id ?? preset.protocol;
+ await persist({
+ providerId,
+ modelId: preset.modelId,
+ protocol,
+ ...(preset.voice ? { voice: preset.voice } : {}),
+ });
+ };
+
+ const commitModel = async () => {
+ const modelId = modelDraft.trim();
+ if (!binding || !modelId || modelId === binding.modelId) return;
+ await persist({ ...binding, modelId });
+ };
+
+ const commitVoice = async () => {
+ if (role !== "synthesize" || !binding) return;
+ const voice = voiceDraft.trim();
+ if ((binding.voice ?? "") === voice) return;
+ const next = { ...binding };
+ if (voice) next.voice = voice;
+ else delete next.voice;
+ await persist(next);
+ };
+
+ return (
+ <SettingsRow
+ title={t(role === "transcribe" ? "settings.speechTranscribe" : "settings.speechSynthesize")}
+ description={t(role === "transcribe" ? "settings.speechTranscribeDesc" : "settings.speechSynthesizeDesc")}
+ >
+ <div className="settings-speech-fields">
+ <SettingsMenuSelect
+ className="settings-speech-select"
+ label={t("settings.speechProvider")}
+ value={binding?.providerId ?? NONE}
+ onChange={(id) => void onProvider(id)}
+ options={providerOptions}
+ />
+ {binding ? (
+ <>
+ <SettingsMenuSelect
+ className="settings-speech-select"
+ label={t("settings.speechProtocol")}
+ value={binding.protocol}
+ onChange={(protocol) => void persist({ ...binding, protocol })}
+ options={protocolOptions.length ? protocolOptions : [{ id: binding.protocol, label: binding.protocol }]}
+ />
+ <Input
+ aria-label={t("settings.speechModel")}
+ placeholder={t("settings.speechModelPlaceholder")}
+ value={modelDraft}
+ onChange={(event) => setModelDraft(event.target.value)}
+ onBlur={() => void commitModel()}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void commitModel();
+ }
+ }}
+ />
+ {role === "synthesize" ? (
+ <Input
+ aria-label={t("settings.speechVoice")}
+ placeholder={t("settings.speechVoicePlaceholder")}
+ value={voiceDraft}
+ onChange={(event) => setVoiceDraft(event.target.value)}
+ onBlur={() => void commitVoice()}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void commitVoice();
+ }
+ }}
+ />
+ ) : null}
+ </>
+ ) : null}
+ </div>
+ </SettingsRow>
+ );
+}
+
+export function VoiceSettingsCard({
+ settings,
+ saveSettings,
+}: {
+ settings: AppSettings;
+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;
+}) {
+ const { t } = useTranslation();
+ const [status, setStatus] = useState<SpeechStatus | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ void api.speechStatus().then(
+ (next) => {
+ if (!cancelled) setStatus(next);
+ },
+ () => {
+ if (!cancelled) setStatus(null);
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [settings.speech]);
+
+ return (
+ <SettingsCard title={t("settings.speechTitle")}>
+ <p className="settings-row-desc settings-speech-lead">{t("settings.speechDesc")}</p>
+ <SpeechRoleFields role="transcribe" settings={settings} status={status} saveSettings={saveSettings} />
+ <SpeechRoleFields role="synthesize" settings={settings} status={status} saveSettings={saveSettings} />
+ </SettingsCard>
+ );
+}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 2d6eacaf7..5372e3c85 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -12,6 +12,11 @@ import type {
AgentPromptResponse,
PromptEnhancementRequest,
PromptEnhancementResponse,
+ SpeechStatus,
+ SpeechSynthesizeRequest,
+ SpeechSynthesizeResult,
+ SpeechTranscribeRequest,
+ SpeechTranscribeResult,
SessionSummarizeTitleRequest,
SessionSummarizeTitleResponse,
AgentStopResponse,
@@ -111,6 +116,7 @@ import {
resolveFontScale,
normalizeChatContentMaxWidth,
validateNetworkProxy,
+ validateSpeechSettings,
} from "@pi-desktop/shared";
export type ImportSource = "claude-code" | "opencode" | "codex" | "pi";
@@ -279,6 +285,11 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {
}
value.networkProxy = proxy.value;
}
+ if (Object.prototype.hasOwnProperty.call(value, "speech")) {
+ (value as AppSettings).speech = validateSpeechSettings(
+ (value as { speech?: unknown }).speech,
+ );
+ }
return settings;
}
@@ -631,6 +642,11 @@ export const api = {
invoke<AgentPromptResponse>(IPC.invoke.agentPrompt, req),
enhancePrompt: (req: PromptEnhancementRequest) =>
invoke<PromptEnhancementResponse>(IPC.invoke.promptEnhance, req),
+ speechStatus: () => invoke<SpeechStatus>(IPC.invoke.speechGetStatus),
+ speechTranscribe: (req: SpeechTranscribeRequest) =>
+ invoke<{ text: string }>(IPC.invoke.speechTranscribe, req),
+ speechSynthesize: (req: SpeechSynthesizeRequest) =>
+ invoke<SpeechSynthesizeResult>(IPC.invoke.speechSynthesize, req),
compact: (req: AgentCompactRequest) =>
invoke<AgentCompactResponse>(IPC.invoke.agentCompact, req),
abort: (sessionId: string) =>
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index 3f821e97a..9ca4aeb3d 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -79,6 +79,9 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
"settings.permissionModeAcceptEdits",
"settings.permissionModeAuto",
"settings.defaultsTitle",
+ "settings.speechTitle",
+ "settings.speechTranscribe",
+ "settings.speechSynthesize",
"settings.mode",
"settings.commandShell",
"settings.linkOpenTarget",
diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.css
index 34c05bcea..4d8f196ce 100644
--- a/apps/desktop/src/styles/settings.css
+++ b/apps/desktop/src/styles/settings.css
@@ -388,6 +388,23 @@
justify-content: flex-end;
}
+.settings-row:has(.settings-speech-fields) .settings-row-control {
+ max-width: 280px;
+ align-items: stretch;
+}
+
+.settings-speech-fields {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 180px;
+ width: 100%;
+}
+
+.settings-speech-lead {
+ padding: 12px 16px 0;
+}
+
.settings-row-control .field-input {
width: 100%;
min-width: 140px;
diff --git a/apps/desktop/test/plugin-speech-adapter.test.mjs b/apps/desktop/test/plugin-speech-adapter.test.mjs
new file mode 100644
index 000000000..42024b6fc
--- /dev/null
+++ b/apps/desktop/test/plugin-speech-adapter.test.mjs
@@ -0,0 +1,209 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fork } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { register } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const hostProcessEntry = join(here, "..", "electron/main/plugin-host-process.mjs");
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+
+const dataDir = mkdtempSync(join(tmpdir(), "pi-speech-data-"));
+process.env.PI_DESKTOP_DATA_DIR = dataDir;
+test.after(() => rmSync(dataDir, { recursive: true, force: true }));
+
+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");
+
+const PLUGIN_ID = "com.example.speech";
+
+function forkPluginProcess({ entry }) {
+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
+ return {
+ postMessage: (message) => {
+ if (child.connected) child.send(message);
+ },
+ onMessage: (handler) => child.on("message", handler),
+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),
+ kill: () => child.kill(),
+ };
+}
+
+function writePlugin(t, { permissions, main }) {
+ const dir = mkdtempSync(join(tmpdir(), "pi-speech-plugin-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ writeFileSync(
+ join(dir, "manifest.json"),
+ JSON.stringify({
+ schemaVersion: 1,
+ id: PLUGIN_ID,
+ name: "Speech Plugin",
+ version: "0.0.1",
+ main: "main.js",
+ permissions,
+ }),
+ "utf8",
+ );
+ writeFileSync(join(dir, "main.js"), main, "utf8");
+ return dir;
+}
+
+function createRuntime(t) {
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ return runtime;
+}
+
+const REGISTER_MAIN = `
+ module.exports = {
+ async onLoad() {
+ await pi.speech.registerAdapter({
+ protocol: "example.tts",
+ label: "Example TTS",
+ roles: ["synthesize"],
+ handle: async (input) => {
+ if (input.role !== "synthesize") throw Object.assign(new Error("no"), { code: "SPEECH_PROTOCOL_UNSUPPORTED" });
+ if (input.extra?.mode === "http") {
+ return { kind: "http", call: { url: input.extra.url, parse: input.extra.parse || "bytes" } };
+ }
+ return { kind: "audio", mimeType: "audio/wav", data: Buffer.from("RIFF").toString("base64") };
+ },
+ });
+ },
+ async onPanelInvoke(channel) {
+ if (channel === "reserved") {
+ try {
+ await pi.speech.registerAdapter({
+ protocol: "openai_audio",
+ label: "Nope",
+ roles: ["transcribe"],
+ handle: async () => ({ kind: "text", text: "x" }),
+ });
+ return { ok: true };
+ } catch (error) {
+ return { ok: false, code: error.code, message: String(error.message) };
+ }
+ }
+ return { ok: true };
+ },
+ };
+`;
+
+test("a plugin can register a speech adapter and handle synthesis", async (t) => {
+ const runtime = createRuntime(t);
+ await runtime.loadFromPath(writePlugin(t, { permissions: ["speech.adapter.register"], main: REGISTER_MAIN }));
+ const listed = runtime.listSpeechAdapters();
+ assert.equal(listed.length, 1);
+ assert.equal(listed[0].id, "example.tts");
+ assert.deepEqual(listed[0].roles, ["synthesize"]);
+ const reply = await runtime.runSpeechAdapter(
+ { role: "synthesize", binding: { protocol: "example.tts" } },
+ { modelId: "demo" },
+ );
+ assert.equal(reply.kind, "audio");
+ assert.equal(Buffer.from(reply.data, "base64").toString(), "RIFF");
+});
+
+test("built-in protocol ids stay reserved", async (t) => {
+ const runtime = createRuntime(t);
+ await runtime.loadFromPath(writePlugin(t, { permissions: ["speech.adapter.register"], main: REGISTER_MAIN }));
+ const answer = await runtime.invokePanelBridge(PLUGIN_ID, "reserved");
+ assert.equal(answer.ok, false);
+ assert.equal(answer.code, "CONFLICT");
+});
+
+test("unload drops the adapter", async (t) => {
+ const runtime = createRuntime(t);
+ await runtime.loadFromPath(writePlugin(t, { permissions: ["speech.adapter.register"], main: REGISTER_MAIN }));
+ await runtime.unload(PLUGIN_ID);
+ assert.equal(runtime.listSpeechAdapters().length, 0);
+});
+
+test("http plans require a parseable call", async (t) => {
+ const runtime = createRuntime(t);
+ await runtime.loadFromPath(writePlugin(t, { permissions: ["speech.adapter.register"], main: REGISTER_MAIN }));
+ const reply = await runtime.runSpeechAdapter(
+ { role: "synthesize", binding: { protocol: "example.tts" } },
+ { modelId: "demo", extra: { mode: "http", url: "https://api.example.com/v1/audio/speech" } },
+ );
+ assert.equal(reply.kind, "http");
+ assert.equal(reply.call.url, "https://api.example.com/v1/audio/speech");
+ await assert.rejects(
+ () =>
+ runtime.runSpeechAdapter(
+ { role: "synthesize", binding: { protocol: "example.tts" } },
+ { modelId: "demo", extra: { mode: "http", url: "https://evil.test/x", parse: "nope" } },
+ ),
+ (error) => error.code === "INVALID_ARGUMENT",
+ );
+});
+
+test("http plans must stay on the provider origin", async (t) => {
+ const runtime = createRuntime(t);
+ await runtime.loadFromPath(writePlugin(t, { permissions: ["speech.adapter.register"], main: REGISTER_MAIN }));
+ const { createSpeechService } = await import("../electron/main/services/speech-service.ts");
+ const svcDataDir = mkdtempSync(join(tmpdir(), "pi-speech-origin-"));
+ t.after(() => rmSync(svcDataDir, { recursive: true, force: true }));
+ const scratch = join(svcDataDir, "scratch", "sess");
+ let extraUrl = "https://api.example.com/v1/audio/speech";
+ const host = {
+ call: async (method) => {
+ if (method === "settings.get") {
+ return {
+ speech: {
+ synthesize: {
+ providerId: "p",
+ modelId: "demo",
+ protocol: "example.tts",
+ extra: { mode: "http", url: extraUrl },
+ },
+ },
+ };
+ }
+ if (method === "providers.get") {
+ return { provider: { id: "p", baseUrl: "https://api.example.com/v1", enabled: true } };
+ }
+ if (method === "providers.getSecret") return { value: "sk" };
+ if (method === "session.getScratchPath") return { path: scratch };
+ throw new Error(method);
+ },
+ };
+ const speech = createSpeechService({
+ dataDir: svcDataDir,
+ getHost: () => host,
+ plugins: runtime,
+ logger: { app() {} },
+ });
+
+ extraUrl = "https://evil.test/steal";
+ await assert.rejects(
+ () => speech.synthesize({ sessionId: "sess", text: "hi" }),
+ (error) => error.errorCode === "INVALID_ARGUMENT",
+ );
+
+ extraUrl = "https://api.example.com/v1/audio/speech";
+ const originalFetch = globalThis.fetch;
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+ let fetched = "";
+ globalThis.fetch = async (url) => {
+ fetched = String(url);
+ return new Response(Buffer.from("RIFF"), {
+ status: 200,
+ headers: { "content-type": "audio/wav" },
+ });
+ };
+ const result = await speech.synthesize({ sessionId: "sess", text: "hi" });
+ assert.equal(fetched, "https://api.example.com/v1/audio/speech");
+ assert.equal(result.mimeType, "audio/wav");
+ assert.match(result.path, /speech-/);
+});
+
diff --git a/apps/desktop/test/speech-capability.test.mjs b/apps/desktop/test/speech-capability.test.mjs
new file mode 100644
index 000000000..4537dea0d
--- /dev/null
+++ b/apps/desktop/test/speech-capability.test.mjs
@@ -0,0 +1,113 @@
+import { readComposerSource } from "./helpers/source-contracts.mjs";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { register } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import test from "node:test";
+import { readFile } from "node:fs/promises";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+
+const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
+
+test("speech IPC is on the typed whitelist and renderer API", async () => {
+ const [protocol, api, registerSrc] = await Promise.all([
+ read("../../../packages/shared/src/protocol.ts"),
+ read("../src/lib/api.ts"),
+ read("../electron/main/ipc/register.ts"),
+ ]);
+ assert.match(protocol, /speechTranscribe: "pi-desktop\/speech\/transcribe"/);
+ assert.match(protocol, /speechSynthesize: "pi-desktop\/speech\/synthesize"/);
+ assert.match(protocol, /speechGetStatus: "pi-desktop\/speech\/getStatus"/);
+ assert.match(api, /IPC\.invoke\.speechGetStatus/);
+ assert.match(api, /IPC\.invoke\.speechTranscribe/);
+ assert.match(api, /validateSpeechSettings/);
+ assert.match(registerSrc, /registerSpeechIpc/);
+});
+
+test("Composer disables voice actions until speech is configured", async () => {
+ const composer = await readComposerSource();
+ assert.match(composer, /status\?\.transcribe\.available/);
+ assert.match(composer, /status\?\.synthesize\.available/);
+ assert.match(composer, /disabled=\{!transcribeEnabled \|\| transcribing \|\| speaking\}/);
+ assert.match(composer, /disabled=\{!speakEnabled \|\| speaking \|\| transcribing\}/);
+ assert.match(composer, /api\.speechTranscribe/);
+ assert.match(composer, /api\.speechSynthesize/);
+});
+
+test("settings reject an illegal speech protocol id", async () => {
+ const { validateSpeechSettings } = await import("@pi-desktop/shared");
+ assert.throws(
+ () =>
+ validateSpeechSettings({
+ transcribe: { providerId: "p", modelId: "m", protocol: "OpenAI Audio" },
+ }),
+ /protocol is invalid/,
+ );
+});
+
+function speechHarness({ transcribeProtocol = "openai_audio", synthesizeProtocol } = {}) {
+ const dataDir = mkdtempSync(join(tmpdir(), "pi-speech-svc-"));
+ test.after(() => rmSync(dataDir, { recursive: true, force: true }));
+ const scratch = join(dataDir, "scratch", "sess");
+ const host = {
+ call: async (method) => {
+ if (method === "settings.get") {
+ return {
+ speech: {
+ transcribe: { providerId: "p", modelId: "whisper-1", protocol: transcribeProtocol },
+ ...(synthesizeProtocol
+ ? { synthesize: { providerId: "p", modelId: "tts-1", protocol: synthesizeProtocol } }
+ : {}),
+ },
+ };
+ }
+ if (method === "providers.get") {
+ return { provider: { id: "p", baseUrl: "https://api.openai.com/v1", enabled: true } };
+ }
+ if (method === "providers.getSecret") return { value: "sk" };
+ if (method === "session.getScratchPath") return { path: scratch };
+ throw new Error(method);
+ },
+ };
+ return { dataDir, scratch, host };
+}
+
+test("speech-service keeps transcription inside session scratch", async () => {
+ const { createSpeechService } = await import("../electron/main/services/speech-service.ts");
+ const { dataDir, host } = speechHarness();
+ const outside = join(dataDir, "outside.wav");
+ writeFileSync(outside, "RIFF");
+ const speech = createSpeechService({
+ dataDir,
+ getHost: () => host,
+ plugins: { listSpeechAdapters: () => [], getSpeechAdapter: () => undefined, runSpeechAdapter: async () => ({}) },
+ logger: { app() {} },
+ });
+ await assert.rejects(
+ () => speech.transcribe({ sessionId: "sess", path: outside }),
+ (error) => error.errorCode === "INVALID_ARGUMENT",
+ );
+ await assert.rejects(
+ () => speech.transcribe({ path: outside }),
+ (error) => error.errorCode === "INVALID_ARGUMENT",
+ );
+});
+
+test("speech-service rejects a protocol that cannot transcribe", async () => {
+ const { createSpeechService } = await import("../electron/main/services/speech-service.ts");
+ const { dataDir, scratch, host } = speechHarness({ transcribeProtocol: "openai_chat_audio" });
+ const speech = createSpeechService({
+ dataDir,
+ getHost: () => host,
+ plugins: { listSpeechAdapters: () => [], getSpeechAdapter: () => undefined, runSpeechAdapter: async () => ({}) },
+ logger: { app() {} },
+ });
+ await assert.rejects(
+ () => speech.transcribe({ sessionId: "sess", path: join(scratch, "a.wav") }),
+ (error) => error.errorCode === "SPEECH_PROTOCOL_UNSUPPORTED",
+ );
+});
diff --git a/docs/adr/0281-host-speech-capability.md b/docs/adr/0281-host-speech-capability.md
new file mode 100644
index 000000000..f8497a5a4
--- /dev/null
+++ b/docs/adr/0281-host-speech-capability.md
@@ -0,0 +1,38 @@
+# ADR 0281: Host speech capability
+
+- Status: Accepted for implementation
+- Date: 2026-09-17
+- Deciders: PI-Desktop core
+- Related: [ADR 0257](0257-plugin-real-time-capabilities.md) ·
+ [03-runtime/20-speech](../spec/03-runtime/20-speech.md)
+
+## Context
+
+Chat models, image generation, transcription, and speech synthesis are different
+jobs. `@earendil-works/pi-ai` has no TTS/ASR surface, and Whisper / MIMO TTS
+must not appear in the chat model picker. Local OpenAI-Audio-compatible servers
+(Speaches, whisper.cpp, LocalAI) should work through an existing
+`openai_compatible` provider.
+
+## Decision
+
+1. The host owns a speech capability independent of chat:
+ `transcribe(audio) → text` and `synthesize(text) → audio`.
+2. Bindings live on optional `AppSettings.speech` (no schema bump). Each role
+ names an existing provider, a model id, and an open protocol id.
+3. Built-in protocols: `openai_audio` (REST `/audio/transcriptions` and
+ `/audio/speech`) and `openai_chat_audio` (chat completions `audio` field;
+ MIMO `mimo-v2.5-tts`). New vendors add an adapter, not a new IPC channel.
+4. Plugins may register a protocol with `pi.speech.registerAdapter` under
+ high-risk `speech.adapter.register`. Handles stay in the guest; HTTP plans
+ are executed by the host with the bound provider's key and must stay on that
+ origin. Built-in protocol ids are reserved.
+5. v1 product entry is Settings → AI Voice plus Composer file transcription and
+ draft speech. Audio bytes never enter the renderer (path in, scratch out).
+6. Out of scope: microphone / `pi.audio` device backend, Realtime, agent
+ `transcribe`/`speak` tools, audio as LLM content blocks, changing pi-ai.
+
+## Consequences
+
+Composer voice actions stay disabled until a role is configured. Provider
+deletion makes the binding fail `NOT_FOUND`. Plugin unload drops its protocols.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 602ceb71d..3777f7f90 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -307,4 +307,5 @@ Each ADR includes:
| 0278 | [Canonical application ID `net.aiuo.pi-desktop`](0278-canonical-application-id.md) | Accepted (D443; amends D141 / D371 / ADR 0204; issue #524) |
| 0279 | [Resumable subagent delegations](0279-resumable-subagent-delegations.md) | Accepted for implementation (amends ADR 0062; ADR 0089; issue #513) |
| 0280 | [Plugin-owned UI localizes from the host locale](0280-plugin-owned-ui-localizes-from-host-locale.md) | Accepted (amends ADR 0267; ADR 0159) |
+| 0281 | [Host speech capability](0281-host-speech-capability.md) | Accepted for implementation (amends ADR 0257) |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 4c9878a08..cd209cb23 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1946,6 +1946,17 @@ attachments. Electron main resolves the provider/model and credentials, so the
renderer never receives a secret. Empty drafts, slash-command drafts, missing
models, and provider failures return the common `Result` error envelope.
+### speech/getStatus, speech/transcribe, speech/synthesize
+
+```ts
+speech/getStatus() -> SpeechStatus
+speech/transcribe({ sessionId?, path, mimeType?, language? }) -> { text }
+speech/synthesize({ sessionId?, text, voice?, format? }) -> { path, mimeType, dataUrl? }
+```
+
+Host speech is independent of chat. Bindings live on `AppSettings.speech`.
+Audio bytes never enter the renderer. See spec `20-speech.md`.
+
### app/openFeedback (D313)
```ts
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 7d9b18840..a8114cb52 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -97,9 +97,11 @@ does not turn temporary thread pressure into a host process exit.
| `STREAM_FAILED` | yes | provider stream was terminated, closed prematurely, or otherwise ended before a complete response; up to ten same-turn retries may precede the terminal event |
| `EMPTY_MODEL_RESPONSE` | yes | the model ended its turn with no tool call and no visible text twice: once as streamed, once after the automatic re-run (spec 02-agent-runtime §5e) |
| `PROMPT_ENHANCEMENT_EMPTY` | no | the one-shot enhancement model returned no text |
+| `SPEECH_NOT_CONFIGURED` | no | host speech ASR or TTS is not bound in settings |
+| `SPEECH_PROTOCOL_UNSUPPORTED` | no | the speech protocol is unknown or does not support this role |
+| `SPEECH_INPUT_TOO_LARGE` | no | speech input exceeds 25 MB |
| `SUBAGENT_IDLE_TIMEOUT` | no | withdrawn (D328): idle watchdogs are not armed; the code remains for stored results |
| `SUBAGENT_DURATION_TIMEOUT` | no | withdrawn (D328): duration watchdogs are not armed; the code remains for stored results |
-
### 3.3 Workspace / tools / permissions
| code | retriable | meaning |
diff --git a/docs/spec/03-runtime/20-speech.md b/docs/spec/03-runtime/20-speech.md
new file mode 100644
index 000000000..bfdbda741
--- /dev/null
+++ b/docs/spec/03-runtime/20-speech.md
@@ -0,0 +1,75 @@
+# 20. Host speech
+
+> Source of truth: `packages/shared/src/types/speech.ts`,
+> `packages/agent-runtime/src/speech/`,
+> `apps/desktop/electron/main/services/speech-service.ts`.
+> ADR: [0281-host-speech-capability](../../adr/0281-host-speech-capability.md).
+
+## 1. Capability
+
+Independent of chat streams and the model picker:
+
+```
+transcribe({ sessionId, path, mimeType?, language? }) → { text }
+synthesize({ sessionId, text, voice?, format? }) → { path, mimeType, dataUrl? }
+```
+
+Input is a session-scratch file path. Output audio is written to that session's
+scratch. The renderer never receives a provider secret. TTS `dataUrl` is omitted
+when the file is larger than 8 MiB. Input is capped at 25 MiB
+(`SPEECH_INPUT_TOO_LARGE`).
+
+## 2. Bindings
+
+`AppSettings.speech` is optional and does not bump the storage schema:
+
+```
+{
+ transcribe?: { providerId, modelId, protocol, voice?, format?, path?, extra? }
+ synthesize?: { providerId, modelId, protocol, voice?, format?, path?, extra? }
+}
+```
+
+Protocol ids match `^[a-z][a-z0-9._-]{0,63}$`. Absent/empty speech is a valid
+unconfigured state: Composer actions stay disabled.
+
+## 3. Built-in protocols
+
+| id | transcribe | synthesize |
+|---|---|---|
+| `openai_audio` | `POST {baseUrl}/audio/transcriptions` multipart | `POST {baseUrl}/audio/speech` JSON |
+| `openai_chat_audio` | unsupported | `POST {baseUrl}/chat/completions` with `audio:{format,voice}`; read `choices.0.message.audio.data` |
+
+Local OpenAI-Audio-compatible servers use an `openai_compatible` provider and
+`openai_audio`. Suggested models: OpenAI `whisper-1` / `tts-1`, Groq
+`whisper-large-v3`, Xiaomi `mimo-v2.5-tts`.
+
+## 4. IPC
+
+```
+pi-desktop/speech/getStatus → SpeechStatus (no secrets)
+pi-desktop/speech/transcribe
+pi-desktop/speech/synthesize
+```
+
+Errors: `SPEECH_NOT_CONFIGURED`, `SPEECH_PROTOCOL_UNSUPPORTED`,
+`SPEECH_INPUT_TOO_LARGE`. Network/auth reuse `NETWORK_ERROR` /
+`PROVIDER_UNAUTHORIZED`. A missing or disabled provider returns `NOT_FOUND`.
+
+## 5. Plugin adapters
+
+`pi.speech.registerAdapter({ protocol, label, roles, handle })` requires
+`speech.adapter.register` (high risk). The handle stays in the plugin process.
+The host stores metadata only and calls `speech.handle`. A handle may return
+`{ kind: "text" }`, `{ kind: "audio", mimeType, data }`, or
+`{ kind: "http", call }` for the host to execute with the bound key. HTTP URLs
+must stay on the provider origin. Built-in protocol ids are reserved. Unload
+unregisters.
+
+## 6. Product
+
+Settings → AI **Voice** card: ASR and TTS each pick provider × protocol × model
+(TTS also voice). Composer: transcribe attached audio into the draft; read the
+draft aloud. Whisper / TTS models must not appear in the chat model picker.
+
+v1 does not implement microphone capture, Realtime, or agent tools.
diff --git a/docs/spec/03-runtime/README.md b/docs/spec/03-runtime/README.md
index 869f01e86..3b2ded8df 100644
--- a/docs/spec/03-runtime/README.md
+++ b/docs/spec/03-runtime/README.md
@@ -21,3 +21,4 @@
| [17-asktool-questions.md](17-asktool-questions.md) | Interactive multi-question tool |
| [18-line-anchored-edit-contract.md](18-line-anchored-edit-contract.md) | Line-anchored Edit contract |
| [19-remote-agent-control-protocol.md](19-remote-agent-control-protocol.md) | Remote Agent Control Protocol |
+| [20-speech.md](20-speech.md) | Host speech (ASR/TTS) |
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 3177c71e2..42dee07b8 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -172,6 +172,11 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
Manual `/compact` remains available from the command palette for an idle
session; the transcript shows where each compaction happened and the context
usage inspector shows whether a checkpoint is installed.
+- **Voice** card: default ASR and TTS bindings (`AppSettings.speech`). Each
+ role picks an existing provider, a protocol (`openai_audio` /
+ `openai_chat_audio` plus plugin adapters), and a model id. TTS may set a
+ voice. Unconfigured roles disable the matching Composer action. Whisper / TTS
+ models do not appear in the chat model picker. See spec `20-speech.md`.
Token usage is **not a Settings destination** (D335 / ADR 0173). Completed-turn
history stays host-owned (`session.endTurn.usage`, `stats.getTokenUsageHistory`).
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 53738341e..8b186e93c 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -316,6 +316,7 @@ combined model × reasoning selection (§11).
- Every control is keyboard-reachable with Tab
- Composer stop control has `aria-label="Stop generating"`
+- Composer transcribe / speak controls are icon buttons with `aria-label` from `chat.transcribe` / `chat.speak`. They stay disabled until the matching speech role is configured.
- The topbar does not render a separate running-state indicator; the Composer
submit control and transcript working feedback remain the running-state cues.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 124689fff..1cdd3699d 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -869,6 +869,20 @@ identify the platform validation still needed.
- **Status**: Source-level regression (`composer-ime.test.mjs`); full UI
keyboard journey remains Draft. Protocol smoke does not dispatch key events.
+#### E2E-008e: Host speech transcribe and speak
+
+- **Preconditions**: A session is open. Settings → AI Voice is unconfigured.
+- **Steps**: 1) Confirm Composer transcribe/speak stay disabled. 2) Bind ASR
+ (`openai_audio` / whisper) and TTS. 3) Attach a small wav and transcribe it
+ into the draft. 4) Read the draft aloud.
+- **Expected**: Unconfigured actions never call the provider. Transcribe inserts
+ text. Speak writes session scratch audio and plays a bounded data URL.
+ Whisper/TTS never appear in the chat model picker.
+- **Specs linked**: `03-runtime/20-speech.md`, `04-ux/06-settings-ia.md`
+- **Acceptance**: C (speech)
+- **Milestone**: M2
+- **Status**: Source-level regression (`speech-capability.test.mjs`,
+ `plugin-speech-adapter.test.mjs`); live provider journey remains Draft.
#### E2E-008a: First-turn tools load on demand
diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.md
index c1972698e..1622c1397 100644
--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md
+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md
@@ -312,6 +312,7 @@ type PluginPermission =
| "session.delete.own"
| "audio.capture.background"
| "audio.playback.background"
+ | "speech.adapter.register"
| "keyboard.globalShortcut"
| "net.websocket";
```
diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.md
index c1c89c44d..dccca5c2e 100644
--- a/docs/spec/07-plugins/03-plugin-api.md
+++ b/docs/spec/07-plugins/03-plugin-api.md
@@ -128,7 +128,23 @@ pi.commands.register(def: {
pi.commands.unregister(id: string): Promise<void>
```
+### speech (`speech.adapter.register`)
+```ts
+pi.speech.registerAdapter(adapter: {
+ protocol: string
+ label: string
+ roles: Array<"transcribe" | "synthesize">
+ handle: (input) => Promise<{ kind: "text"; text: string } | { kind: "audio"; mimeType: string; data: string } | { kind: "http"; call: SpeechHttpCall }>
+}): Promise<void>
+pi.speech.unregisterAdapter(protocol: string): Promise<void>
+```
+
+The handle stays in the plugin process. Built-in protocol ids `openai_audio`
+and `openai_chat_audio` are reserved. HTTP plans are executed by the host with
+the bound provider key and must stay on that origin.
+
### ui
+
```ts
pi.ui.openPanel(options?: { title?: string }): Promise<void>
pi.ui.closePanel(): Promise<void>
@@ -1057,6 +1073,7 @@ The desktop plugin runtime now implements the MVP host API surface used by local
`fs.writeText` / `fs.glob` / `fs.list` / `fs.remove` / `fs.requestDirectory`,
bounded by `manifest.fs` (ADR 0088)
- `agent.registerTool` / `unregisterTool` / `agent.complete`
+- `speech.registerAdapter` / `unregisterAdapter` (`speech.adapter.register`)
- `models.list`, `session.getLlmContext`
- `clipboard.*`, `shell.openExternal`, `net.fetch`
- `browser.*` (guest CDP; `browser.cdp`)
diff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.md
index bc03fef83..817b45dd1 100644
--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md
+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md
@@ -47,6 +47,7 @@ Provide a permission–capability–risk–default-policy reference table for re
| `session.update.own` | medium | `pi.session.rename` | Confirm at install | Renames only the calling plugin's active imported sessions |
| `session.delete.own` | high | `pi.session.delete` | Confirm at install | Trash/purge only the calling plugin's imported sessions; rate-limited |
| `agent.complete` | high | `pi.agent.complete` | Confirm at install | Host-owned one-shot; spends user quota; `includeSessionContext` also needs `session.read` |
+| `speech.adapter.register` | high | `pi.speech.registerAdapter` / `unregisterAdapter` | Confirm at install | Registers a speech protocol. Handles stay in the guest; HTTP plans are executed by the host with the bound provider key and must stay on that origin. Built-in protocol ids are reserved |
## 2A. A permission is the switch; the manifest carries the range
@@ -148,6 +149,7 @@ so "Modify the files it lists" is followed by the list.
| `session.update.own` | Rename sessions imported by this plugin | 重命名此插件导入的会话 |
| `session.delete.own` | Trash or purge sessions imported by this plugin | 将此插件导入的会话移入回收站或清除 |
| `agent.complete` | Run a one-shot completion with your models | 用你的模型发起一次补全 |
+| `speech.adapter.register` | Register a speech adapter | 注册语音适配器 |
| `audio.capture.background` | Use the microphone in the background | 后台使用麦克风 |
| `audio.playback.background` | Play audio in the background | 后台播放声音 |
| `keyboard.globalShortcut` | Register system-wide shortcuts | 注册系统级快捷键 |
diff --git a/docs/spec/NAV.md b/docs/spec/NAV.md
index 7b55675f0..6d92dc608 100644
--- a/docs/spec/NAV.md
+++ b/docs/spec/NAV.md
@@ -41,6 +41,7 @@
- [17-asktool-questions.md](03-runtime/17-asktool-questions.md)
- [18-line-anchored-edit-contract.md](03-runtime/18-line-anchored-edit-contract.md)
- [19-remote-agent-control-protocol.md](03-runtime/19-remote-agent-control-protocol.md)
+- [20-speech.md](03-runtime/20-speech.md)
## 4. UX
- [README.md](04-ux/README.md)
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index aa4f928b1..20dc8dff0 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -1609,6 +1609,15 @@ prompt/enhance({
提供商/模型和凭据,因此渲染器永远拿不到密钥。空草稿、斜杠命令草稿、缺失模型
以及提供商失败都返回通用的 `Result` 错误包络。
+### speech/getStatus、speech/transcribe、speech/synthesize
+```ts
+speech/getStatus() -> SpeechStatus
+speech/transcribe({ sessionId?, path, mimeType?, language? }) -> { text }
+speech/synthesize({ sessionId?, text, voice?, format? }) -> { path, mimeType, dataUrl? }
+```
+
+宿主语音独立于聊天。绑定在 `AppSettings.speech`。音频字节不进入渲染器。见 `20-speech.md`。
+
### app/openFeedback(D313)
```ts
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 7e6b874e0..fcb035cbb 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -98,6 +98,9 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况
| `STREAM_FAILED` | 是的 | 提供程序流在完整响应之前终止、提前关闭或以其他方式结束;最多四次同回合重试可能会在终止事件之前发生 |
| `EMPTY_MODEL_RESPONSE` | 是的 | 模型在没有工具调用且没有可见文本的情况下结束了两次:一次是流式传输,一次是在自动重新运行后(规范 02-agent-runtime §5e) |
| `PROMPT_ENHANCEMENT_EMPTY` | 不 | 一次性增强模型没有返回任何文本 |
+| `SPEECH_NOT_CONFIGURED` | 不 | 设置里没有绑定转写或朗读 |
+| `SPEECH_PROTOCOL_UNSUPPORTED` | 不 | 语音协议未知或不支持该角色 |
+| `SPEECH_INPUT_TOO_LARGE` | 不 | 语音输入超过 25 MB |
| `SUBAGENT_IDLE_TIMEOUT` | 不 | 已撤回(D328):空闲看门狗不再武装;代码仅为已存储结果保留 |
| `SUBAGENT_DURATION_TIMEOUT` | 不 | 已撤回(D328):时长看门狗不再武装;代码仅为已存储结果保留 |
diff --git a/docs/zh-CN/spec/03-runtime/20-speech.md b/docs/zh-CN/spec/03-runtime/20-speech.md
new file mode 100644
index 000000000..c42973e27
--- /dev/null
+++ b/docs/zh-CN/spec/03-runtime/20-speech.md
@@ -0,0 +1,75 @@
+# 20. 宿主语音
+
+> **翻译说明:** 本页是与 [英文源规格](/spec/03-runtime/20-speech) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。
+
+> 事实来源:`packages/shared/src/types/speech.ts`、
+> `packages/agent-runtime/src/speech/`、
+> `apps/desktop/electron/main/services/speech-service.ts`。
+> ADR:[0281-host-speech-capability](/adr/0281-host-speech-capability)。
+
+## 1. 能力
+
+独立于聊天流和模型选择器:
+
+```
+transcribe({ sessionId, path, mimeType?, language? }) → { text }
+synthesize({ sessionId, text, voice?, format? }) → { path, mimeType, dataUrl? }
+```
+
+输入是 session scratch 文件路径。输出音频写入该 session 的 scratch。
+渲染器不接收 provider 密钥。TTS `dataUrl` 在文件大于8 MiB 时省略。
+输入上限25 MiB(`SPEECH_INPUT_TOO_LARGE`)。
+
+## 2. 绑定
+
+`AppSettings.speech` 为可选字段,不升 schema:
+
+```
+{
+ transcribe?: { providerId, modelId, protocol, voice?, format?, path?, extra? }
+ synthesize?: { providerId, modelId, protocol, voice?, format?, path?, extra? }
+}
+```
+
+协议 id 匹配 `^[a-z][a-z0-9._-]{0,63}$`。speech 为空或缺省即未配置状态:
+Composer 入口保持禁用。
+
+## 3. 内置协议
+
+| id | transcribe | synthesize |
+|---|---|---|
+| `openai_audio` | `POST {baseUrl}/audio/transcriptions` multipart | `POST {baseUrl}/audio/speech` JSON |
+| `openai_chat_audio` | 不支持 | `POST {baseUrl}/chat/completions` + `audio:{format,voice}`;读取 `choices.0.message.audio.data` |
+
+本地 OpenAI-Audio 兼容服务器使用 `openai_compatible` provider +
+`openai_audio`。推荐模型:OpenAI `whisper-1` / `tts-1`、Groq
+`whisper-large-v3`、小米 `mimo-v2.5-tts`。
+
+## 4. IPC
+
+```
+pi-desktop/speech/getStatus → SpeechStatus(无密钥)
+pi-desktop/speech/transcribe
+pi-desktop/speech/synthesize
+```
+
+错误码:`SPEECH_NOT_CONFIGURED`、`SPEECH_PROTOCOL_UNSUPPORTED`、
+`SPEECH_INPUT_TOO_LARGE`。网络/认证复用 `NETWORK_ERROR` /
+`PROVIDER_UNAUTHORIZED`。provider 缺失或禁用返回 `NOT_FOUND`。
+
+## 5. 插件适配器
+
+`pi.speech.registerAdapter({ protocol, label, roles, handle })` 需要
+`speech.adapter.register`(高风险)。handle 留在插件进程内。
+宿主仅存元数据并调用 `speech.handle`。handle 可返回
+`{ kind: "text" }`、`{ kind: "audio", mimeType, data }` 或
+`{ kind: "http", call }` 由宿主用绑定密钥代发。HTTP URL
+必须保持在 provider origin。内置协议 id 受保留。卸载时注销。
+
+## 6. 产品
+
+设置 → AI **语音** 卡片:ASR 和 TTS 各选 provider × protocol × model
+(TTS 还选 voice)。Composer:转写附件音频到草稿;朗读草稿。
+Whisper / TTS 模型不得出现在聊天模型选择器中。
+
+v1 不实现麦克风采集、Realtime 和 agent 工具。
diff --git a/docs/zh-CN/spec/03-runtime/README.md b/docs/zh-CN/spec/03-runtime/README.md
index 98ce9e077..ba72d2a20 100644
--- a/docs/zh-CN/spec/03-runtime/README.md
+++ b/docs/zh-CN/spec/03-runtime/README.md
@@ -24,3 +24,4 @@
| [17-asktool-questions.md](/zh-CN/spec/03-runtime/17-asktool-questions) | 交互式多问题工具 |
| [18-line-anchored-edit-contract.md](/zh-CN/spec/03-runtime/18-line-anchored-edit-contract) | 按行锚定的 Edit 合约 |
| [19-remote-agent-control-protocol.md](/zh-CN/spec/03-runtime/19-remote-agent-control-protocol) | 远程 Agent 控制协议 |
+| [20-speech.md](/zh-CN/spec/03-runtime/20-speech) | 宿主语音(转写/朗读) |
diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index 4aad9e7f5..998ce4874 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -86,6 +86,7 @@
工具栏上下文环及其弹层是以剩余容量还是已用容量为引导数值;默认为剩余。
该阈值决定纯文本粘贴何时转为会话临时文件,默认值为 600 个字符,
接受 1 至 1,000,000 的整数。
+- **语音**卡:默认转写/朗读绑定(`AppSettings.speech`)。未配置时 Composer 对应入口禁用。Whisper / TTS 不进聊天模型列表。见 `20-speech.md`。
- **默认项**卡中的**命令 Shell**行:主机发现的本机 PowerShell 5.1、PowerShell 7、
cmd、Git Bash 和 ID 为 `windows-powershell`、`windows-pwsh`、`cmd`、`git-bash`
的 Bash 和
diff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
index baa76deae..c7251ea3f 100644
--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
@@ -284,6 +284,7 @@ type PluginPermission =
| "session.delete.own"
| "audio.capture.background"
| "audio.playback.background"
+ | "speech.adapter.register"
| "keyboard.globalShortcut"
| "net.websocket";
```
diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
index 9e2557f22..3e7dc0c24 100644
--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md
+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
@@ -107,6 +107,21 @@ pi.commands.register(def: {
pi.commands.unregister(id: string): Promise<void>
```
+### 语音(`speech.adapter.register`)
+```ts
+pi.speech.registerAdapter(adapter: {
+ protocol: string
+ label: string
+ roles: Array<"transcribe" | "synthesize">
+ handle: (input) => Promise<{ kind: "text"; text: string } | { kind: "audio"; mimeType: string; data: string } | { kind: "http"; call: SpeechHttpCall }>
+}): Promise<void>
+pi.speech.unregisterAdapter(protocol: string): Promise<void>
+```
+
+handle 留在插件进程。内置协议 id `openai_audio` 和 `openai_chat_audio` 保留。
+HTTP 计划由宿主用绑定 provider 的密钥代发,且必须落在该 origin。
+
+
### 用户界面
```ts
pi.ui.openPanel(options?: { title?: string }): Promise<void>
@@ -854,6 +869,8 @@ window.pluginBridge.on(event, handler)
`fs.writeText` / `fs.glob` / `fs.list` / `fs.remove` / `fs.requestDirectory`,
范围由 `manifest.fs` 限定(ADR 0088)
- `agent.registerTool` / `unregisterTool` / `agent.complete`
+- `speech.registerAdapter` / `unregisterAdapter`(`speech.adapter.register`)
+
- `models.list`、`session.getLlmContext`
- `clipboard.*`、`shell.openExternal`、`net.fetch`
- `browser.*`(访客页 CDP;`browser.cdp`)
diff --git a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
index a51c6d49e..33b260c1f 100644
--- a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
+++ b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
@@ -50,6 +50,7 @@
| `session.update.own` | 中等 | `pi.session.rename` | 安装时确认 | 只能重命名本插件拥有的活动导入会话 |
| `session.delete.own` | 高 | `pi.session.delete` | 安装时确认 | 只能回收或清除本插件导入的会话;有频率限制 |
| `agent.complete` | 高 | `pi.agent.complete` | 安装时确认 | 宿主代发一次性补全;消耗用户额度;`includeSessionContext` 还需要 `session.read` |
+| `speech.adapter.register` | 高 | `pi.speech.registerAdapter` / `unregisterAdapter` | 安装时确认 | 注册语音协议。handle 留在插件进程;HTTP 计划由宿主用绑定密钥代发且必须同 origin |
## 2A. 权限是开关,manifest 承载范围
@@ -145,6 +146,7 @@ Agent,在 Plan 中不可见。主机返回 `PLUGIN_DISABLED_IN_PLAN`
| `session.update.own` | Rename sessions imported by this plugin | 重命名此插件导入的会话 |
| `session.delete.own` | Trash or purge sessions imported by this plugin | 将此插件导入的会话移入回收站或清除 |
| `agent.complete` | Run a one-shot completion with your models | 用你的模型发起一次补全 |
+| `speech.adapter.register` | Register a speech adapter | 注册语音适配器 |
| `audio.capture.background` | Use the microphone in the background | 后台使用麦克风 |
| `audio.playback.background` | Play audio in the background | 后台播放声音 |
| `keyboard.globalShortcut` | Register system-wide shortcuts | 注册系统级快捷键 |
diff --git a/docs/zh-CN/spec/NAV.md b/docs/zh-CN/spec/NAV.md
index e26bbda11..80e36552d 100644
--- a/docs/zh-CN/spec/NAV.md
+++ b/docs/zh-CN/spec/NAV.md
@@ -44,6 +44,7 @@
- [17-asktool-questions.md](/zh-CN/spec/03-runtime/17-asktool-questions)
- [18-line-anchored-edit-contract.md](/zh-CN/spec/03-runtime/18-line-anchored-edit-contract)
- [19-remote-agent-control-protocol.md](/zh-CN/spec/03-runtime/19-remote-agent-control-protocol)
+- [20-speech.md](/zh-CN/spec/03-runtime/20-speech)
## 4. 用户体验
- [README.md](/zh-CN/spec/04-ux/README)
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index 236c1f244..146f97f73 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -20,3 +20,5 @@ export * from "./stream-coalescer.js";
export * from "./extensions/index.js";
export { startAuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";
export type { AuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";
+
+export * from "./speech/index.js";
diff --git a/packages/agent-runtime/src/speech/adapters.test.ts b/packages/agent-runtime/src/speech/adapters.test.ts
new file mode 100644
index 000000000..18342e374
--- /dev/null
+++ b/packages/agent-runtime/src/speech/adapters.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from "vitest";
+import type { SpeechBinding } from "@pi-desktop/shared";
+import { openaiAudioCall, openaiChatAudioCall, runBuiltinSpeech } from "./adapters.js";
+import { assertSameOrigin } from "./http.js";
+
+const transcribe: SpeechBinding = {
+ providerId: "openai",
+ modelId: "whisper-1",
+ protocol: "openai_audio",
+};
+
+const tts: SpeechBinding = {
+ providerId: "openai",
+ modelId: "tts-1",
+ protocol: "openai_audio",
+ voice: "alloy",
+ format: "mp3",
+};
+
+const chatTts: SpeechBinding = {
+ providerId: "xiaomi",
+ modelId: "mimo-v2.5-tts",
+ protocol: "openai_chat_audio",
+ voice: "Chloe",
+ format: "wav",
+ extra: { style: "Bright and bouncy." },
+};
+
+describe("builtin speech adapters", () => {
+ it("builds OpenAI transcription multipart", () => {
+ const call = openaiAudioCall(
+ { role: "transcribe", binding: transcribe, language: "en" },
+ { baseUrl: "https://api.openai.com/v1" },
+ );
+ expect(call.url).toBe("https://api.openai.com/v1/audio/transcriptions");
+ expect(call.body).toMatchObject({
+ type: "multipart",
+ fileField: "file",
+ fields: { model: "whisper-1", language: "en" },
+ });
+ });
+
+ it("builds OpenAI speech JSON", () => {
+ const call = openaiAudioCall(
+ { role: "synthesize", binding: tts, text: "hello" },
+ { baseUrl: "https://api.openai.com/v1" },
+ );
+ expect(call.url).toBe("https://api.openai.com/v1/audio/speech");
+ expect(call.body).toMatchObject({
+ type: "json",
+ value: { model: "tts-1", input: "hello", voice: "alloy", response_format: "mp3" },
+ });
+ });
+
+ it("builds MIMO-style chat audio", () => {
+ const call = openaiChatAudioCall(
+ { role: "synthesize", binding: chatTts, text: "I passed!" },
+ { baseUrl: "https://api.xiaomimimo.com/v1" },
+ );
+ expect(call.url).toBe("https://api.xiaomimimo.com/v1/chat/completions");
+ expect(call.body).toMatchObject({
+ type: "json",
+ value: {
+ model: "mimo-v2.5-tts",
+ audio: { format: "wav", voice: "Chloe" },
+ },
+ });
+ });
+
+ it("transcribes through a mock OpenAI Audio server", async () => {
+ const result = await runBuiltinSpeech(
+ {
+ role: "transcribe",
+ binding: transcribe,
+ audio: { filename: "a.wav", mimeType: "audio/wav", bytes: new Uint8Array([1, 2, 3]) },
+ },
+ {
+ baseUrl: "https://api.openai.com/v1",
+ apiKey: "sk-test",
+ fetchImpl: async (url, init) => {
+ expect(String(url)).toContain("/audio/transcriptions");
+ expect((init?.headers as Headers).get("Authorization")).toBe("Bearer sk-test");
+ expect(init?.body).toBeInstanceOf(FormData);
+ return new Response(JSON.stringify({ text: "hello world" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ },
+ },
+ );
+ expect(result).toEqual({ kind: "text", text: "hello world" });
+ });
+
+ it("decodes chat-audio base64", async () => {
+ const wav = Buffer.from("RIFF").toString("base64");
+ const result = await runBuiltinSpeech(
+ { role: "synthesize", binding: chatTts, text: "hi" },
+ {
+ baseUrl: "https://api.xiaomimimo.com/v1",
+ apiKey: "mimo",
+ fetchImpl: async () =>
+ new Response(
+ JSON.stringify({ choices: [{ message: { audio: { data: wav } } }] }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ },
+ );
+ expect(result.kind).toBe("audio");
+ if (result.kind === "audio") {
+ expect(Buffer.from(result.bytes).toString()).toBe("RIFF");
+ }
+ });
+
+ it("rejects an unknown protocol", async () => {
+ await expect(
+ runBuiltinSpeech(
+ {
+ role: "synthesize",
+ binding: { ...tts, protocol: "elevenlabs" },
+ text: "hi",
+ },
+ { baseUrl: "https://api.openai.com/v1" },
+ ),
+ ).rejects.toMatchObject({ errorCode: "SPEECH_PROTOCOL_UNSUPPORTED" });
+ });
+});
+
+describe("assertSameOrigin", () => {
+ it("allows the provider origin", () => {
+ expect(() =>
+ assertSameOrigin("https://api.openai.com/v1", "https://api.openai.com/v1/audio/speech"),
+ ).not.toThrow();
+ });
+
+ it("rejects a different origin", () => {
+ expect(() => assertSameOrigin("https://api.openai.com/v1", "https://evil.test/x")).toThrow(
+ /provider origin/,
+ );
+ });
+});
+
diff --git a/packages/agent-runtime/src/speech/adapters.ts b/packages/agent-runtime/src/speech/adapters.ts
new file mode 100644
index 000000000..dfe7b4a68
--- /dev/null
+++ b/packages/agent-runtime/src/speech/adapters.ts
@@ -0,0 +1,118 @@
+import { ErrorCodes, type SpeechBinding, type SpeechRole } from "@pi-desktop/shared";
+import {
+ assertSameOrigin,
+ executeSpeechHttp,
+ joinProviderUrl,
+ type SpeechHttpCall,
+ type SpeechHttpContext,
+ type SpeechHttpResult,
+} from "./http.js";
+
+export type SpeechJob = {
+ role: SpeechRole;
+ binding: SpeechBinding;
+ text?: string;
+ language?: string;
+ audio?: { filename: string; mimeType: string; bytes: Uint8Array };
+};
+
+export type SpeechEndpoint = {
+ baseUrl: string;
+ apiKey?: string;
+ fetchImpl?: typeof fetch;
+};
+
+function fail(code: string, message: string): never {
+ throw Object.assign(new Error(message), { errorCode: code });
+}
+
+function endpointUrl(endpoint: SpeechEndpoint, binding: SpeechBinding, fallback: string): string {
+ const url = joinProviderUrl(endpoint.baseUrl, binding.path || fallback);
+ assertSameOrigin(endpoint.baseUrl, url);
+ return url;
+}
+
+export function openaiAudioCall(job: SpeechJob, endpoint: SpeechEndpoint): SpeechHttpCall {
+ const { binding, role } = job;
+ if (role === "transcribe") {
+ return {
+ url: endpointUrl(endpoint, binding, "audio/transcriptions"),
+ body: {
+ type: "multipart",
+ fields: {
+ model: binding.modelId,
+ ...(job.language ? { language: job.language } : {}),
+ ...(binding.extra ?? {}),
+ },
+ fileField: "file",
+ },
+ parse: "openai-transcription",
+ };
+ }
+ const format = binding.format || "mp3";
+ return {
+ url: endpointUrl(endpoint, binding, "audio/speech"),
+ body: {
+ type: "json",
+ value: {
+ model: binding.modelId,
+ input: job.text ?? "",
+ voice: job.binding.voice || "alloy",
+ response_format: format,
+ ...(binding.extra ?? {}),
+ },
+ },
+ parse: "bytes",
+ };
+}
+
+export function openaiChatAudioCall(job: SpeechJob, endpoint: SpeechEndpoint): SpeechHttpCall {
+ if (job.role !== "synthesize") {
+ fail(ErrorCodes.SPEECH_PROTOCOL_UNSUPPORTED, "openai_chat_audio does not transcribe");
+ }
+ const format = job.binding.format || "wav";
+ const voice = job.binding.voice || "alloy";
+ const style = job.binding.extra?.style;
+ return {
+ url: endpointUrl(endpoint, job.binding, "chat/completions"),
+ body: {
+ type: "json",
+ value: {
+ model: job.binding.modelId,
+ messages: [
+ ...(style ? [{ role: "user", content: style }] : []),
+ { role: "assistant", content: job.text ?? "" },
+ ],
+ audio: { format, voice },
+ ...(job.binding.extra
+ ? Object.fromEntries(Object.entries(job.binding.extra).filter(([key]) => key !== "style"))
+ : {}),
+ },
+ },
+ parse: "openai-chat-audio",
+ };
+}
+
+export function builtinSpeechCall(job: SpeechJob, endpoint: SpeechEndpoint): SpeechHttpCall {
+ switch (job.binding.protocol) {
+ case "openai_audio":
+ return openaiAudioCall(job, endpoint);
+ case "openai_chat_audio":
+ return openaiChatAudioCall(job, endpoint);
+ default:
+ fail(ErrorCodes.SPEECH_PROTOCOL_UNSUPPORTED, `unknown speech protocol: ${job.binding.protocol}`);
+ }
+}
+
+export async function runBuiltinSpeech(
+ job: SpeechJob,
+ endpoint: SpeechEndpoint,
+): Promise<SpeechHttpResult> {
+ const call = builtinSpeechCall(job, endpoint);
+ const context: SpeechHttpContext = {
+ apiKey: endpoint.apiKey,
+ audio: job.audio,
+ fetchImpl: endpoint.fetchImpl,
+ };
+ return executeSpeechHttp(call, context);
+}
diff --git a/packages/agent-runtime/src/speech/http.ts b/packages/agent-runtime/src/speech/http.ts
new file mode 100644
index 000000000..0c07d9569
--- /dev/null
+++ b/packages/agent-runtime/src/speech/http.ts
@@ -0,0 +1,180 @@
+import { ErrorCodes } from "@pi-desktop/shared";
+
+export type SpeechHttpBody =
+ | { type: "json"; value: unknown }
+ | { type: "multipart"; fields?: Record<string, string>; fileField?: string }
+ | { type: "raw"; mimeType: string; bytes: Uint8Array };
+
+export type SpeechHttpParse =
+ | "bytes"
+ | "json-text"
+ | "json-path"
+ | "openai-transcription"
+ | "openai-chat-audio";
+
+export type SpeechHttpCall = {
+ url: string;
+ method?: "GET" | "POST";
+ headers?: Record<string, string>;
+ body?: SpeechHttpBody;
+ parse: SpeechHttpParse;
+ jsonPath?: string;
+};
+
+export type SpeechHttpContext = {
+ apiKey?: string;
+ audio?: { filename: string; mimeType: string; bytes: Uint8Array };
+ fetchImpl?: typeof fetch;
+};
+
+export type SpeechHttpResult =
+ | { kind: "text"; text: string }
+ | { kind: "audio"; mimeType: string; bytes: Uint8Array };
+
+function fail(code: string, message: string): never {
+ throw Object.assign(new Error(message), { errorCode: code });
+}
+
+export function joinProviderUrl(baseUrl: string, path = ""): string {
+ if (/^https?:\/\//i.test(path)) return path;
+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
+ return new URL(path.replace(/^\//, ""), base).href;
+}
+
+export function assertSameOrigin(baseUrl: string, url: string): void {
+ let expected: URL;
+ let actual: URL;
+ try {
+ expected = new URL(baseUrl);
+ actual = new URL(url);
+ } catch {
+ fail(ErrorCodes.INVALID_ARGUMENT, "speech request URL is invalid");
+ }
+ if (expected.protocol !== actual.protocol || expected.host !== actual.host) {
+ fail(ErrorCodes.INVALID_ARGUMENT, "speech request URL must stay on the provider origin");
+ }
+}
+
+function headerMap(headers: Headers): Record<string, string> {
+ const out: Record<string, string> = {};
+ headers.forEach((value, key) => {
+ out[key.toLowerCase()] = value;
+ });
+ return out;
+}
+
+function readPath(value: unknown, path: string): unknown {
+ let current: unknown = value;
+ for (const part of path.split(".").filter(Boolean)) {
+ if (!current || typeof current !== "object" || Array.isArray(current) && !/^\d+$/.test(part)) {
+ if (Array.isArray(current) && /^\d+$/.test(part)) {
+ current = current[Number(part)];
+ continue;
+ }
+ return undefined;
+ }
+ current = (current as Record<string, unknown>)[part];
+ }
+ return current;
+}
+
+function decodeBase64(value: string): Uint8Array {
+ return new Uint8Array(Buffer.from(value, "base64"));
+}
+
+function asBodyBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
+ const copy = new Uint8Array(bytes.byteLength);
+ copy.set(bytes);
+ return copy;
+}
+
+async function parseBody(
+ response: Response,
+ call: SpeechHttpCall,
+): Promise<SpeechHttpResult> {
+ const mimeType = headerMap(response.headers)["content-type"]?.split(";")[0]?.trim() || "application/octet-stream";
+ if (call.parse === "bytes") {
+ return { kind: "audio", mimeType, bytes: new Uint8Array(await response.arrayBuffer()) };
+ }
+ const json = (await response.json()) as unknown;
+ if (call.parse === "json-text" || call.parse === "openai-transcription") {
+ const text =
+ typeof (json as { text?: unknown })?.text === "string"
+ ? (json as { text: string }).text
+ : typeof (json as { transcript?: unknown })?.transcript === "string"
+ ? (json as { transcript: string }).transcript
+ : undefined;
+ if (!text?.trim()) fail(ErrorCodes.PROVIDER_ERROR, "speech response had no text");
+ return { kind: "text", text: text.trim() };
+ }
+ if (call.parse === "json-path") {
+ const path = call.jsonPath?.trim();
+ if (!path) fail(ErrorCodes.INVALID_ARGUMENT, "speech jsonPath is required");
+ const found = readPath(json, path);
+ if (typeof found !== "string" || !found.trim()) {
+ fail(ErrorCodes.PROVIDER_ERROR, "speech response path was empty");
+ }
+ return { kind: "text", text: found.trim() };
+ }
+ const data = readPath(json, call.jsonPath?.trim() || "choices.0.message.audio.data");
+ if (typeof data !== "string" || !data.trim()) {
+ fail(ErrorCodes.PROVIDER_ERROR, "speech response had no audio");
+ }
+ return { kind: "audio", mimeType: "audio/wav", bytes: decodeBase64(data.trim()) };
+}
+
+export async function executeSpeechHttp(
+ call: SpeechHttpCall,
+ context: SpeechHttpContext = {},
+): Promise<SpeechHttpResult> {
+ const headers = new Headers();
+ for (const [key, value] of Object.entries(call.headers ?? {})) {
+ if (key.toLowerCase() === "authorization") continue;
+ headers.set(key, value);
+ }
+ if (context.apiKey) headers.set("Authorization", `Bearer ${context.apiKey}`);
+
+ let body: BodyInit | undefined;
+ const spec = call.body;
+ if (spec?.type === "json") {
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
+ body = JSON.stringify(spec.value ?? {});
+ } else if (spec?.type === "raw") {
+ if (!headers.has("content-type")) headers.set("content-type", spec.mimeType);
+ body = asBodyBytes(spec.bytes);
+ } else if (spec?.type === "multipart") {
+ const form = new FormData();
+ for (const [key, value] of Object.entries(spec.fields ?? {})) form.append(key, value);
+ if (spec.fileField) {
+ const audio = context.audio;
+ if (!audio) fail(ErrorCodes.INVALID_ARGUMENT, "speech audio file is required");
+ form.append(
+ spec.fileField,
+ new Blob([asBodyBytes(audio.bytes)], { type: audio.mimeType || "application/octet-stream" }),
+
+ audio.filename || "audio.wav",
+ );
+ }
+ body = form;
+ }
+
+ const fetchImpl = context.fetchImpl ?? fetch;
+ let response: Response;
+ try {
+ response = await fetchImpl(call.url, {
+ method: call.method ?? "POST",
+ headers,
+ body,
+ });
+ } catch (error) {
+ fail(ErrorCodes.NETWORK_ERROR, error instanceof Error ? error.message : "speech request failed");
+ }
+ if (response.status === 401 || response.status === 403) {
+ fail(ErrorCodes.PROVIDER_UNAUTHORIZED, `speech provider returned ${response.status}`);
+ }
+ if (!response.ok) {
+ const detail = (await response.text().catch(() => "")).slice(0, 300);
+ fail(ErrorCodes.PROVIDER_ERROR, detail || `speech provider returned ${response.status}`);
+ }
+ return parseBody(response, call);
+}
diff --git a/packages/agent-runtime/src/speech/index.ts b/packages/agent-runtime/src/speech/index.ts
new file mode 100644
index 000000000..05f652aa9
--- /dev/null
+++ b/packages/agent-runtime/src/speech/index.ts
@@ -0,0 +1,18 @@
+export {
+ assertSameOrigin,
+ executeSpeechHttp,
+ joinProviderUrl,
+ type SpeechHttpBody,
+ type SpeechHttpCall,
+ type SpeechHttpContext,
+ type SpeechHttpParse,
+ type SpeechHttpResult,
+} from "./http.js";
+export {
+ builtinSpeechCall,
+ openaiAudioCall,
+ openaiChatAudioCall,
+ runBuiltinSpeech,
+ type SpeechEndpoint,
+ type SpeechJob,
+} from "./adapters.js";
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 54983e8bc..395e09081 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -238,6 +238,13 @@ export const de = {
"editQueuedPromptBusy": "Leere das Eingabefeld, bevor du diese wartende Nachricht bearbeitest",
"enhancePrompt": "Eingabeaufforderung verbessern",
"enhancingPrompt": "Verbesserung…",
+ "transcribe": "Audio transkribieren",
+ "transcribing": "Transkription…",
+ "transcribeFailed": "Dieses Audio konnte nicht transkribiert werden",
+ "speak": "Vorlesen",
+ "speaking": "Wird vorgelesen…",
+ "speakFailed": "Dieser Entwurf konnte nicht vorgelesen werden",
+ "speakSaved": "Gesprochene Audio gespeichert unter {{path}}",
"undoEnhancement": "Verbesserung rückgängig machen",
"enhancementFailed": "Eingabeaufforderung zur Verbesserung fehlgeschlagen",
"dismissEnhancementError": "Verbesserungsfehler verwerfen",
@@ -872,6 +879,19 @@ sklm: {
"proxyTestOk": "Verbunden",
"proxyTestFail": "Verbindung konnte nicht hergestellt werden: {{message}}",
"defaultsTitle": "Standardwerte",
+ "speechTitle": "Stimme",
+ "speechDesc": "Transkription und Sprache nutzen einen konfigurierten Anbieter und erscheinen nicht in der Chat-Modellliste.",
+ "speechTranscribe": "Transkription",
+ "speechTranscribeDesc": "Angehängtes Audio in Entwurftext verwandeln.",
+ "speechSynthesize": "Sprache",
+ "speechSynthesizeDesc": "Den Composer-Entwurf vorlesen.",
+ "speechProvider": "Anbieter",
+ "speechProtocol": "Protokoll",
+ "speechModel": "Modell",
+ "speechVoice": "Stimme",
+ "speechNone": "Nicht konfiguriert",
+ "speechModelPlaceholder": "whisper-1",
+ "speechVoicePlaceholder": "alloy",
"defaultModel": "Standardmodell",
"defaultModelNone": "Kein KI-Anbieter bereit",
"defaultModelSearch": "Filtermodelle",
@@ -1599,6 +1619,7 @@ sklm: {
"background.service": "Einen Hintergrunddienst laufen lassen",
"audio.capture.background": "Das Mikrofon im Hintergrund nutzen",
"audio.playback.background": "Audio im Hintergrund wiedergeben",
+ "speech.adapter.register": "Einen Sprachadapter registrieren",
"keyboard.globalShortcut": "Systemweite Tastaturkürzel registrieren",
"net.websocket": "Echtzeitverbindungen öffnen",
"bus.publish": "Nachrichten an andere Plugins senden",
@@ -1634,6 +1655,7 @@ sklm: {
"background.service": "Hält einen Worker am Laufen, während das Plugin aktiviert ist.",
"audio.capture.background": "Erfasst das Mikrofon, während das Plugin im Hintergrund läuft und kein Panel geöffnet ist.",
"audio.playback.background": "Gibt Audio wieder, das das Plugin streamt, auch wenn kein Panel geöffnet ist.",
+ "speech.adapter.register": "Kann ein Transkriptions- oder Sprachprotokoll hinzufügen, das vorhandene Anbieterschlüssel nutzt. Das Plugin sieht den Schlüssel nie.",
"keyboard.globalShortcut": "Registriert systemweite Tastaturkürzel, die die eigenen Befehle dieses Plugins auslösen, während PI-Desktop nicht fokussiert ist.",
"net.websocket": "Öffnet bidirektionale Echtzeitverbindungen zu den Hosts, die das Plugin deklariert hat.",
"bus.publish": "Kann Nachrichten zu den angegebenen Themen senden.",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index a243fd8ba..1439d47e8 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -245,6 +245,13 @@ export const en = {
editQueuedPromptBusy: "Clear the input before editing this queued message",
enhancePrompt: "Enhance prompt",
enhancingPrompt: "Enhancing…",
+ transcribe: "Transcribe audio",
+ transcribing: "Transcribing…",
+ transcribeFailed: "Couldn't transcribe this audio",
+ speak: "Read aloud",
+ speaking: "Reading…",
+ speakFailed: "Couldn't read this draft",
+ speakSaved: "Saved spoken audio to {{path}}",
undoEnhancement: "Undo enhancement",
enhancementFailed: "Prompt enhancement failed",
dismissEnhancementError: "Dismiss enhancement error",
@@ -884,6 +891,19 @@ sklm: {
proxyTestOk: "Connected",
proxyTestFail: "Couldn't connect: {{message}}",
defaultsTitle: "Defaults",
+ speechTitle: "Voice",
+ speechDesc: "Transcription and speech use a configured provider. They stay out of the chat model picker.",
+ speechTranscribe: "Transcription",
+ speechTranscribeDesc: "Turn attached audio into draft text.",
+ speechSynthesize: "Speech",
+ speechSynthesizeDesc: "Read the composer draft aloud.",
+ speechProvider: "Provider",
+ speechProtocol: "Protocol",
+ speechModel: "Model",
+ speechVoice: "Voice",
+ speechNone: "Not configured",
+ speechModelPlaceholder: "whisper-1",
+ speechVoicePlaceholder: "alloy",
defaultModel: "Default model",
defaultModelNone: "No AI provider ready",
defaultModelSearch: "Filter models",
@@ -1616,6 +1636,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a
"background.service": "Keep a background service running",
"audio.capture.background": "Use the microphone in the background",
"audio.playback.background": "Play audio in the background",
+ "speech.adapter.register": "Register a speech adapter",
"keyboard.globalShortcut": "Register system-wide shortcuts",
"net.websocket": "Open real-time connections",
"bus.publish": "Send messages to other plugins",
@@ -1663,6 +1684,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a
"background.service": "Keeps a worker running while the plugin is enabled.",
"audio.capture.background": "Captures the microphone while the plugin runs in the background, with no panel open.",
"audio.playback.background": "Plays audio the plugin streams, even when no panel is open.",
+ "speech.adapter.register": "Can add a transcription or speech protocol that uses your existing provider keys. The plugin never sees the key.",
"keyboard.globalShortcut": "Registers system-wide keyboard shortcuts that trigger this plugin's own commands while PI-Desktop is not focused.",
"net.websocket": "Opens real-time two-way connections to the hostnames the plugin declared.",
"bus.publish": "Can send messages on the topics it declared.",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 29db2828e..636204748 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -238,6 +238,13 @@ export const es = {
"editQueuedPromptBusy": "Vacía el campo antes de editar este mensaje en cola",
"enhancePrompt": "Mejorar mensaje",
"enhancingPrompt": "Mejorando...",
+ "transcribe": "Transcribir audio",
+ "transcribing": "Transcribiendo…",
+ "transcribeFailed": "No se pudo transcribir este audio",
+ "speak": "Leer en voz alta",
+ "speaking": "Leyendo…",
+ "speakFailed": "No se pudo leer este borrador",
+ "speakSaved": "Audio guardado en {{path}}",
"undoEnhancement": "Deshacer mejora",
"enhancementFailed": "Error en la mejora de solicitud",
"dismissEnhancementError": "Descartar error de mejora",
@@ -872,6 +879,19 @@ sklm: {
"proxyTestOk": "Conectado",
"proxyTestFail": "No se pudo conectar: ​​{{message}}",
"defaultsTitle": "Valores predeterminados",
+ "speechTitle": "Voz",
+ "speechDesc": "La transcripción y la voz usan un proveedor configurado. No aparecen en el selector de modelos del chat.",
+ "speechTranscribe": "Transcripción",
+ "speechTranscribeDesc": "Convertir el audio adjunto en texto del borrador.",
+ "speechSynthesize": "Voz",
+ "speechSynthesizeDesc": "Leer en voz alta el borrador del compositor.",
+ "speechProvider": "Proveedor",
+ "speechProtocol": "Protocolo",
+ "speechModel": "Modelo",
+ "speechVoice": "Voz",
+ "speechNone": "Sin configurar",
+ "speechModelPlaceholder": "whisper-1",
+ "speechVoicePlaceholder": "alloy",
"defaultModel": "Modelo predeterminado",
"defaultModelNone": "No hay ningún proveedor de IA listo",
"defaultModelSearch": "Modelos de filtro",
@@ -1599,6 +1619,7 @@ sklm: {
"background.service": "Mantener un servicio en segundo plano en ejecución",
"audio.capture.background": "Usar el micrófono en segundo plano",
"audio.playback.background": "Reproducir audio en segundo plano",
+ "speech.adapter.register": "Registrar un adaptador de voz",
"keyboard.globalShortcut": "Registrar atajos de teclado del sistema",
"net.websocket": "Abrir conexiones en tiempo real",
"bus.publish": "Enviar mensajes a otros complementos",
@@ -1634,6 +1655,7 @@ sklm: {
"background.service": "Mantiene a un trabajador en ejecución mientras el complemento está habilitado.",
"audio.capture.background": "Captura el micrófono mientras el complemento se ejecuta en segundo plano, sin ningún panel abierto.",
"audio.playback.background": "Reproduce el audio que transmite el complemento, incluso cuando no hay ningún panel abierto.",
+ "speech.adapter.register": "Puede añadir un protocolo de transcripción o voz que use tus claves de proveedor. El complemento nunca ve la clave.",
"keyboard.globalShortcut": "Registra atajos de teclado del sistema que activan los comandos propios de este complemento mientras PI-Desktop no tiene el foco.",
"net.websocket": "Abre conexiones bidireccionales en tiempo real con los hosts que declara el complemento.",
"bus.publish": "Puede enviar mensajes sobre los temas que declaró.",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 5543ff87a..f15d7f610 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -238,6 +238,13 @@ export const fr = {
"editQueuedPromptBusy": "Videz le champ avant de modifier ce message en attente",
"enhancePrompt": "Améliorer l'invite",
"enhancingPrompt": "Amélioration…",
+ "transcribe": "Transcrire l’audio",
+ "transcribing": "Transcription…",
+ "transcribeFailed": "Impossible de transcrire cet audio",
+ "speak": "Lire à voix haute",
+ "speaking": "Lecture…",
+ "speakFailed": "Impossible de lire ce brouillon",
+ "speakSaved": "Audio enregistré dans {{path}}",
"undoEnhancement": "Annuler l'amélioration",
"enhancementFailed": "L'amélioration de l'invite a échoué",
"dismissEnhancementError": "Ignorer l'erreur d'amélioration",
@@ -872,6 +879,19 @@ sklm: {
"proxyTestOk": "Connecté",
"proxyTestFail": "Impossible de se connecter : {{message}}",
"defaultsTitle": "Valeurs par défaut",
+ "speechTitle": "Voix",
+ "speechDesc": "La transcription et la synthèse utilisent un fournisseur configuré. Elles n’apparaissent pas dans le sélecteur de modèles du chat.",
+ "speechTranscribe": "Transcription",
+ "speechTranscribeDesc": "Transformer l’audio joint en texte du brouillon.",
+ "speechSynthesize": "Synthèse",
+ "speechSynthesizeDesc": "Lire le brouillon du compositeur à voix haute.",
+ "speechProvider": "Fournisseur",
+ "speechProtocol": "Protocole",
+ "speechModel": "Modèle",
+ "speechVoice": "Voix",
+ "speechNone": "Non configuré",
+ "speechModelPlaceholder": "whisper-1",
+ "speechVoicePlaceholder": "alloy",
"defaultModel": "Modèle par défaut",
"defaultModelNone": "Aucun fournisseur d'IA prêt",
"defaultModelSearch": "Modèles de filtre",
@@ -1599,6 +1619,7 @@ sklm: {
"background.service": "Maintenir un service en arrière-plan en cours d'exécution",
"audio.capture.background": "Utiliser le microphone en arrière-plan",
"audio.playback.background": "Lire l'audio en arrière-plan",
+ "speech.adapter.register": "Enregistrer un adaptateur vocal",
"keyboard.globalShortcut": "Enregistrer des raccourcis clavier système",
"net.websocket": "Ouvrir des connexions en temps réel",
"bus.publish": "Envoyer des messages à d'autres plugins",
@@ -1634,6 +1655,7 @@ sklm: {
"background.service": "Maintient un travailleur en cours d'exécution pendant que le plugin est activé.",
"audio.capture.background": "Capture le microphone pendant que le plugin s'exécute en arrière-plan, sans panneau ouvert.",
"audio.playback.background": "Lit l'audio diffusé par le plugin, même lorsqu'aucun panneau n'est ouvert.",
+ "speech.adapter.register": "Peut ajouter un protocole de transcription ou de synthèse qui réutilise vos clés fournisseur. Le plugin ne voit jamais la clé.",
"keyboard.globalShortcut": "Enregistre des raccourcis clavier système qui déclenchent les commandes propres à ce plugin lorsque PI-Desktop n'est pas au premier plan.",
"net.websocket": "Ouvre des connexions bidirectionnelles en temps réel vers les hôtes déclarés par le plugin.",
"bus.publish": "Peut envoyer des messages sur les sujets qu'il a déclarés.",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index f9bebd115..96d7381a7 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -247,6 +247,13 @@ export const ko = {
editQueuedPromptBusy: "대기 중인 메시지를 편집하려면 먼저 입력란을 비우세요",
enhancePrompt: "프롬프트 개선",
enhancingPrompt: "개선 중…",
+ transcribe: "오디오 받아쓰기",
+ transcribing: "받아쓰는 중…",
+ transcribeFailed: "이 오디오를 받아쓸 수 없습니다",
+ speak: "소리 내어 읽기",
+ speaking: "읽는 중…",
+ speakFailed: "이 초안을 읽을 수 없습니다",
+ speakSaved: "음성 파일을 {{path}}에 저장했습니다",
undoEnhancement: "개선 취소",
enhancementFailed: "프롬프트 개선 실패",
dismissEnhancementError: "프롬프트 개선 오류 닫기",
@@ -885,6 +892,19 @@ sklm: {
proxyTestOk: "연결됨",
proxyTestFail: "연결할 수 없습니다: {{message}}",
defaultsTitle: "기본값",
+ speechTitle: "음성",
+ speechDesc: "받아쓰기와 낭독은 설정된 제공자를 사용하며 채팅 모델 목록에는 나오지 않습니다.",
+ speechTranscribe: "받아쓰기",
+ speechTranscribeDesc: "첨부된 오디오를 초안 텍스트로 바꿉니다.",
+ speechSynthesize: "낭독",
+ speechSynthesizeDesc: "입력창의 초안을 소리 내어 읽습니다.",
+ speechProvider: "제공자",
+ speechProtocol: "프로토콜",
+ speechModel: "모델",
+ speechVoice: "목소리",
+ speechNone: "설정되지 않음",
+ speechModelPlaceholder: "whisper-1",
+ speechVoicePlaceholder: "alloy",
defaultModel: "기본 모델",
defaultModelNone: "사용 가능한 AI 프로바이더 없음",
defaultModelSearch: "모델 필터",
@@ -1617,6 +1637,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
"background.service": "백그라운드 서비스 계속 실행",
"audio.capture.background": "백그라운드에서 마이크 사용",
"audio.playback.background": "백그라운드 오디오 재생",
+ "speech.adapter.register": "음성 어댑터 등록",
"keyboard.globalShortcut": "시스템 전역 키보드 단축키 등록",
"net.websocket": "실시간 연결 열기",
"bus.publish": "다른 플러그인에 메시지 보내기",
@@ -1663,6 +1684,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
"background.service": "플러그인이 활성화된 동안 작업자를 계속 실행합니다.",
"audio.capture.background": "플러그인이 백그라운드에서 실행되는 동안 패널이 열려 있지 않아도 마이크를 캡처합니다.",
"audio.playback.background": "패널이 열려 있지 않아도 플러그인이 스트리밍하는 오디오를 재생합니다.",
+ "speech.adapter.register": "기존 제공자 키를 쓰는 받아쓰기 또는 낭독 프로토콜을 추가할 수 있습니다. 플러그인은 키를 보지 못합니다.",
"keyboard.globalShortcut": "PI-Desktop이 포커스되지 않은 상태에서 이 플러그인 자체 명령을 실행하는 시스템 전역 키보드 단축키를 등록합니다.",
"net.websocket": "플러그인이 선언한 호스트로 실시간 양방향 연결을 엽니다.",
"bus.publish": "선언한 주제로 메시지를 보낼 수 있습니다.",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index a49af9691..03a69505a 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -247,6 +247,13 @@ export const tr = {
editQueuedPromptBusy: "Bu sıradaki iletiyi düzenlemeden önce giriş alanını temizle",
enhancePrompt: "İstemi iyileştir",
enhancingPrompt: "İyileştiriliyor…",
+ transcribe: "Sesi yazıya dök",
+ transcribing: "Yazıya dökülüyor…",
+ transcribeFailed: "Bu ses yazıya dökülemedi",
+ speak: "Sesli oku",
+ speaking: "Okunuyor…",
+ speakFailed: "Bu taslak okunamadı",
+ speakSaved: "Ses {{path}} konumuna kaydedildi",
undoEnhancement: "İyileştirmeyi geri al",
enhancementFailed: "İstem iyileştirilemedi",
dismissEnhancementError: "İyileştirme hatasını kapat",
@@ -885,6 +892,19 @@ sklm: {
proxyTestOk: "Bağlandı",
proxyTestFail: "Bağlanılamadı: {{message}}",
defaultsTitle: "Varsayılanlar",
+ speechTitle: "Ses",
+ speechDesc: "Yazıya dökme ve konuşma yapılandırılmış bir sağlayıcı kullanır. Sohbet model listesinde görünmezler.",
+ speechTranscribe: "Yazıya dökme",
+ speechTranscribeDesc: "Ekli sesi taslak metne çevir.",
+ speechSynthesize: "Konuşma",
+ speechSynthesizeDesc: "Besteci taslağını sesli oku.",
+ speechProvider: "Sağlayıcı",
+ speechProtocol: "Protokol",
+ speechModel: "Model",
+ speechVoice: "Ses",
+ speechNone: "Yapılandırılmadı",
+ speechModelPlaceholder: "whisper-1",
+ speechVoicePlaceholder: "alloy",
defaultModel: "Varsayılan model",
defaultModelNone: "Hazır AI servisi yok",
defaultModelSearch: "Modelleri süz",
@@ -1617,6 +1637,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
"background.service": "Arka plan servisini çalışır tut",
"audio.capture.background": "Mikrofonu arka planda kullan",
"audio.playback.background": "Sesi arka planda çal",
+ "speech.adapter.register": "Bir konuşma bağdaştırıcısı kaydet",
"keyboard.globalShortcut": "Sistem geneli klavye kısayolları kaydet",
"net.websocket": "Gerçek zamanlı bağlantılar aç",
"bus.publish": "Diğer eklentilere ileti gönder",
@@ -1663,6 +1684,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
"background.service": "Eklenti açıkken bir işçiyi çalışır tutar.",
"audio.capture.background": "Eklenti arka planda çalışırken, hiçbir panel açık olmadan mikrofonu yakalar.",
"audio.playback.background": "Hiçbir panel açık olmasa bile eklentinin akışa verdiği sesi çalar.",
+ "speech.adapter.register": "Mevcut sağlayıcı anahtarlarınızı kullanan bir yazıya dökme veya konuşma protokolü ekleyebilir. Eklenti anahtarı asla görmez.",
"keyboard.globalShortcut": "PI-Desktop odakta değilken bu eklentinin kendi komutlarını tetikleyen sistem geneli klavye kısayollarını kaydeder.",
"net.websocket": "Eklentinin bildirdiği ana makinelere gerçek zamanlı iki yönlü bağlantılar açar.",
"bus.publish": "Bildirdiği konularda ileti gönderebilir.",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 7b5174e75..6d7e8d7a8 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -240,6 +240,13 @@ export const zhCN = {
editQueuedPromptBusy: "请先清空输入框,再编辑这条待发送消息",
enhancePrompt: "增强提示词",
enhancingPrompt: "增强中…",
+ transcribe: "转写音频",
+ transcribing: "转写中…",
+ transcribeFailed: "无法转写这段音频",
+ speak: "朗读",
+ speaking: "朗读中…",
+ speakFailed: "无法朗读这段草稿",
+ speakSaved: "朗读音频已保存到 {{path}}",
undoEnhancement: "撤回增强",
enhancementFailed: "提示词增强失败",
dismissEnhancementError: "关闭增强错误",
@@ -873,6 +880,19 @@ sklm: {
proxyTestOk: "已连接",
proxyTestFail: "无法连接:{{message}}",
defaultsTitle: "默认项",
+ speechTitle: "语音",
+ speechDesc: "转写和朗读使用已配置的服务,不会出现在聊天模型列表里。",
+ speechTranscribe: "转写",
+ speechTranscribeDesc: "把附件音频转成草稿文字。",
+ speechSynthesize: "朗读",
+ speechSynthesizeDesc: "朗读输入框里的草稿。",
+ speechProvider: "服务",
+ speechProtocol: "协议",
+ speechModel: "模型",
+ speechVoice: "音色",
+ speechNone: "未配置",
+ speechModelPlaceholder: "whisper-1",
+ speechVoicePlaceholder: "alloy",
defaultModel: "默认模型",
defaultModelNone: "还没有可用的 AI 服务",
defaultModelSearch: "筛选模型",
@@ -1599,6 +1619,7 @@ sklm: {
"background.service": "保持后台服务运行",
"audio.capture.background": "后台使用麦克风",
"audio.playback.background": "后台播放声音",
+ "speech.adapter.register": "注册语音适配器",
"keyboard.globalShortcut": "注册系统级快捷键",
"net.websocket": "建立实时双向连接",
"bus.publish": "向其他插件发送消息",
@@ -1636,6 +1657,7 @@ sklm: {
"background.service": "插件启用期间保持一个后台工作进程运行。",
"audio.capture.background": "插件在后台运行时(没有打开面板)也能采集麦克风。",
"audio.playback.background": "即使没有打开面板,也能播放插件推送的音频。",
+ "speech.adapter.register": "可以添加转写或朗读协议,复用你已有的服务密钥。插件拿不到密钥。",
"keyboard.globalShortcut": "注册系统级快捷键,在 PI-Desktop 未聚焦时触发本插件自己的命令。",
"net.websocket": "与插件声明的域名建立实时双向连接。",
"bus.publish": "可在其声明的主题上发送消息。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 525c45b3b..e28990527 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -240,6 +240,13 @@ export const zhTW = {
editQueuedPromptBusy: "請先清空輸入框,再編輯這則待傳送訊息",
enhancePrompt: "增強提示詞",
enhancingPrompt: "增強中…",
+ transcribe: "轉寫音訊",
+ transcribing: "轉寫中…",
+ transcribeFailed: "無法轉寫這段音訊",
+ speak: "朗讀",
+ speaking: "朗讀中…",
+ speakFailed: "無法朗讀這段草稿",
+ speakSaved: "朗讀音訊已儲存到 {{path}}",
undoEnhancement: "撤回增強",
enhancementFailed: "提示詞增強失敗",
dismissEnhancementError: "關閉增強錯誤",
@@ -873,6 +880,19 @@ sklm: {
proxyTestOk: "已連線",
proxyTestFail: "無法連線:{{message}}",
defaultsTitle: "預設項",
+ speechTitle: "語音",
+ speechDesc: "轉寫和朗讀使用已設定的服務,不會出現在聊天模型清單裡。",
+ speechTranscribe: "轉寫",
+ speechTranscribeDesc: "把附件音訊轉成草稿文字。",
+ speechSynthesize: "朗讀",
+ speechSynthesizeDesc: "朗讀輸入框裡的草稿。",
+ speechProvider: "服務",
+ speechProtocol: "協定",
+ speechModel: "模型",
+ speechVoice: "音色",
+ speechNone: "未設定",
+ speechModelPlaceholder: "whisper-1",
+ speechVoicePlaceholder: "alloy",
defaultModel: "預設模型",
defaultModelNone: "還沒有可用的 AI 服務",
defaultModelSearch: "篩選模型",
@@ -1599,6 +1619,7 @@ sklm: {
"background.service": "保持後臺服務執行",
"audio.capture.background": "後臺使用麥克風",
"audio.playback.background": "後臺播放聲音",
+ "speech.adapter.register": "註冊語音轉接器",
"keyboard.globalShortcut": "註冊系統級快捷鍵",
"net.websocket": "建立即時雙向連線",
"bus.publish": "向其他外掛傳送訊息",
@@ -1635,6 +1656,7 @@ sklm: {
"background.service": "外掛啟用期間保持一個後臺工作程序執行。",
"audio.capture.background": "外掛在後臺執行時(沒有開啟面板)也能擷取麥克風。",
"audio.playback.background": "即使沒有開啟面板,也能播放外掛推送的音訊。",
+ "speech.adapter.register": "可以新增轉寫或朗讀協定,沿用你既有的服務金鑰。外掛拿不到金鑰。",
"keyboard.globalShortcut": "註冊系統級快捷鍵,在 PI-Desktop 未聚焦時觸發此外掛自己的命令。",
"net.websocket": "與外掛宣告的網域建立即時雙向連線。",
"bus.publish": "可在其宣告的主題上傳送訊息。",
diff --git a/packages/plugin-devkit/src/check.ts b/packages/plugin-devkit/src/check.ts
index 61ca53e80..750336e9d 100644
--- a/packages/plugin-devkit/src/check.ts
+++ b/packages/plugin-devkit/src/check.ts
@@ -31,6 +31,7 @@ export const HIGH_RISK_PERMISSIONS = [
"agent.tool.register",
"browser.cdp",
"audio.capture.background",
+ "speech.adapter.register",
] as const;
/** Host API surface each permission unlocks, used for the unused-permission hint. */
@@ -58,6 +59,7 @@ const PERMISSION_API_HINTS: Record<string, string[]> = {
"fs.write": ["fs.writeText"],
"fs.delete": ["fs.remove"],
"agent.tool.register": ["agent.registerTool"],
+ "speech.adapter.register": ["speech.registerAdapter"],
"net.fetch": ["net.fetch"],
"audio.capture.background": [
"audio.getInputDevices",
diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.ts
index 0f6311e7c..168a49658 100644
--- a/packages/plugin-sdk/src/index.test.ts
+++ b/packages/plugin-sdk/src/index.test.ts
@@ -543,6 +543,7 @@ describe("PLUGIN_PERMISSIONS", () => {
"browser.cdp",
"audio.capture.background",
"audio.playback.background",
+ "speech.adapter.register",
"keyboard.globalShortcut",
"net.websocket",
]) {
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 72f5b8875..8f11c6501 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -592,6 +592,42 @@ export type PluginCommand = {
run: () => Promise<void> | void;
};
+export type PluginSpeechRole = "transcribe" | "synthesize";
+
+export type PluginSpeechHandleInput = {
+ protocol: string;
+ role: PluginSpeechRole;
+ modelId: string;
+ voice?: string;
+ format?: string;
+ extra?: Record<string, string>;
+ text?: string;
+ language?: string;
+ audio?: { mimeType: string; data: string };
+};
+
+export type PluginSpeechHandleResult =
+ | { kind: "text"; text: string }
+ | { kind: "audio"; mimeType: string; data: string }
+ | {
+ kind: "http";
+ call: {
+ url: string;
+ method?: "GET" | "POST";
+ headers?: Record<string, string>;
+ body?: unknown;
+ parse: "bytes" | "json-text" | "json-path" | "openai-transcription" | "openai-chat-audio";
+ jsonPath?: string;
+ };
+ };
+
+export type PluginSpeechAdapter = {
+ protocol: string;
+ label: string;
+ roles: PluginSpeechRole[];
+ handle: (input: PluginSpeechHandleInput) => Promise<PluginSpeechHandleResult> | PluginSpeechHandleResult;
+};
+
export type PluginTool = {
name: string;
description: string;
@@ -929,6 +965,10 @@ export type PluginHostApi = {
register: (command: PluginCommand) => Promise<void>;
unregister: (id: string) => Promise<void>;
};
+ speech: {
+ registerAdapter: (adapter: PluginSpeechAdapter) => Promise<void>;
+ unregisterAdapter: (protocol: string) => Promise<void>;
+ };
ui: {
openPanel: (opts?: { title?: string }) => Promise<void>;
closePanel: () => Promise<void>;
@@ -1176,6 +1216,7 @@ export const PLUGIN_PERMISSIONS = [
// what a service may use with no page open.
"audio.capture.background",
"audio.playback.background",
+ "speech.adapter.register",
"keyboard.globalShortcut",
"net.websocket",
] as const;
diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.ts
index e73ec2987..1e5479d99 100644
--- a/packages/shared/src/errors.ts
+++ b/packages/shared/src/errors.ts
@@ -80,6 +80,9 @@ export const ErrorCodes = {
STREAM_FAILED: "STREAM_FAILED",
EMPTY_MODEL_RESPONSE: "EMPTY_MODEL_RESPONSE",
PROMPT_ENHANCEMENT_EMPTY: "PROMPT_ENHANCEMENT_EMPTY",
+ SPEECH_NOT_CONFIGURED: "SPEECH_NOT_CONFIGURED",
+ SPEECH_PROTOCOL_UNSUPPORTED: "SPEECH_PROTOCOL_UNSUPPORTED",
+ SPEECH_INPUT_TOO_LARGE: "SPEECH_INPUT_TOO_LARGE",
SUBAGENT_IDLE_TIMEOUT: "SUBAGENT_IDLE_TIMEOUT",
SUBAGENT_DURATION_TIMEOUT: "SUBAGENT_DURATION_TIMEOUT",
WORKSPACE_REQUIRED: "WORKSPACE_REQUIRED",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index dd403dc4d..357170568 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -46,6 +46,7 @@ export * from "./model-catalog.js";
export * from "./github-feedback.js";
export * from "./network-proxy.js";
export * from "./attachment-limits.js";
+export * from "./speech.js";
export * from "./font-size.js";
export * from "./chat-content-width.js";
export * from "./racp.js";
diff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.ts
index 36cf99a8a..f108e3484 100644
--- a/packages/shared/src/protocol.test.ts
+++ b/packages/shared/src/protocol.test.ts
@@ -61,6 +61,10 @@ describe("Plan protocol contracts", () => {
expect(IPC_WHITELIST.has(IPC.invoke.modelConfigImportRun)).toBe(true);
expect(IPC.invoke.projectClone).toBe("pi-desktop/project/clone");
expect(IPC_WHITELIST.has(IPC.invoke.projectClone)).toBe(true);
+ expect(IPC.invoke.speechTranscribe).toBe("pi-desktop/speech/transcribe");
+ expect(IPC_WHITELIST.has(IPC.invoke.speechTranscribe)).toBe(true);
+ expect(IPC_WHITELIST.has(IPC.invoke.speechSynthesize)).toBe(true);
+ expect(IPC_WHITELIST.has(IPC.invoke.speechGetStatus)).toBe(true);
});
it("exposes the vendor-account OAuth channels through the preload whitelist", () => {
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 636d978e4..726742e68 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -71,6 +71,9 @@ export const IPC = {
agentPrompt: "pi-desktop/agent/prompt",
agentSteer: "pi-desktop/agent/steer",
promptEnhance: "pi-desktop/prompt/enhance",
+ speechTranscribe: "pi-desktop/speech/transcribe",
+ speechSynthesize: "pi-desktop/speech/synthesize",
+ speechGetStatus: "pi-desktop/speech/getStatus",
agentCompact: "pi-desktop/agent/compact",
agentAbort: "pi-desktop/agent/abort",
agentStop: "pi-desktop/agent/stop",
diff --git a/packages/shared/src/speech.test.ts b/packages/shared/src/speech.test.ts
new file mode 100644
index 000000000..7af254048
--- /dev/null
+++ b/packages/shared/src/speech.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest";
+import {
+ builtinSpeechProtocols,
+ parseSpeechBinding,
+ validateSpeechSettings,
+} from "./speech.js";
+
+describe("validateSpeechSettings", () => {
+ it("accepts absent speech", () => {
+ expect(validateSpeechSettings(undefined)).toBeUndefined();
+ expect(validateSpeechSettings(null)).toBeUndefined();
+ expect(validateSpeechSettings({})).toBeUndefined();
+ });
+
+ it("parses a transcribe binding", () => {
+ const speech = validateSpeechSettings({
+ transcribe: {
+ providerId: "openai",
+ modelId: "whisper-1",
+ protocol: "openai_audio",
+ },
+ });
+ expect(speech?.transcribe).toEqual({
+ providerId: "openai",
+ modelId: "whisper-1",
+ protocol: "openai_audio",
+ });
+ });
+
+ it("rejects a closed protocol enum and accepts plugin ids", () => {
+ const speech = validateSpeechSettings({
+ synthesize: {
+ providerId: "eleven",
+ modelId: "eleven_multilingual_v2",
+ protocol: "elevenlabs",
+ voice: "Rachel",
+ },
+ });
+ expect(speech?.synthesize?.protocol).toBe("elevenlabs");
+ });
+
+ it("rejects an invalid protocol id", () => {
+ expect(() =>
+ parseSpeechBinding(
+ { providerId: "p", modelId: "m", protocol: "OpenAI Audio" },
+ "transcribe",
+ ),
+ ).toThrow(/protocol is invalid/);
+ });
+});
+
+describe("builtinSpeechProtocols", () => {
+ it("lists open request-shape adapters", () => {
+ expect(builtinSpeechProtocols().map((item) => item.id)).toEqual([
+ "openai_audio",
+ "openai_chat_audio",
+ ]);
+ });
+});
diff --git a/packages/shared/src/speech.ts b/packages/shared/src/speech.ts
new file mode 100644
index 000000000..08be20adc
--- /dev/null
+++ b/packages/shared/src/speech.ts
@@ -0,0 +1,135 @@
+/** Validation and catalog helpers for host speech bindings. */
+import {
+ BUILTIN_SPEECH_PROTOCOLS,
+ MAX_SPEECH_INPUT_BYTES,
+ SPEECH_PROTOCOL_PATTERN,
+ SPEECH_ROLES,
+ type SpeechBinding,
+ type SpeechProtocolInfo,
+ type SpeechRole,
+ type SpeechSettings,
+} from "./types/speech.js";
+
+export {
+ BUILTIN_SPEECH_PROTOCOL_IDS,
+ BUILTIN_SPEECH_PROTOCOLS,
+ MAX_SPEECH_INPUT_BYTES,
+ MAX_SPEECH_TTS_DATA_URL_BYTES,
+ SPEECH_PROTOCOL_PATTERN,
+ SPEECH_ROLES,
+} from "./types/speech.js";
+export type {
+ BuiltinSpeechProtocolId,
+ SpeechBinding,
+ SpeechProtocolInfo,
+ SpeechRole,
+ SpeechRoleStatus,
+ SpeechSettings,
+ SpeechStatus,
+ SpeechSynthesizeRequest,
+ SpeechSynthesizeResult,
+ SpeechTranscribeRequest,
+ SpeechTranscribeResult,
+} from "./types/speech.js";
+
+const MAX_PROVIDER_ID = 128;
+const MAX_MODEL_ID = 256;
+const MAX_VOICE = 64;
+const MAX_FORMAT = 32;
+const MAX_PATH = 256;
+const MAX_EXTRA_KEYS = 16;
+const MAX_EXTRA_VALUE = 256;
+
+function invalid(message: string): never {
+ throw Object.assign(new Error(message), { errorCode: "INVALID_ARGUMENT" });
+}
+
+function asTrimmed(value: unknown, field: string, max: number): string {
+ if (typeof value !== "string" || !value.trim()) invalid(`${field} is required`);
+ const trimmed = value.trim();
+ if (trimmed.length > max) invalid(`${field} is too long`);
+ return trimmed;
+}
+
+function asOptionalString(value: unknown, field: string, max: number): string | undefined {
+ if (value === undefined || value === null || value === "") return undefined;
+ if (typeof value !== "string") invalid(`${field} must be a string`);
+ const trimmed = value.trim();
+ if (!trimmed) return undefined;
+ if (trimmed.length > max) invalid(`${field} is too long`);
+ return trimmed;
+}
+
+export function isSpeechProtocolId(value: string): boolean {
+ return SPEECH_PROTOCOL_PATTERN.test(value);
+}
+
+export function builtinSpeechProtocols(): SpeechProtocolInfo[] {
+ return Object.values(BUILTIN_SPEECH_PROTOCOLS).map((entry) => ({
+ id: entry.id,
+ label: entry.label,
+ roles: [...entry.roles],
+ source: "builtin",
+ }));
+}
+
+export function parseSpeechBinding(value: unknown, role: SpeechRole): SpeechBinding {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ invalid(`speech.${role} must be an object`);
+ }
+ const record = value as Record<string, unknown>;
+ const protocol = asTrimmed(record.protocol, `speech.${role}.protocol`, 64);
+ if (!isSpeechProtocolId(protocol)) invalid(`speech.${role}.protocol is invalid`);
+ const extraRaw = record.extra;
+ let extra: Record<string, string> | undefined;
+ if (extraRaw !== undefined && extraRaw !== null) {
+ if (!extraRaw || typeof extraRaw !== "object" || Array.isArray(extraRaw)) {
+ invalid(`speech.${role}.extra must be an object`);
+ }
+ const entries = Object.entries(extraRaw as Record<string, unknown>);
+ if (entries.length > MAX_EXTRA_KEYS) invalid(`speech.${role}.extra has too many keys`);
+ extra = {};
+ for (const [key, item] of entries) {
+ if (!isSpeechProtocolId(key) && !/^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/.test(key)) {
+ invalid(`speech.${role}.extra key is invalid`);
+ }
+ extra[key] = asTrimmed(item, `speech.${role}.extra.${key}`, MAX_EXTRA_VALUE);
+ }
+ }
+ const voice = asOptionalString(record.voice, `speech.${role}.voice`, MAX_VOICE);
+ const format = asOptionalString(record.format, `speech.${role}.format`, MAX_FORMAT);
+ const path = asOptionalString(record.path, `speech.${role}.path`, MAX_PATH);
+ return {
+ providerId: asTrimmed(record.providerId, `speech.${role}.providerId`, MAX_PROVIDER_ID),
+ modelId: asTrimmed(record.modelId, `speech.${role}.modelId`, MAX_MODEL_ID),
+ protocol,
+ ...(voice ? { voice } : {}),
+ ...(format ? { format } : {}),
+ ...(path ? { path } : {}),
+ ...(extra ? { extra } : {}),
+ };
+}
+
+/** Reject malformed `settings.speech`. Absent/empty is a valid unconfigured state. */
+export function validateSpeechSettings(value: unknown): SpeechSettings | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (typeof value !== "object" || Array.isArray(value)) invalid("speech must be an object");
+ const record = value as Record<string, unknown>;
+ const next: SpeechSettings = {};
+ for (const role of SPEECH_ROLES) {
+ if (!Object.prototype.hasOwnProperty.call(record, role)) continue;
+ const raw = record[role];
+ if (raw === undefined || raw === null) continue;
+ next[role] = parseSpeechBinding(raw, role);
+ }
+ return Object.keys(next).length ? next : undefined;
+}
+
+export function assertSpeechInputSize(bytes: number): void {
+ if (!Number.isFinite(bytes) || bytes < 0) invalid("speech input size is invalid");
+ if (bytes > MAX_SPEECH_INPUT_BYTES) {
+ throw Object.assign(new Error("speech input is too large"), {
+ errorCode: "SPEECH_INPUT_TOO_LARGE",
+ });
+ }
+}
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index e02855e71..7c69b9425 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -20,3 +20,4 @@ export * from "./types/composer.js";
export * from "./types/platform.js";
export * from "./types/workpanel.js";
export * from "./types/filesystem.js";
+export * from "./types/speech.js";
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index 45d7ee55d..44db7e7da 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -6,6 +6,7 @@ import type { ContextCompactionSettings } from "./sessions.js";
import type { Mode } from "./common.js";
import type { GlobalPermissionMode } from "./permissions.js";
import type { PluginMarketSource } from "./plugins.js";
+import type { SpeechSettings } from "./speech.js";
export type ThemePreference = "system" | "light" | "dark" | `plugin:${string}`;
@@ -22,6 +23,8 @@ export type CloseBehavior = "ask" | "tray" | "quit";
export type AppSettings = {
defaultProviderId?: string;
defaultModelId?: string;
+ /** Host speech bindings. Absent means voice actions stay disabled. */
+ speech?: SpeechSettings;
defaultMode: Mode;
/** Configured command shell for the agent Bash protocol tool. */
defaultCommandShell?: CommandShellId;
diff --git a/packages/shared/src/types/speech.ts b/packages/shared/src/types/speech.ts
new file mode 100644
index 000000000..be4961ab3
--- /dev/null
+++ b/packages/shared/src/types/speech.ts
@@ -0,0 +1,89 @@
+/** Host speech capability bindings. Protocol ids are open strings. */
+export const SPEECH_ROLES = ["transcribe", "synthesize"] as const;
+export type SpeechRole = (typeof SPEECH_ROLES)[number];
+
+/** Wire identity for a request-shape adapter. Built-ins plus plugin ids. */
+export const SPEECH_PROTOCOL_PATTERN = /^[a-z][a-z0-9._-]{0,63}$/;
+
+export const MAX_SPEECH_INPUT_BYTES = 25_000_000;
+export const MAX_SPEECH_TTS_DATA_URL_BYTES = 8_000_000;
+
+export const BUILTIN_SPEECH_PROTOCOL_IDS = ["openai_audio", "openai_chat_audio"] as const;
+export type BuiltinSpeechProtocolId = (typeof BUILTIN_SPEECH_PROTOCOL_IDS)[number];
+
+export const BUILTIN_SPEECH_PROTOCOLS: Record<
+ BuiltinSpeechProtocolId,
+ { id: BuiltinSpeechProtocolId; label: string; roles: readonly SpeechRole[] }
+> = {
+ openai_audio: {
+ id: "openai_audio",
+ label: "OpenAI Audio",
+ roles: ["transcribe", "synthesize"],
+ },
+ openai_chat_audio: {
+ id: "openai_chat_audio",
+ label: "Chat Completions Audio",
+ roles: ["synthesize"],
+ },
+};
+
+export type SpeechBinding = {
+ providerId: string;
+ modelId: string;
+ protocol: string;
+ voice?: string;
+ format?: string;
+ /** Optional path under the provider base URL. */
+ path?: string;
+ extra?: Record<string, string>;
+};
+
+export type SpeechSettings = {
+ transcribe?: SpeechBinding;
+ synthesize?: SpeechBinding;
+};
+
+export type SpeechProtocolInfo = {
+ id: string;
+ label: string;
+ roles: SpeechRole[];
+ source: "builtin" | "plugin";
+ pluginId?: string;
+};
+
+export type SpeechRoleStatus = {
+ configured: boolean;
+ available: boolean;
+ providerId?: string;
+ modelId?: string;
+ protocol?: string;
+};
+
+export type SpeechStatus = {
+ transcribe: SpeechRoleStatus;
+ synthesize: SpeechRoleStatus;
+ protocols: SpeechProtocolInfo[];
+};
+
+export type SpeechTranscribeRequest = {
+ sessionId?: string | null;
+ path: string;
+ mimeType?: string;
+ language?: string;
+};
+
+export type SpeechTranscribeResult = { text: string };
+
+export type SpeechSynthesizeRequest = {
+ sessionId?: string | null;
+ text: string;
+ voice?: string;
+ format?: string;
+};
+
+export type SpeechSynthesizeResult = {
+ path: string;
+ mimeType: string;
+ /** Bounded playback payload; omitted when the file is larger than the cap. */
+ dataUrl?: string;
+};