Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: real media generation (images, speech, video, music); chat view, picker and composer fixes (ADR-042)
Salman Qureshi296741c93ff0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c9d20af8..9aecefed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,41 @@## Unreleased+### Video and music+- **Mercury makes videos and music.** Ask in your own words, use the desktop chat box's **Create** menu (it replaces the Image button; image, video or music), or type `/video <the shot>` (`--portrait`, `--seconds 6`) or `/music <style, mood, lyrics>` (`--instrumental`, `--seconds 60`).+ - They take a minute or a few. Mercury says it has started and posts the clip or song into the same chat when it's ready, even if you've moved on. The desktop app shows it as a new message with a player, Telegram and WhatsApp receive the file, and the terminal shows where it was saved.+ - `/media jobs` lists what's being made. Stop also stops the video or song that chat is making.+- **Where they come from:**+ - **Video:** Gemini Omni (3–15 s with sound, from a Gemini key in Settings → Voice), or video models on gateways that serve the OpenAI Videos API (LiteLLM, Mercury Cloud once it adds it).+ - **Music:** Gemini Lyria (clips and full songs), or ElevenLabs Music (from an ElevenLabs key).+ - **Images too:** a Gemini key also brings Gemini's image models (Nano Banana).+ - **Choosing:** pick defaults in Settings → AI → Media or with `/media video <n>` and `/media music <n>`.+- **No dead ends.** When a provider says your account has no quota for a model (a free tier, no billing), Mercury skips that model in automatic picks for a day and uses the next one. `/media` marks it as skipped.+- If Mercury restarts while a video or song is being made, that chat is told to ask again, instead of waiting forever.++### Speech and voice notes+- **Voice notes both ways in Telegram.** Send Mercury a voice note and it's transcribed and answered, as WhatsApp already did. Replies come back as a voice note too, as Telegram's real voice-note bubble, not an audio file. By default this happens when you sent a voice note; `/media replies always` speaks every reply, `/media replies off` never does. The text reply always comes as well. WhatsApp follows the same setting.+- **`/say <text>`** speaks it, as a voice note in chat apps and as audio in the apps (add `--style "calm"`). Or just ask: "send me a voice note", "read this out loud", "narrate this".+- **Choose what speaks and in which voice** in Settings → AI → **Media** (the Images page, renamed), or with `/media speech <number>` and `/media voice <name>`.+ - The choices are OpenAI, Gemini, Deepgram, ElevenLabs, or a text-to-speech model found on your providers (OpenAI's `tts-1`/`gpt-4o-mini-tts`, LiteLLM, Mercury Cloud).+ - A style ("warm", "excited") is followed by OpenAI's newer voices and Gemini.+ - Reading replies aloud in the apps uses the same choice. With none set, everything follows Settings → Voice, as before.+- Gemini and ElevenLabs audio is turned into a voice note with ffmpeg when it is installed. Without ffmpeg it is sent as an audio file.++### Images+- **Mercury makes real images.** Ask for a picture in your own words, use the new **Image** button in the Mercury Desktop chat box (square, landscape or portrait), or type `/image <what to draw>` in the terminal, Telegram, WhatsApp, Discord, Slack or Signal. An image model draws it; Mercury no longer writes an SVG when you asked for a picture (it still does when you ask for SVG, a diagram or a chart).+- **Edit what you made.** "Make it blue", or send a photo with `/image make this a watercolor`: the earlier image (or yours) goes to the model as a reference.+- **Found on your providers, automatically.**+ - OpenAI (gpt-image, DALL·E), OpenRouter (Gemini image, FLUX, Seedream…), LiteLLM, AI/ML API, Atlas Cloud, Runcrate and Ollama image models are listed without any setup.+ - Mercury Cloud models appear once its model list says which ones make images.+ - Pick the default in Settings → AI → **Images**, or with `/media` (`/media image 2`, `/media image auto`). Automatic prefers the provider you chat with.+ - If a model fails, the next one is tried.+- **Delivered where you asked.**+ - The desktop app shows the image in the reply and keeps it in Artifacts.+ - Telegram, WhatsApp, Discord, Slack and Signal receive it as a photo.+ - The terminal prints where it was saved: the chat's artifacts folder, or `~/mercury-artifacts/Images`.+- Telegram no longer tries to send SVG or BMP files, or photos over 10 MB, as photos (Telegram rejects them); they go as files, and GIFs as animations.+### Seeing Mercury work- **A reply reads top to bottom as it happens.** In Mercury Desktop the thinking, each tool it runs, the answer and any notes appear in order at the bottom of the chat, where you already are. Before, the activity sat above the answer and scrolled out of view as the answer grew.- **Tools show while they run.** Each tool appears when it starts, with a live timer, and gets a tick or an error with the real duration when it ends. Before, a tool appeared only after it had finished, so a long command showed nothing. Failures show their reason, and long runs fold earlier steps away.diff --git a/DECISIONS.md b/DECISIONS.mdindex b5cc2ef9..bd28b72b 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -511,3 +511,93 @@- **Rejected:**- A probe request on every startup (cost, and side effects on metered gateways).- Treating every OpenAI-compatible model as effort-capable (a wrong guess would cost a 400 on the first request of every chat).++## ADR-042: Media generation is a tool the chat model calls, with models discovered per provider (phase 1: images)++- **Context**:+ - **Mercury could not make an image.** Asked for one, the chat model's only option was `create_file`, so it wrote an SVG. The artifact classifier then filed the SVG as an "image".+ - **The pieces existed but were unused.** Text-to-speech existed only for read-aloud. The AI SDK's image, speech and video functions were installed and unused. Provider model listings already saw image and video models, and filtered them out.+ - **Prior art:**+ - Open WebUI, LibreChat, Hermes and OpenClaw expose generation as tools the chat model calls, with a default model per modality. Image models never enter the chat-model picker.+ - ChatGPT and Gemini use the same pattern, with a composer entry point as an intent hint.+ - OpenClaw resolves models in this order: per-call → primary → fallbacks → auto-detected from configured auth.+ - **Model ids churn.** In 2026 alone, OpenAI's Sora API, Imagen and the Gemini API's Veo preview were retired. Ids cannot be hard-coded.+- **Decision** (phase 1: images; speech and video follow the same shape):+ - **One tool, `generate_image`.** It takes a prompt, aspect (square/landscape/portrait), quality, count (≤4) and `reference_images` (paths, for edits), plus an optional explicit model.+ - It is registered whenever filesystem tools are.+ - With no model available it returns a clear "no image model is set up" error, so the model reports the problem instead of drawing code.+ - A system-prompt line routes picture requests to it, and keeps SVG for SVG, diagrams and charts.+ - **Discovery** (`media/catalog.ts`) lists image models per configured provider, cached for a day; a provider that can't be reached keeps its last answer:+ - OpenRouter: `?output_modalities=image`, generated through chat with `modalities: ["image","text"]`.+ - LiteLLM: `mode: image_generation`.+ - Any `/models`: `output_modalities` ∋ image, `type` ∋ image-generation, or a known image-model name.+ - Ollama: `/api/tags` names.++ Dated snapshots are hidden when the plain id exists.+ - **Two wire formats** (`media/image.ts`) cover every provider Mercury has:+ - **OpenAI Images API:** `/images/generations`, and `/images/edits` as multipart. Results come back as `b64_json` or a URL.+ - **OpenRouter chat:** images come back as data URLs in `message.images`.++ Providers expose `mediaEndpoint()` (base URL + auth): OpenAI-compatible providers from their config; Mercury Cloud with a fresh JWT and its agent header.+ - **Resolution** (`media/service.ts`), at most three tried, each failure handing over to the next:+ 1. the requested model;+ 2. the owner's default, then its fallbacks (`media-prefs.json`, not `mercury.yaml`, which the agent rewrites);+ 3. automatic: the chat provider first, then better-known families.+ - **Results are files.** They are saved to the chat's artifacts folder, or `<artifacts>/Images` for the terminal. The tool result names the path (for later edits).+ - The artifact collector treats them as delivered.+ - Chat channels receive them through their own `sendFile`.+ - Apps show them through the existing artifacts event.+ - **Explicit requests:**+ - `/image [--landscape|--portrait] [--model ref] <prompt>`, and the desktop composer's Image switch (`POST /api/chat/send { media }`), keep the chat model in the turn but tell it to call `generate_image` first. Attached images are passed as reference candidates.+ - `/media` shows and sets the default (by number, ref, or `auto`).+ - `GET /api/media/models` and `PUT /api/media/default` serve Settings → AI → Images.+- **Consequences**:+ - Image requests produce images on any setup with an image-capable provider (verified live: OpenAI `gpt-image-1-mini`, 11 s). Without one, the user is told how to add one instead of getting SVG.+ - **Mercury Cloud** needs two backend changes, outside this repo, before its image models appear:+ - its `/v1/models` must carry `output_modalities` (or a `type`);+ - it must serve `/v1/images/generations` and `/v1/images/edits`.+ - **Not in phase 1:**+ - ChatGPT sign-in image generation (Codex backend `image_generation` tool).+ - A Google/Gemini provider.+ - Speech and voice notes (phase 2).+ - Video as background jobs, then music (phase 3).+ - Per-channel size limits and transcoding (WhatsApp 5 MB images).+- **Phase 2 (speech and voice notes):**+ - **What speaks: one choice for everything.** That covers `generate_speech`, `/say`, voice-note replies and read-aloud (`/api/speak`).+ - The owner's pick (`media-prefs.json` `speech.choice`) is either a direct service with a key (OpenAI, Gemini, Deepgram, ElevenLabs) or a text-to-speech model found on a provider: LiteLLM `mode: audio_speech`, `/models` with `output_modalities` ∋ speech, `type` text-to-speech, or a TTS name.+ - With no pick, the Settings → Voice service applies, as read-aloud always did.+ - Provider models are called through OpenAI `/audio/speech` with the provider's `mediaEndpoint()` auth, so Mercury Cloud works once it serves the route.+ - **Synthesis** (`plugins/speak.ts`) gains a voice, a style (OpenAI's instructable models; Gemini as words in front; never sent to `tts-1`) and an Ogg/Opus format.+ - Ogg/Opus is native from OpenAI (`opus`) and Deepgram (`container=ogg`).+ - Gemini WAV and ElevenLabs MP3 are converted with ffmpeg when present, and otherwise left as they are (then sent as audio).+ - **`generate_speech`** speaks given text into the chat folder: Ogg/Opus in chat apps, MP3 elsewhere. Delivery and artifacts work as for images. `/say [--style …] <text>` routes to it with the exact words.+ - **Voice notes:**+ - Telegram transcribes incoming voice and audio messages (the Settings → Voice listener, files up to 20 MB) and marks them `voiceNote`, as the WhatsApp bridge already did.+ - Telegram sends `.ogg/.oga/.opus` with `sendVoice`, falling back to `sendAudio`.+ - After a chat-app reply is delivered, `speech.replies` decides whether a spoken version follows: `mirror` (default: when they sent a voice note), `always` or `off`.+ - The spoken text is the reply without markdown or code, cut at a sentence near 1500 characters with "The rest is in the message".+ - It is best effort and never fails the turn.+ - **Surfaces:** `/media speech|voice|replies`; Settings → AI → Media (Images + Speech); `GET /api/media/models` `speech`; `PUT /api/media/speech`.+ - **Still open:** realtime voice is unchanged (Optimus); ElevenLabs voices are entered by id, not listed.+- **Phase 3 (video and music as background jobs):**+ - **Sources:**+ - A Gemini key (Settings → Voice) is a media source of its own (`media/key-sources.ts`). Its `models.list` gives images (generateContent with `responseModalities: ["TEXT","IMAGE"]`, `imageConfig.aspectRatio`), Omni video, and Lyria music. Lyria RealTime is a live stream, not a file, and is left out.+ - Omni and Lyria are called through the Interactions API (`POST /v1beta/interactions`). Omni takes `response_format {type: "video", aspect_ratio, resolution, duration}`. Lyria takes length and "instrumental" in the prompt, with header `Api-Revision: 2026-05-20`. Both return their output inline in `steps[type=model_output].content`.+ - An ElevenLabs key gives ElevenLabs Music: `POST /v1/music` with `music_length_ms`, `force_instrumental` and `model_id`.+ - Gateways serve video through the OpenAI Videos API shape: create, poll `/videos/{id}`, then `/videos/{id}/content`. Discovery uses LiteLLM `mode: video_generation`, `output_modalities` ∋ video, or a video-model name.+ - **Jobs** (`media/jobs.ts`): `generate_video` and `generate_music` check that a model exists, start a job and end the turn ("do not wait").+ - The job runs the fallback chain (at most three models) with a 15-minute (video) or 10-minute (music) bound, saves the file into the chat's folder, and is delivered exactly once by `Agent.deliverMediaJob`:+ - **Apps:** artifact, a stored assistant message, and an SSE `media_ready` event. This is a message of its own, so a turn running in that chat is untouched.+ - **Chat apps:** a note, then `sendFile`.+ - **Terminal:** a notice with the path.+ - Jobs persist in `media-jobs.json`. On start, the process that owns the runtime (never a terminal attached to the daemon) marks still-running jobs as failed and tells their chats, because the HTTP call died with the old process.+ - `/stop` in a chat aborts its jobs; `/halt` aborts all of them.+ - **No-quota models:** a provider answer such as "limit: 0 … Free Tier", "insufficient_quota" or "billing required" marks the model unusable for 24 h. Automatic picks and the shown automatic choice skip it; a model named explicitly is still tried.+ - Found live: a free-tier Gemini key lists Omni, Lyria and image models, but each answers 429 with limit 0. Without this rule, every automatic request would fail first.+ - **Surfaces:**+ - `/video`, `/music` (`/song`), `/media video|music <n|auto>`, `/media jobs`.+ - The desktop composer's Create menu (image, video or music; `POST /api/chat/send { media: {kind} }`).+ - Settings → AI → Media sections for video and music, backed by `GET /api/media/models` `video`/`music` and `PUT /api/media/default { kind }`.+ - **Verified live:** ElevenLabs Music (5 s, 4.2 s).+ - **Shapes taken from the current docs, not confirmed live:** the Gemini Omni and Lyria request shapes (the test key is on the free tier, with no quota for them).+ - **Implemented to the OpenAI shape, not exercised live:** the gateway Videos API.diff --git a/apps/desktop/src/api/artifacts.ts b/apps/desktop/src/api/artifacts.tsindex 1ca2a43e..1ed3c525 100644--- a/apps/desktop/src/api/artifacts.ts+++ b/apps/desktop/src/api/artifacts.ts@@ -4,7 +4,7 @@ import { apiUrl, authHeaders, http } from "./client";export type ArtifactKind = "image" | "video" | "audio" | "pdf" | "document" | "text" | "file";/** What a chat message carries about its artifacts. */-export interface ArtifactRef { id: string; name: string; kind: ArtifactKind; mime: string; size: number; path: string }+export interface ArtifactRef { id: string; name: string; kind: ArtifactKind; mime: string; size: number; path: string; tool?: string }export interface ArtifactItem {id: string;diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.tsindex acc7773d..df480b2f 100644--- a/apps/desktop/src/api/mercury.ts+++ b/apps/desktop/src/api/mercury.ts@@ -4,7 +4,7 @@═══════════════════════════════════════════════════════════════ */import { http, ApiError } from "./client";-import type { ChatEffort, TurnsInfo } from "./types";+import type { ChatEffort, ImageIntent, MediaModelsResponse, TurnsInfo, VoiceReplies } from "./types";import type { CommandEntry } from "~/views/chat/picker";import type { SkillDraft,BotApproval, BotInboxEntry, BotManifest, BotPlan, CrewSpec, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,@@ -75,8 +75,8 @@ export const chat = {createThread: (title?: string) => http.post<ChatThread>("/api/chat/threads", { title }),renameThread: (id: string, title: string) => http.put<{ id: string; title: string }>(`/api/chat/threads/${encodeURIComponent(id)}/title`, { title }),deleteThread: (id: string) => http.post<{ deleted: boolean }>(`/api/chat/threads/${encodeURIComponent(id)}/delete`, { confirmSessionId: id }),- send: (content: string, sessionId?: string, attachments?: Array<{ name: string; data: string }>, code?: { programming: string; cwd?: string }) =>- http.post<{ sent: boolean; sessionId: string }>("/api/chat/send", { content, sessionId, ...(attachments?.length ? { attachments } : {}), ...(code ?? {}) }),+ send: (content: string, sessionId?: string, attachments?: Array<{ name: string; data: string }>, code?: { programming: string; cwd?: string }, media?: ImageIntent) =>+ http.post<{ sent: boolean; sessionId: string }>("/api/chat/send", { content, sessionId, ...(attachments?.length ? { attachments } : {}), ...(code ?? {}), ...(media ? { media } : {}) }),/*** Interrupt a running turn (same as /stop). With a thread, only that chat's* turn stops (runtimes that run chats at once); without one, everything.@@ -107,6 +107,8 @@ export const chat = {settings: () => http.get<ChatSettings>("/api/chat/settings"),updateSettings: (patch: Partial<ChatSettings>) => http.put<ChatSettings>("/api/chat/settings", patch),models: (sessionId?: string | null) => http.get<ModelsResponse>(`/api/chat/models${sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : ""}`),+ /** The reply this chat is working on now, as far as it got (runtimes from ADR-041 on). */+ live: (id: string) => http.get<{ running: boolean; startedAt?: number; activity?: string; trace?: unknown; text?: string }>(`/api/chat/threads/${encodeURIComponent(id)}/live`),/** This chat's effort: a level, "auto", or null for the model's default (#188). */setEffort: (sessionId: string, level: ReasoningChoice | null) => http.post<{ ok: boolean; effort: ChatEffort }>("/api/chat/effort", { sessionId, level }),switchModel: (provider: string, model?: string) => http.post<{ ok: boolean; message: string }>("/api/chat/models/switch", { provider, model }),@@ -205,3 +207,11 @@ export const skills = {};export type { ChatMessage };++/** Image models on the configured providers, and the default (ADR-042). */+export const media = {+ models: (refresh = false) => http.get<MediaModelsResponse>(`/api/media/models${refresh ? "?refresh=1" : ""}`),+ setDefault: (ref: string | null, kind: "image" | "video" | "music" = "image") => http.put<{ ok: boolean }>("/api/media/default", { kind, ref }),+ /** Speaking: what speaks, the voice, and when chat-app replies come as voice notes. null clears. */+ setSpeech: (update: { choice?: string | null; voice?: string | null; replies?: VoiceReplies }) => http.put<{ ok: boolean }>("/api/media/speech", update),+};diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.tsindex 06fbde72..79f2f1ae 100644--- a/apps/desktop/src/api/types.ts+++ b/apps/desktop/src/api/types.ts@@ -181,6 +181,17 @@ export interface ThoughtStep {endedAt?: number;/** How long the tool ran (the runtime's own measure where it sent one). */durationMs?: number;+ /** A media tool: what it is making, for a placeholder of the right shape. */+ media?: { kind: "image" | "video" | "music" | "speech"; aspect?: string; count?: number; prompt?: string };+}++/** A video or song being made in the background for this chat (arrives with media_ready). */+export interface PendingMedia {+ jobId: string;+ kind: "video" | "music";+ aspect?: string;+ prompt: string;+ startedAt: number;}/** One entry of a turn's timeline, in the order it happened. */@@ -235,6 +246,8 @@ export interface ChatEffort {}export interface ModelsResponse {+ /** Lookups that failed, in words ("Mercury Cloud sign-in expired…"). */+ notices?: string[];current: { name: string; model: string; effort?: ChatEffort } & ModelDescription;providers: ({ name: string; model: string; available: boolean; isCurrent?: boolean } & ModelDescription)[];}@@ -542,3 +555,57 @@ export interface TurnsInfo {running: Array<TurnChat & { startedAt: number; activity: string; steps: number }>;waiting: Array<TurnChat & { waiting: number; position: number }>;}++/* ── Media generation (ADR-042) ── */++export type ImageAspect = "square" | "landscape" | "portrait";++/** The composer's Create menu: this message asks for an image, a video or music. */+export interface ImageIntent {+ kind: "image" | "video" | "music";+ aspect?: ImageAspect;+}++/** Models of one kind on the configured providers, the default and the automatic pick. */+export interface MediaKindInfo {+ models: MediaModelInfo[];+ default: { ref: string; available: boolean } | null;+ auto: { ref: string; label: string; group: string } | null;+}++export interface MediaModelInfo {+ /** "provider::model" */+ ref: string;+ provider: string;+ model: string;+ label: string;+ group: string;+ canEdit: boolean;+}++export interface SpeechOptionInfo {+ /** "openai" | "gemini" | "deepgram" | "elevenlabs", or "provider::model". */+ id: string;+ label: string;+ group: string;+ voices: string[];+}++export type VoiceReplies = "off" | "mirror" | "always";++export interface SpeechInfo {+ options: SpeechOptionInfo[];+ current: { id: string; label: string; voice: string | null } | null;+ /** The owner's pick; null follows Settings → Voice. */+ choice: string | null;+ voice: string | null;+ replies: VoiceReplies;+}++export interface MediaModelsResponse {+ /** Runtimes before phase 2 send no speech part, before phase 3 no video or music. */+ speech?: SpeechInfo | null;+ image: MediaKindInfo;+ video?: MediaKindInfo;+ music?: MediaKindInfo;+}diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.tsindex 1069d2c3..95adc5b6 100644--- a/apps/desktop/src/app/conversation.ts+++ b/apps/desktop/src/app/conversation.ts@@ -33,6 +33,9 @@ export interface ConversationState {waiting: { position: number; busyWith?: string; busySessionId?: string } | null;setWaiting(waiting: ConversationState["waiting"]): void;setStopping(stopping: boolean): void;+ /** Videos and songs being made in the background for this chat: placeholders until they arrive. */+ pendingMedia: import("~/api/types").PendingMedia[];+ setPendingMedia(update: (list: import("~/api/types").PendingMedia[]) => import("~/api/types").PendingMedia[]): void;/** An effort picked before this chat existed: applied when its thread is created. */pendingEffort?: import("~/api/types").ReasoningChoice;setPendingEffort(level: import("~/api/types").ReasoningChoice | undefined): void;@@ -87,6 +90,8 @@ function makeConversation(surface: Surface): ConversationStore {setStopping: (stopping) => set({ stopping }),draft: null,setDraft: (draft) => set({ draft }),+ pendingMedia: [],+ setPendingMedia: (update) => set((s) => ({ pendingMedia: update(s.pendingMedia) })),pendingEffort: undefined,setPendingEffort: (pendingEffort) => set({ pendingEffort }),plan: null,@@ -99,7 +104,7 @@ function makeConversation(surface: Surface): ConversationStore {setNotice: (notice) => set({ notice }),setLive: (update) => set((s) => ({ live: update(s.live ?? newTrace()) })),clearLive: () => set({ live: null }),- setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null, stopping: false, plan: null, research: null, researchPlan: null, notice: null, pendingEffort: undefined }),+ setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null, stopping: false, plan: null, research: null, researchPlan: null, notice: null, pendingEffort: undefined, pendingMedia: [] }),setMessages: (messages) => set({ messages }),addMessage: (message) => set((s) => ({ messages: [...s.messages, message] })),appendStreaming: (text) => set((s) => ({ streaming: s.streaming + text })),diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.tsindex bc3c013c..519d40fb 100644--- a/apps/desktop/src/app/events.ts+++ b/apps/desktop/src/app/events.ts@@ -9,12 +9,12 @@ import { useEffect } from "react";import { openStream } from "~/api/stream";import * as api from "~/api/mercury";import { ApiError, http } from "~/api/client";-import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, PendingPrompt, ReplyUsage, ResearchPlanPrompt, ResearchSnapshot } from "~/api/types";+import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, ImageIntent, PendingMedia, PendingPrompt, ThoughtTrace, ReplyUsage, ResearchPlanPrompt, ResearchSnapshot } from "~/api/types";import { useBots, useChat, useRuntimeState, type AgentState } from "./store";-import { conversations, useCodeSessions, type ConversationStore, type Surface } from "./conversation";+import { conversations, useCodeSessions, type ConversationState, type ConversationStore, type Surface } from "./conversation";import type { ArtifactRef } from "~/api/artifacts";import { useNotify } from "./notify/store";-import { addNote, addReasoning, addText, endReasoning, finishTool, finishTrace, hasProcess, markStopped, newTrace, normalizeMessages, setPhase, startTool } from "./trace";+import { addNote, addReasoning, addText, endReasoning, finishTool, finishTrace, hasProcess, liveFromSnapshot, markStopped, newTrace, normalizeMessages, setPhase, startTool } from "./trace";export function useRuntimeEvents(enabled: boolean): void {const chatId = conversations.chat((s) => s.activeId);@@ -187,6 +187,21 @@ export function handleEvent(store: ConversationStore, event: string, raw: stringif (conv.live || conv.agent !== "idle") conv.setLive((l) => setPhase(l, label));}break;+ case "media_pending": {+ // A video or song started in the background: hold its place until it arrives.+ if (typeof data.jobId !== "string") break;+ const job = { jobId: data.jobId, kind: data.kind === "music" ? "music" as const : "video" as const, prompt: String(data.prompt ?? ""), startedAt: Number(data.startedAt) || Date.now(), ...(typeof data.aspect === "string" ? { aspect: data.aspect } : {}) };+ conv.setPendingMedia((list) => [...list.filter((p) => p.jobId !== job.jobId), job]);+ break;+ }+ case "media_ready": {+ // A video or song made in the background (after its turn ended): its own message.+ if (typeof data.jobId === "string") conv.setPendingMedia((list) => list.filter((p) => p.jobId !== data.jobId));+ const items = Array.isArray(data.artifacts) ? (data.artifacts as ArtifactRef[]) : [];+ conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: String(data.text ?? ""), timestamp: new Date().toISOString(), ...(items.length ? { artifacts: items } : {}) });+ void refreshThreads();+ break;+ }case "progress":// "Checking my work…": a note inside the running turn, not its reply.if (typeof data.text === "string" && data.text.trim()) conv.setLive((l) => addNote(l, data.text as string));@@ -236,6 +251,7 @@ export function handleEvent(store: ConversationStore, event: string, raw: stringtitle: typeof data.title === "string" ? data.title : undefined,label: String(data.label ?? tool),step: Number(data.step) || undefined,+ ...(data.media && typeof data.media === "object" ? { media: data.media as ThoughtTrace["steps"][number]["media"] } : {}),}));break;}@@ -398,10 +414,57 @@ export async function refreshBots(): Promise<void> {} catch { /* bots unavailable on this runtime */ }}+/**+ * A chat's running reply as the screen showed it, kept when you switch+ * away, so coming back shows it at once (the runtime's snapshot then+ * brings it up to date).+ */+const leftMidTurn = new Map<string, { live: ThoughtTrace | null; streaming: string; agent: AgentState; step: ConversationState["step"] }>();++function busy(agent: AgentState): boolean {+ return agent === "thinking" || agent === "working" || agent === "streaming";+}++/** The runtime's snapshot of a reply still being worked on, onto the screen. */+async function restoreRunningTurn(store: ConversationStore, id: string): Promise<void> {+ let snap: { running: boolean; startedAt?: number; activity?: string; trace?: unknown; text?: string };+ try {+ snap = await api.chat.live(id);+ } catch {+ return; // older Mercury: what was kept on screen stays+ }+ const s = store.getState();+ if (s.activeId !== id) return;+ if (!snap.running) {+ // It finished while you were away: the reply is in the messages now.+ if (busy(s.agent) && !s.waiting) { s.clearLive(); s.clearStreaming(); s.setAgent(s.prompts.length ? "needs-you" : "idle"); }+ return;+ }+ const live = liveFromSnapshot(snap.trace, snap.text ?? "", snap.startedAt ?? Date.now(), snap.activity);+ s.setLive(() => live);+ if (snap.text) { s.clearStreaming(); s.appendStreaming(snap.text); }+ const running = live.steps.some((st) => st.status === "running");+ if (!s.prompts.length) s.setAgent(running ? "working" : snap.text ? "streaming" : "thinking");+}+export async function openThread(surface: Surface, id: string | null): Promise<void> {const store = conversations[surface];+ // Leaving a chat mid-reply: keep what it showed.+ const before = store.getState();+ if (before.activeId && before.activeId !== id && (before.live || busy(before.agent))) {+ leftMidTurn.set(before.activeId, { live: before.live, streaming: before.streaming, agent: before.agent, step: before.step });+ }store.getState().setActive(id);store.getState().clearStreaming();+ // Coming back to one: show it straight away, then ask the runtime how far it got.+ const kept = id ? leftMidTurn.get(id) : undefined;+ if (id && kept) {+ leftMidTurn.delete(id);+ if (kept.live) store.getState().setLive(() => kept.live!);+ if (kept.streaming) store.getState().appendStreaming(kept.streaming);+ store.getState().setAgent(kept.agent);+ store.getState().setStep(kept.step);+ }if (!id) {store.getState().setMessages([]);return;@@ -443,6 +506,12 @@ export async function openThread(surface: Surface, id: string | null): Promise<vtry {const thread = await api.chat.thread(id);store.getState().setMessages(normalizeMessages(thread.messages ?? []));+ // A reply still being worked on (here or from another device): show it as far as it got.+ await restoreRunningTurn(store, id);+ // Videos or songs still being made for this chat: their placeholders.+ void http.get<{ jobs?: PendingMedia[] }>(`/api/media/jobs?sessionId=${encodeURIComponent(id)}`)+ .then((r) => { if (store.getState().activeId === id) store.getState().setPendingMedia(() => r.jobs ?? []); })+ .catch(() => { /* older Mercury */ });} catch {store.getState().setMessages([]);} finally {@@ -455,7 +524,7 @@ export interface CodeTurn {folder: string | null;}-export async function sendMessage(surface: Surface, content: string, attachments: Array<{ name: string; data: string; mime?: string }> = [], code?: CodeTurn): Promise<void> {+export async function sendMessage(surface: Surface, content: string, attachments: Array<{ name: string; data: string; mime?: string }> = [], code?: CodeTurn, media?: ImageIntent): Promise<void> {const store = conversations[surface];let id = store.getState().activeId;if (!id) {@@ -484,7 +553,7 @@ export async function sendMessage(surface: Surface, content: string, attachmentsstore.getState().addMessage(optimistic);store.getState().setAgent("thinking");store.getState().setLive(() => newTrace());- await api.chat.send(content, id, attachments.map(({ name, data }) => ({ name, data })), code ? { programming: code.mode, cwd: code.folder ?? undefined } : undefined);+ await api.chat.send(content, id, attachments.map(({ name, data }) => ({ name, data })), code ? { programming: code.mode, cwd: code.folder ?? undefined } : undefined, media);void refreshThreads();}diff --git a/apps/desktop/src/app/live-restore.test.ts b/apps/desktop/src/app/live-restore.test.tsnew file mode 100644index 00000000..ea16cb18--- /dev/null+++ b/apps/desktop/src/app/live-restore.test.ts@@ -0,0 +1,74 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++/**+ * Switching chats mid-reply and coming back shows the reply as far as it+ * got: what the screen had at once, then the runtime's snapshot.+ */+const live = vi.fn();+const thread = vi.fn();+// Every other call openThread makes (research, plan…) answers nothing.+vi.mock("~/api/mercury", () => ({+ chat: new Proxy({ live: (id: string) => live(id), thread: (id: string) => thread(id) } as Record<string, unknown>, {+ get: (t, k: string) => t[k] ?? (async () => ({})),+ }),+}));+vi.mock("~/api/client", () => ({ http: { get: async () => ({}) }, ApiError: class extends Error {} }));++const { conversations } = await import("./conversation");+const { handleEvent, openThread } = await import("./events");+const { liveFromSnapshot } = await import("./trace");+const store = conversations.chat;+const ev = (type: string, data: Record<string, unknown> = {}) => handleEvent(store, type, JSON.stringify(data));++describe("coming back to a chat mid-reply", () => {+ beforeEach(() => {+ live.mockReset(); thread.mockReset();+ store.setState({ activeId: "a", messages: [], streaming: "", live: null, agent: "idle", stopping: false, prompts: [], waiting: null, step: null });+ });++ it("shows the runtime's snapshot: thinking, the running step, the text so far", async () => {+ thread.mockResolvedValue({ messages: [{ id: "u", role: "user", content: "go", timestamp: "" }] });+ live.mockResolvedValue({+ running: true, startedAt: 1000, activity: "⚙️ Running npm test", text: "Half an answer",+ trace: { startedAt: 1000, endedAt: 2000, items: [+ { kind: "reasoning", text: "Planning.", startedAt: 1000, endedAt: 1500 },+ { kind: "tool", id: "c1", title: "Running npm test", status: "running", startedAt: 1500 },+ ] },+ });+ await openThread("chat", "b");+ const s = store.getState();+ expect(s.live?.items?.map((i) => i.kind)).toEqual(["reasoning", "step", "text"]);+ expect(s.live?.steps[0]).toMatchObject({ key: "c1", status: "running" });+ expect(s.streaming).toBe("Half an answer");+ expect(s.agent).toBe("working");+ // Live events carry on from there.+ ev("step_done", { id: "c1", tool: "run_command", summary: "passed", failed: false, durationMs: 4000 });+ expect(store.getState().live?.steps[0].status).toBe("done");+ });++ it("what the screen had is back at once when you return, before the runtime answers", async () => {+ store.setState({ activeId: "a", agent: "working" });+ ev("reasoning", { text: "Thinking about it." });+ ev("step_start", { id: "s1", tool: "read_file", title: "Reading a.ts" });+ thread.mockResolvedValue({ messages: [] });+ let answer!: (v: unknown) => void;+ const pending = new Promise((r) => { answer = r; });+ live.mockImplementation((id: string) => (id === "a" ? pending : Promise.resolve({ running: false })));+ await openThread("chat", "b"); // away+ expect(store.getState().live).toBeNull();+ const back = openThread("chat", "a"); // and back+ await Promise.resolve();+ expect(store.getState().live?.steps[0]).toMatchObject({ key: "s1", status: "running" });+ expect(store.getState().agent).toBe("working");+ answer({ running: false }); // it finished meanwhile+ await back;+ expect(store.getState().live).toBeNull();+ expect(store.getState().agent).toBe("idle");+ });++ it("a snapshot keeps thinking that is still streaming open", () => {+ const t = liveFromSnapshot({ startedAt: 1, endedAt: 2, items: [{ kind: "reasoning", text: "Hmm", startedAt: 1 }] }, "", 1);+ expect(t.items?.[0]).toEqual({ kind: "reasoning", text: "Hmm", startedAt: 1 });+ expect(t.endedAt).toBeUndefined();+ });+});diff --git a/apps/desktop/src/app/media-skeleton.test.ts b/apps/desktop/src/app/media-skeleton.test.tsnew file mode 100644index 00000000..b6378244--- /dev/null+++ b/apps/desktop/src/app/media-skeleton.test.ts@@ -0,0 +1,39 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++/**+ * Media on its way: a placeholder in the right shape while a picture or+ * voice is made in the reply, and one per video or song made in the+ * background until it arrives.+ */+vi.mock("~/api/mercury", () => ({ chat: {} }));++const { conversations } = await import("./conversation");+const { handleEvent } = await import("./events");+const { mediaPhase } = await import("~/components/MediaSkeleton");+const store = conversations.chat;+const ev = (type: string, data: Record<string, unknown> = {}) => handleEvent(store, type, JSON.stringify(data));++describe("media placeholders", () => {+ beforeEach(() => store.setState({ activeId: "a", messages: [], streaming: "", live: null, agent: "thinking", pendingMedia: [], prompts: [], waiting: null }));++ it("a picture being made: its step carries the shape for the placeholder", () => {+ ev("step_start", { id: "c1", tool: "generate_image", title: "Generating an image", media: { kind: "image", aspect: "portrait", count: 2, prompt: "a fox" } });+ expect(store.getState().live?.steps[0].media).toEqual({ kind: "image", aspect: "portrait", count: 2, prompt: "a fox" });+ });++ it("a video in the background holds its place until it arrives, then becomes a message", () => {+ ev("media_pending", { jobId: "j1", kind: "video", prompt: "a cat surfing", startedAt: 1000, aspect: "portrait" });+ ev("media_pending", { jobId: "j2", kind: "music", prompt: "lo-fi", startedAt: 1000 });+ expect(store.getState().pendingMedia.map((p) => p.jobId)).toEqual(["j1", "j2"]);+ ev("media_ready", { jobId: "j1", text: "🎬 Your video is ready.", artifacts: [{ id: "x", name: "cat.mp4", kind: "video", mime: "video/mp4", size: 1, path: "/p", tool: "generate_video" }] });+ expect(store.getState().pendingMedia.map((p) => p.jobId)).toEqual(["j2"]);+ expect(store.getState().messages.at(-1)?.artifacts?.[0].tool).toBe("generate_video");+ });++ it("the status moves on during a long wait, so it never reads as stuck", () => {+ expect(mediaPhase("image", 0)).toBe("Composing");+ expect(mediaPhase("image", 12_000)).toBe("Adding light and colour");+ expect(mediaPhase("image", 600_000)).toBe("Refining");+ expect(mediaPhase("video", 30_000)).toBe("Animating");+ });+});diff --git a/apps/desktop/src/app/trace.ts b/apps/desktop/src/app/trace.tsindex 17f6f678..d77315c9 100644--- a/apps/desktop/src/app/trace.ts+++ b/apps/desktop/src/app/trace.ts@@ -49,7 +49,7 @@ export function endReasoning(t: ThoughtTrace, now = Date.now()): ThoughtTrace {return { ...t, items: [...items.slice(0, -1), { ...last, endedAt: now }], reasoning: t.reasoning ? `${t.reasoning}\n\n` : t.reasoning, lastEventAt: now };}-export function startTool(t: ThoughtTrace, ev: { key?: string; tool: string; title?: string; label?: string; step?: number }, now = Date.now()): ThoughtTrace {+export function startTool(t: ThoughtTrace, ev: { key?: string; tool: string; title?: string; label?: string; step?: number; media?: ThoughtStep["media"] }, now = Date.now()): ThoughtTrace {const closed = endReasoning(t, now);const key = ev.key || `${ev.tool}:${now}:${closed.steps.length}`;if (closed.steps.some((s) => s.key === key)) return closed;@@ -59,6 +59,7 @@ export function startTool(t: ThoughtTrace, ev: { key?: string; tool: string; tittool: ev.tool,label: ev.label || ev.tool,...(ev.title ? { title: ev.title } : {}),+ ...(ev.media ? { media: ev.media } : {}),status: "running",startedAt: now,};@@ -155,7 +156,7 @@ const num = (v: unknown): number | undefined => (typeof v === "number" && Number* A reply's trace as the runtime keeps it ({startedAt, endedAt, items}) →* the screen's shape. A trace already in that shape passes through.*/-export function fromStored(raw: unknown): ThoughtTrace | undefined {+export function fromStored(raw: unknown, opts: { live?: boolean } = {}): ThoughtTrace | undefined {if (!raw || typeof raw !== "object") return undefined;const r = raw as { startedAt?: unknown; endedAt?: unknown; items?: unknown; reasoning?: unknown; steps?: unknown };if (typeof r.reasoning === "string" && Array.isArray(r.steps)) return raw as ThoughtTrace;@@ -165,7 +166,9 @@ export function fromStored(raw: unknown): ThoughtTrace | undefined {const parts: string[] = [];for (const it of r.items as StoredItem[]) {if (it?.kind === "reasoning" && typeof it.text === "string" && it.text.trim()) {- trace.items!.push({ kind: "reasoning", text: it.text, startedAt: num(it.startedAt) ?? startedAt, endedAt: num(it.endedAt) ?? startedAt });+ // A snapshot of a running reply may have thinking still streaming (no end yet).+ const endedAt = num(it.endedAt) ?? (opts.live ? undefined : startedAt);+ trace.items!.push({ kind: "reasoning", text: it.text, startedAt: num(it.startedAt) ?? startedAt, ...(endedAt !== undefined ? { endedAt } : {}) });parts.push(it.text.trim());} else if (it?.kind === "tool" && typeof it.id === "string") {const title = typeof it.title === "string" ? it.title : "";@@ -177,7 +180,7 @@ export function fromStored(raw: unknown): ThoughtTrace | undefined {tool: title.split(" ")[0] || "tool",label: title,title,- status: it.status === "error" ? "error" : "done",+ status: it.status === "error" ? "error" : it.status === "running" && opts.live ? "running" : "done",startedAt: at,...(durationMs !== undefined ? { durationMs, endedAt: at + durationMs } : {}),...(typeof it.summary === "string" ? { summary: it.summary } : {}),@@ -189,6 +192,25 @@ export function fromStored(raw: unknown): ThoughtTrace | undefined {return trace.items!.length ? trace : undefined;}+/**+ * A reply still being worked on, from the runtime's snapshot+ * (GET /api/chat/threads/:id/live): its thinking and steps so far, then the+ * text written so far, ready for live events to carry on from.+ */+export function liveFromSnapshot(raw: unknown, text: string, startedAt: number, activity?: string, now = Date.now()): ThoughtTrace {+ const base = fromStored(raw, { live: true }) ?? { ...newTrace(startedAt), startedAt };+ const items = [...(base.items ?? [])];+ if (text) items.push({ kind: "text", text });+ return {+ ...base,+ startedAt,+ endedAt: undefined,+ items,+ lastEventAt: now,+ ...(activity ? { phase: activity.replace(/^[^\p{L}\p{N}]+/u, "").trim() || undefined } : {}),+ };+}+/*** Messages from the runtime → the screen: stored traces normalised, and the* separate "used N tools" entry dropped where the reply carries the samediff --git a/apps/desktop/src/components/MediaSkeleton.tsx b/apps/desktop/src/components/MediaSkeleton.tsxnew file mode 100644index 00000000..6f214d20--- /dev/null+++ b/apps/desktop/src/components/MediaSkeleton.tsx@@ -0,0 +1,91 @@+import { Clapperboard, Image as ImageIcon, Music, AudioLines } from "lucide-react";+import { cx } from "~/lib/cx";+import { formatDuration } from "~/app/trace";++/* ═══════════════════════════════════════════════════════════════+ Media on its way (ADR-042): a placeholder in the shape of what is+ coming, so nothing jumps when it lands — a soft colour field drifting+ under a light sweep for pictures and video, moving bars for sound —+ with what it is doing now and for how long. Still under reduced motion.+ ═══════════════════════════════════════════════════════════════ */++export type MediaKind = "image" | "video" | "music" | "speech";++export interface MediaShape {+ kind: MediaKind;+ aspect?: string;+ count?: number;+ prompt?: string;+}++/** What it says while working: changes every few seconds so a long wait never reads as stuck. */+const PHASES: Record<MediaKind, string[]> = {+ image: ["Composing", "Sketching shapes", "Adding light and colour", "Adding detail", "Refining"],+ video: ["Setting up the shot", "Blocking the scene", "Animating", "Adding sound", "Rendering frames", "Finishing"],+ music: ["Finding the groove", "Writing the melody", "Arranging", "Mixing", "Mastering"],+ speech: ["Warming up the voice", "Speaking", "Polishing"],+};++const KIND_WORD: Record<MediaKind, string> = { image: "image", video: "video", music: "music", speech: "voice" };++/** The status line for a wait of `ms`. */+export function mediaPhase(kind: MediaKind, ms: number): string {+ const list = PHASES[kind];+ const step = kind === "video" || kind === "music" ? 12_000 : 5_000;+ return list[Math.min(Math.floor(ms / step), list.length - 1)];+}++function ratioOf(kind: MediaKind, aspect?: string): string {+ if (kind === "video") return aspect === "portrait" ? "9 / 16" : "16 / 9";+ if (aspect === "landscape") return "3 / 2";+ if (aspect === "portrait") return "2 / 3";+ return "1 / 1";+}++export function MediaSkeleton({ shape, startedAt, now, note, className }: { shape: MediaShape; startedAt: number; now: number; note?: string; className?: string }) {+ const elapsed = Math.max(0, now - startedAt);+ const status = `${mediaPhase(shape.kind, elapsed)}…`;+ const Icon = shape.kind === "video" ? Clapperboard : shape.kind === "music" ? Music : shape.kind === "speech" ? AudioLines : ImageIcon;+ const label = `Creating ${KIND_WORD[shape.kind]}`;++ if (shape.kind === "music" || shape.kind === "speech") {+ return (+ <div className={cx("media-skeleton flex w-full max-w-[420px] items-center gap-3 rounded-xl border border-line px-3.5 py-3", className)} role="status" aria-label={`${label}: ${status}`}>+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-accent/12 text-accent"><Icon size={16} /></span>+ <div className="min-w-0 flex-1">+ <div className="flex h-7 items-end gap-[3px]" aria-hidden="true">+ {Array.from({ length: 32 }, (_, i) => (+ <span key={i} className="media-bar block w-[3px] rounded-full bg-ink/25" style={{ height: `${30 + ((i * 37) % 70)}%`, animationDelay: `${(i % 8) * 0.11}s` }} />+ ))}+ </div>+ <div className="mt-1.5 flex items-center gap-2 text-xs text-ink3">+ <span className="shimmer-text truncate">{note ?? status}</span>+ <span className="ml-auto shrink-0 font-mono text-2xs text-ink4">{formatDuration(elapsed)}</span>+ </div>+ </div>+ </div>+ );+ }++ const tiles = Math.min(Math.max(shape.count ?? 1, 1), 4);+ return (+ <div className={cx("flex w-full flex-col gap-2", className)} role="status" aria-label={`${label}: ${status}`}>+ <div className={cx("grid gap-2", tiles > 1 ? "grid-cols-2" : "grid-cols-1")} style={{ maxWidth: tiles > 1 ? 520 : shape.kind === "video" && shape.aspect !== "portrait" ? 520 : 380 }}>+ {Array.from({ length: tiles }, (_, i) => (+ <div key={i} className="media-skeleton relative overflow-hidden rounded-xl border border-line" style={{ aspectRatio: ratioOf(shape.kind, shape.aspect) }}>+ <div className="media-aurora absolute inset-0" style={{ animationDelay: `${i * -2.3}s` }} aria-hidden="true" />+ <div className="media-sweep absolute inset-0" aria-hidden="true" />+ <div className="absolute inset-0 flex items-center justify-center" aria-hidden="true">+ <Icon size={28} className="media-icon text-ink/30" strokeWidth={1.5} />+ </div>+ </div>+ ))}+ </div>+ <div className="flex max-w-[520px] items-center gap-2 text-xs text-ink3">+ <span className="shimmer-text">{label} · {note ?? status}</span>+ <span className="ml-auto shrink-0 font-mono text-2xs text-ink4">{formatDuration(elapsed)}</span>+ </div>+ {shape.prompt && <p className="line-clamp-1 max-w-[520px] text-2xs text-ink4" title={shape.prompt}>{shape.prompt}</p>}+ </div>+ );+}diff --git a/apps/desktop/src/components/TurnTimeline.tsx b/apps/desktop/src/components/TurnTimeline.tsxindex b4b85e09..270d48c8 100644--- a/apps/desktop/src/components/TurnTimeline.tsx+++ b/apps/desktop/src/components/TurnTimeline.tsx@@ -7,6 +7,7 @@ import { Markdown } from "~/components/Markdown";import { StreamCaret } from "~/components/indicators/Thinking";import { Spinner } from "~/components/ui/bits";import { cx } from "~/lib/cx";+import { MediaSkeleton } from "~/components/MediaSkeleton";/* ═══════════════════════════════════════════════════════════════A turn as it happened, top to bottom: thinking, the tools it ran, the@@ -134,7 +135,11 @@ function StepGroup({ steps, live, now }: { steps: ThoughtStep[]; live: boolean;const hidden = all ? [] : steps.slice(0, Math.max(0, steps.length - SHOW_STEPS)).filter((s) => s.status !== "error" && s.status !== "running");const hiddenKeys = new Set(hidden);const shown = steps.filter((s) => !hiddenKeys.has(s));+ // A picture or voice being made in this reply: its placeholder until the reply lands+ // (the finished file arrives with it). Videos and songs have their own (PendingMedia).+ const making = live ? steps.filter((s) => s.media && (s.media.kind === "image" || s.media.kind === "speech") && s.status !== "error" && s.status !== "stopped") : [];return (+ <><ol className="flex flex-col gap-1">{hidden.length > 0 && (<li>@@ -146,6 +151,10 @@ function StepGroup({ steps, live, now }: { steps: ThoughtStep[]; live: boolean;)}{shown.map((s) => <StepRow key={s.key ?? `${s.id}-${s.startedAt}`} step={s} live={live} now={now} />)}</ol>+ {making.map((s) => (+ <MediaSkeleton key={`m-${s.key ?? s.id}`} shape={s.media!} startedAt={s.startedAt} now={now} note={s.status === "done" ? "Almost there…" : undefined} className="mt-1" />+ ))}+ </>);}@@ -188,17 +197,18 @@ const LONG_QUIET_MS = 120_000;/*** The line under a running turn: what is happening right now and how long- * the turn has taken. Hidden while the answer is visibly streaming.+ * the turn has taken. The only progress line (the chat box has none).*/export function LiveStatus({ trace, agent, stopping, now }: { trace: ThoughtTrace; agent: AgentState; stopping: boolean; now: number }) {const items = trace.items ?? [];const last = items[items.length - 1];const quietFor = now - (trace.lastEventAt ?? trace.startedAt);+ // Always shown while the turn runs: the one place that says what is happening.const writing = last?.kind === "text" && quietFor < 2500 && !stopping;- if (writing) return null;const step = runningStep(trace);const thinking = last?.kind === "reasoning" && !last.endedAt;const what = stopping ? "Stopping"+ : writing ? "Writing": step ? (step.title || step.label): thinking ? "Thinking": trace.phase ? trace.phasediff --git a/apps/desktop/src/components/artifacts/ArtifactCard.tsx b/apps/desktop/src/components/artifacts/ArtifactCard.tsxindex 4337fc0b..7e97169a 100644--- a/apps/desktop/src/components/artifacts/ArtifactCard.tsx+++ b/apps/desktop/src/components/artifacts/ArtifactCard.tsx@@ -47,12 +47,58 @@ export function ArtifactThumb({ id, kind, name, className }: { id: string; kind:}/** Under a reply: what this turn made, one tap from a preview. */-export function ArtifactStrip({ items, onOpenThread }: { items: ArtifactRef[]; onOpenThread?: (threadId: string) => void }) {+/** Made by a media model (generate_image, _video, _music, _speech): shown large and playable. */+function isGenerated(a: ArtifactRef): boolean {+ return !!a.tool?.startsWith("generate_") && (a.kind === "image" || a.kind === "video" || a.kind === "audio");+}++/**+ * A generated picture, clip or sound in the reply itself, where its+ * placeholder was (MediaSkeleton); `fresh` reveals it from soft to sharp.+ */+function GeneratedMedia({ a, fresh, onOpen }: { a: ArtifactRef; fresh: boolean; onOpen: () => void }) {+ const [url, setUrl] = useState<string | null>(null);+ useEffect(() => {+ let live = true;+ void artifactBlobUrl(a.id).then((u) => { if (live) setUrl(u); });+ return () => { live = false; };+ }, [a.id]);+ if (a.kind === "audio") {+ return (+ <div className={cx("flex w-full max-w-[420px] flex-col gap-1.5 rounded-xl border border-line bg-surface px-3 py-2.5", fresh && "media-reveal")}>+ {url ? <audio src={url} controls preload="metadata" className="h-9 w-full" /> : <div className="h-9" />}+ <button onClick={onOpen} className="truncate text-left text-xs text-ink4 hover:text-ink2">{a.name} · {formatBytes(a.size)}</button>+ </div>+ );+ }+ if (a.kind === "video") {+ return (+ <div className={cx("w-full max-w-[520px] overflow-hidden rounded-xl border border-line bg-black", fresh && "media-reveal")}>+ {url ? <video src={url} controls playsInline preload="metadata" className="block max-h-[480px] w-full" /> : <div className="aspect-video" />}+ </div>+ );+ }+ return (+ <button onClick={onOpen} title={a.name} className={cx("block max-w-[380px] overflow-hidden rounded-xl border border-line bg-soft", fresh && "media-reveal")}>+ {url ? <img src={url} alt={a.name} className="block h-auto w-full" draggable={false} /> : <div className="aspect-square w-[380px] max-w-full" />}+ </button>+ );+}++export function ArtifactStrip({ items, onOpenThread, fresh = false }: { items: ArtifactRef[]; onOpenThread?: (threadId: string) => void; fresh?: boolean }) {const [open, setOpen] = useState<string | null>(null);if (!items.length) return null;+ const media = items.filter(isGenerated);+ const rest = items.filter((a) => !isGenerated(a));return (- <div className="mt-3 flex flex-wrap gap-2" aria-label="Artifacts">- {items.map((a) => (+ <div className="mt-3 flex flex-col gap-2" aria-label="Artifacts">+ {media.length > 0 && (+ <div className={cx("grid gap-2", media.filter((a) => a.kind === "image").length > 1 ? "max-w-[520px] grid-cols-2" : "grid-cols-1")}>+ {media.map((a) => <GeneratedMedia key={a.id} a={a} fresh={fresh} onOpen={() => setOpen(a.id)} />)}+ </div>+ )}+ {rest.length > 0 && <div className="flex flex-wrap gap-2">+ {rest.map((a) => (<button key={a.id} onClick={() => setOpen(a.id)} title={a.path}className="group flex w-[220px] items-center gap-2.5 overflow-hidden rounded-xl border border-line bg-surface p-1.5 pr-3 text-left transition-colors hover:border-ink/25"><span className="h-12 w-12 shrink-0 overflow-hidden rounded-lg"><ArtifactThumb id={a.id} kind={a.kind} name={a.name} /></span>@@ -62,6 +108,7 @@ export function ArtifactStrip({ items, onOpenThread }: { items: ArtifactRef[]; o</span></button>))}+ </div>}<Dialog open={!!open} onOpenChange={(o) => { if (!o) setOpen(null); }} title="Artifact" width={860}>{open && <div className="-m-5 h-[70vh]"><ArtifactViewer id={open} onOpenThread={onOpenThread ? (t) => { setOpen(null); onOpenThread(t); } : undefined} onDeleted={() => setOpen(null)} /></div>}</Dialog>diff --git a/apps/desktop/src/components/ui/Menu.tsx b/apps/desktop/src/components/ui/Menu.tsxindex 298761b6..9a7a96e4 100644--- a/apps/desktop/src/components/ui/Menu.tsx+++ b/apps/desktop/src/components/ui/Menu.tsx@@ -3,16 +3,25 @@ import { Check } from "lucide-react";import type { ReactNode } from "react";import { cx } from "~/lib/cx";-export function Menu({ trigger, children, align = "start", side = "bottom" }: { trigger: ReactNode; children: ReactNode; align?: "start" | "center" | "end"; side?: "top" | "bottom" | "left" | "right" }) {+export function Menu({ trigger, children, align = "start", side = "bottom", className, onOpenChange }: {+ trigger: ReactNode;+ children: ReactNode;+ align?: "start" | "center" | "end";+ side?: "top" | "bottom" | "left" | "right";+ /** Extra classes for the open menu (a width, no padding…). */+ className?: string;+ onOpenChange?: (open: boolean) => void;+}) {return (- <Dropdown.Root>+ <Dropdown.Root onOpenChange={onOpenChange}><Dropdown.Trigger asChild>{trigger}</Dropdown.Trigger><Dropdown.Portal><Dropdown.Contentalign={align}side={side}sideOffset={6}- className="z-50 min-w-[200px] rounded-lg border border-line bg-raised p-1 text-sm text-ink shadow-xl animate-fade-in"+ collisionPadding={12}+ className={cx("z-50 min-w-[200px] rounded-lg border border-line bg-raised p-1 text-sm text-ink shadow-xl animate-fade-in", className)}>{children}</Dropdown.Content>diff --git a/apps/desktop/src/styles/base.css b/apps/desktop/src/styles/base.cssindex 07815375..63021134 100644--- a/apps/desktop/src/styles/base.css+++ b/apps/desktop/src/styles/base.css@@ -119,6 +119,39 @@ button, input, textarea, a, [role="button"], [data-no-drag] { -webkit-app-region.md-alert-caution { --alert: rgb(var(--red)); }/* ── Live thought process ── */+/* The composer's controls stay on one line: when it gets narrow, chips show only their icons+ (their names stay in the tooltip/title), and the model name truncates. */+.composer-row { container-type: inline-size; }+@container (max-width: 640px) { .chip-label { display: none; } }++/* Media on its way (MediaSkeleton): a soft colour field drifting under a light sweep. */+.media-skeleton { background: rgb(var(--ink) / 0.035); }+.media-aurora {+ background:+ radial-gradient(60% 55% at 25% 30%, rgb(var(--accent) / 0.22), transparent 70%),+ radial-gradient(55% 50% at 75% 70%, rgb(var(--cyan) / 0.20), transparent 70%),+ radial-gradient(45% 45% at 60% 20%, rgb(var(--accent) / 0.12), transparent 70%);+ background-size: 180% 180%;+ filter: blur(18px);+ animation: media-drift 7s ease-in-out infinite alternate;+}+.media-sweep {+ background: linear-gradient(105deg, transparent 30%, rgb(255 255 255 / 0.10) 45%, rgb(255 255 255 / 0.18) 50%, rgb(255 255 255 / 0.10) 55%, transparent 70%);+ background-size: 250% 100%;+ animation: media-sweep 2.2s linear infinite;+}+.dark .media-sweep { background-image: linear-gradient(105deg, transparent 30%, rgb(255 255 255 / 0.05) 45%, rgb(255 255 255 / 0.09) 50%, rgb(255 255 255 / 0.05) 55%, transparent 70%); }+.media-icon { animation: media-breathe 2.4s ease-in-out infinite; }+.media-bar { animation: media-bar 1.1s ease-in-out infinite alternate; transform-origin: bottom; }+/* The real thing arriving: from soft to sharp. */+.media-reveal { animation: media-reveal 700ms cubic-bezier(.2,.7,.2,1) both; }+@keyframes media-drift { 0% { background-position: 0% 0%; transform: scale(1); } 100% { background-position: 100% 100%; transform: scale(1.08); } }+@keyframes media-sweep { from { background-position: 120% 0; } to { background-position: -120% 0; } }+@keyframes media-breathe { 0%, 100% { opacity: .45; transform: scale(1); } 50% { opacity: .8; transform: scale(1.06); } }+@keyframes media-bar { from { transform: scaleY(.35); } to { transform: scaleY(1); } }+@keyframes media-reveal { from { filter: blur(18px) saturate(1.3); transform: scale(1.02); opacity: .6; } to { filter: none; transform: none; opacity: 1; } }+@media (prefers-reduced-motion: reduce) { .media-aurora, .media-sweep, .media-icon, .media-bar, .media-reveal { animation: none; } }+/* Text that is "in progress": a soft light passing over it. */.shimmer-text {background: linear-gradient(90deg, rgb(var(--ink-3)) 0%, rgb(var(--ink-3)) 40%, rgb(var(--ink)) 50%, rgb(var(--ink-3)) 60%, rgb(var(--ink-3)) 100%);diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsxindex aaf580c2..0ce6cd09 100644--- a/apps/desktop/src/views/chat/Composer.tsx+++ b/apps/desktop/src/views/chat/Composer.tsx@@ -1,8 +1,8 @@-import { ArrowUp, AudioLines, ChevronDown, Gauge, Paperclip, Shield, ShieldCheck, Square, Telescope, X } from "lucide-react";+import { ArrowUp, AudioLines, ChevronDown, Clapperboard, Gauge, Image as ImageIcon, Music, Paperclip, Shield, ShieldCheck, Square, Telescope, X } from "lucide-react";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { cx } from "~/lib/cx";import * as api from "~/api/mercury";-import type { ChatEffort, ModelsResponse, ReasoningChoice, ReasoningLevel } from "~/api/types";+import type { ChatEffort, ImageAspect, ImageIntent, MediaModelsResponse, ModelsResponse, ReasoningChoice, ReasoningLevel } from "~/api/types";import { usePermissionMode } from "~/app/permission";import { useBots, useRuntimeState } from "~/app/store";import { CommandPicker } from "./CommandPicker";@@ -66,6 +66,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, monconst [sending, setSending] = useState(false);// Research the next message (one run, then back to off). Chat only.const [researchNext, setResearchNext] = useState<ResearchNext>("off");+ const [imageNext, setImageNext] = useState<ImageIntent | null>(null);const threadKey = useConversation((s) => s.activeId);useEffect(() => { setResearchNext("off"); }, [threadKey]);const [error, setError] = useState<string | null>(null);@@ -200,15 +201,17 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, monasync function submit(override?: string) {let content = (override ?? (token ? `${token.fill}${text}` : text)).trim();- if (surface === "chat" && researchNext !== "off" && content && !/^[/#]/.test(content)) content = `/research ${researchNext === "plan" ? "plan " : ""}${content}`;+ if (surface === "chat" && researchNext !== "off" && !imageNext && content && !/^[/#]/.test(content)) content = `/research ${researchNext === "plan" ? "plan " : ""}${content}`;+ const media: ImageIntent | undefined = surface === "chat" && imageNext && content && !/^[/#]/.test(content) ? imageNext : undefined;if ((!content && files.length === 0) || sending) return;setSending(true);setError(null);try {- await sendMessage(surface, content, files.map((f) => ({ name: f.name, data: f.data, mime: f.mime })), code);+ await sendMessage(surface, content, files.map((f) => ({ name: f.name, data: f.data, mime: f.mime })), code, media);setText("");setToken(null);setResearchNext("off");+ setImageNext(null);for (const f of files) if (f.preview) URL.revokeObjectURL(f.preview);setFiles([]);} catch (err) {@@ -300,7 +303,9 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon/></div>)}- <div className="flex flex-wrap items-center gap-1 px-3 pb-3 pt-1.5">+ {/* One line, always: the model name gives way first, then the chips drop to their icons (base.css .composer-row). */}+ <div className="composer-row flex flex-nowrap items-center gap-1 px-3 pb-3 pt-1.5">+ <div className="flex min-w-0 flex-1 items-center gap-1"><Tooltip label="Attach images, PDFs, TXT or Markdown" side="top"><Button variant="ghost" size="md" icon onClick={() => picker.current?.click()} disabled={!connected || files.length >= MAX_FILES} aria-label="Attach"><Paperclip size={17} />@@ -316,14 +321,12 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon</Tooltip>)}<ModelPicker />- {surface === "chat" && <ResearchToggle value={researchNext} onChange={(v) => { setResearchNext(v); ref.current?.focus(); }} />}+ {surface === "chat" && <ImageToggle value={imageNext} onChange={(v) => { setImageNext(v); if (v) setResearchNext("off"); ref.current?.focus(); }} />}+ {surface === "chat" && <ResearchToggle value={researchNext} onChange={(v) => { setResearchNext(v); if (v !== "off") setImageNext(null); ref.current?.focus(); }} />}{surface === "chat" && <ModePicker />}- <div className="flex-1" />- {busy ? (- <span className="mr-2 text-xs text-ink4">{stopping ? "Stopping" : agent === "streaming" ? "Answering" : agent === "working" ? "Working" : "Thinking"}…</span>- ) : text.length > 0 ? (- <span className="mr-2 hidden text-2xs text-ink4 sm:inline">⇧↵ new line</span>- ) : null}+ </div>+ {/* What Mercury is doing shows inside the chat, under the reply (TurnTimeline's status line), not here. */}+ <div className="flex shrink-0 items-center gap-1">{!recording && <MicButton d={dictation} disabled={!connected} />}{!recording && surface === "chat" && voiceAvailable && !text.trim() && files.length === 0 && !busy && (<Tooltip label="Talk to Mercury (voice call)" side="top">@@ -345,6 +348,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon</Button></Tooltip>)}+ </div></div></div></div>@@ -367,13 +371,18 @@ function formatSize(bytes: number): string {return `${(bytes / 1048576).toFixed(1)} MB`;}+/** How many models before the picker offers a search box. */+const SEARCH_FROM = 8;+function ModelPicker() {const [models, setModels] = useState<ModelsResponse | null>(null);+ const [query, setQuery] = useState("");const provider = useRuntimeState((s) => s.provider);const model = useRuntimeState((s) => s.model);const store = useConversationStore();const threadId = useConversation((s) => s.activeId);const pendingEffort = useConversation((s) => s.pendingEffort);+ const search = useRef<HTMLInputElement>(null);async function load() {try { setModels(await api.chat.models(threadId)); } catch { setModels(null); }@@ -381,37 +390,64 @@ function ModelPicker() {useEffect(() => { void load(); }, [provider, model, threadId]); // eslint-disable-line react-hooks/exhaustive-depsconst label = models?.current?.label || model || provider || "Model";+ const all = models?.providers ?? [];+ const q = query.trim().toLowerCase();+ // Every word must match the name, the model id or the provider ("pro cloud", "gpt 5").+ const matches = (p: ModelsResponse["providers"][number]) => !q || q.split(/\s+/).every((w) => `${p.label} ${p.model} ${p.group}`.toLowerCase().includes(w));+ const shown = all.filter(matches);const groups = new Map<string, ModelsResponse["providers"]>();- for (const p of models?.providers ?? []) {- const list = groups.get(p.group) ?? [];- list.push(p);- groups.set(p.group, list);- }-+ for (const p of shown) groups.set(p.group, [...(groups.get(p.group) ?? []), p]);const current = models?.current;return (<><Menuside="top"+ className="flex w-[min(360px,calc(100vw-32px))] flex-col p-0"+ onOpenChange={(open) => {+ if (open) { setQuery(""); void load(); setTimeout(() => search.current?.focus(), 0); }+ }}trigger={- <button className="flex h-8 items-center gap-1 rounded-md px-2 text-sm text-ink2 hover:bg-ink/[0.06] hover:text-ink" aria-label="Model">- <span className="max-w-[180px] truncate">{label}</span>- <ChevronDown size={12} className="text-ink4" />+ <button className="flex h-8 min-w-0 items-center gap-1 rounded-md px-2 text-sm text-ink2 hover:bg-ink/[0.06] hover:text-ink" aria-label={`Model: ${label}`} title={label}>+ <span className="min-w-0 max-w-[200px] truncate">{label}</span>+ <ChevronDown size={12} className="shrink-0 text-ink4" /></button>}>- {[...groups.entries()].map(([group, list], gi) => (- <div key={group}>- {gi > 0 && <MenuSeparator />}- <MenuLabel>{group}</MenuLabel>- {list.map((p) => (- <MenuItem key={`${p.name}:${p.model}`} selected={p.isCurrent} disabled={!p.available} hint={p.available ? undefined : "no key"} onSelect={() => { void api.chat.switchModel(p.name, p.model).then(load); }}>- {p.label}- </MenuItem>- ))}+ {all.length >= SEARCH_FROM && (+ <div className="border-b border-line p-1.5">+ <input+ ref={search}+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ // Typing goes to the box, not to the menu's jump-to-letter.+ onKeyDown={(e) => { if (e.key !== "ArrowDown" && e.key !== "Escape" && e.key !== "Tab") e.stopPropagation(); }}+ placeholder={`Search ${all.length} models`}+ aria-label="Search models"+ className="h-8 w-full rounded-md border border-line bg-bg px-2.5 text-sm text-ink outline-none placeholder:text-ink4 focus:border-accent"+ /></div>- ))}- {groups.size === 0 && <MenuItem disabled>No providers configured</MenuItem>}+ )}+ {/* At most this tall, whatever the screen: longer lists scroll. */}+ <div className="max-h-[min(420px,55vh)] overflow-y-auto overscroll-contain p-1">+ {[...groups.entries()].map(([group, list], gi) => (+ <div key={group}>+ {gi > 0 && <MenuSeparator />}+ <MenuLabel>{group}{list.length > 1 ? ` · ${list.length}` : ""}</MenuLabel>+ {list.map((p) => (+ <MenuItem key={`${p.name}:${p.model}`} selected={p.isCurrent} disabled={!p.available} hint={p.available ? undefined : "no key"} onSelect={() => { void api.chat.switchModel(p.name, p.model).then(load); }}>+ <span className="block truncate" title={p.model}>{p.label}</span>+ </MenuItem>+ ))}+ </div>+ ))}+ {all.length === 0 && <MenuItem disabled>No providers configured</MenuItem>}+ {all.length > 0 && shown.length === 0 && <MenuItem disabled>No model matches “{query}”</MenuItem>}+ </div>+ {(models?.notices?.length ?? 0) > 0 && (+ <div className="border-t border-line px-3 py-2 text-xs text-amber">+ {models!.notices!.map((n) => <p key={n}>{n}</p>)}+ </div>+ )}</Menu>{current && current.reasoningLevels?.length > 0 && (<EffortPicker@@ -474,12 +510,12 @@ function EffortPicker({ effort, levels, modelLabel, onChat, onDefault }: {side="top"trigger={<button- className={cx("flex h-8 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", effort.effective === "auto" ? "text-ink3" : "text-ink2")}+ className={cx("flex h-8 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", effort.effective === "auto" ? "text-ink3" : "text-ink2")}aria-label="Thinking effort"title={`${EFFORT_LABEL[effort.effective]} · ${own ? "this chat" : effort.source === "model" ? `${modelLabel} default` : "the model decides"}`}><Gauge size={14} />- {shown}+ <span className="chip-label">{shown}</span>{own && <span className="h-1.5 w-1.5 rounded-full bg-accent" aria-label="set for this chat" />}<ChevronDown size={12} className="text-ink4" /></button>@@ -503,6 +539,63 @@ function EffortPicker({ effort, levels, modelLabel, onChat, onDefault }: {);}+const ASPECT_LABEL: Record<ImageAspect, string> = { square: "Square", landscape: "Landscape", portrait: "Portrait" };+const KIND_LABEL = { image: "Image", video: "Video", music: "Music" } as const;+const ASPECT_RATIO: Record<"image" | "video", Record<ImageAspect, string>> = {+ image: { square: "1:1", landscape: "3:2", portrait: "2:3" },+ video: { square: "1:1", landscape: "16:9", portrait: "9:16" },+};++/**+ * Create with the next message (ADR-042): an image, a video or music, made+ * by a real model (never an SVG). The models are the defaults in Settings →+ * AI → Media, or the best ones Mercury finds on your providers. Videos and+ * music take a while and arrive in the chat when ready.+ */+function ImageToggle({ value, onChange }: { value: ImageIntent | null; onChange: (v: ImageIntent | null) => void }) {+ const [info, setInfo] = useState<MediaModelsResponse | null>(null);+ const provider = useRuntimeState((s) => s.provider);+ // Asked again when the chat provider changes (a new provider may bring media models).+ useEffect(() => { void api.media.models().then(setInfo).catch(() => setInfo(null)); }, [provider]);+ const has = (k: "image" | "video" | "music") => info === null || (info[k]?.models.length ?? 0) > 0;+ const using = (k: "image" | "video" | "music") => {+ const i = info?.[k];+ if (!i) return null;+ return i.default?.available ? i.models.find((m) => m.ref === i.default!.ref)?.label ?? null : i.auto?.label ?? null;+ };+ // Short, so the row stays on one line: "Video 16:9", "Image 3:2", "Music".+ const label = value ? `${KIND_LABEL[value.kind]}${value.aspect ? ` ${ASPECT_RATIO[value.kind === "video" ? "video" : "image"][value.aspect]}` : ""}` : "Create";+ return (+ <Menu+ side="top"+ trigger={+ <button className={cx("flex h-8 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", value ? "bg-accent/10 text-accent" : "text-ink3")} aria-label={`Create: ${label}`} title={label} aria-pressed={!!value}>+ {value?.kind === "video" ? <Clapperboard size={14} /> : value?.kind === "music" ? <Music size={14} /> : <ImageIcon size={14} />}+ <span className="chip-label">{label}</span>+ </button>+ }+ >+ <MenuLabel>Your next message</MenuLabel>+ <MenuItem selected={!value} onSelect={() => onChange(null)}>Normal answer</MenuItem>+ <MenuSeparator />+ <MenuLabel>Image{using("image") ? ` · ${using("image")}` : ""}</MenuLabel>+ {(["square", "landscape", "portrait"] as ImageAspect[]).map((a) => (+ <MenuItem key={a} selected={value?.kind === "image" && value.aspect === a} disabled={!has("image")} onSelect={() => onChange({ kind: "image", aspect: a })}>{ASPECT_LABEL[a]}</MenuItem>+ ))}+ <MenuLabel>Video{using("video") ? ` · ${using("video")}` : ""}</MenuLabel>+ {(["landscape", "portrait"] as ImageAspect[]).map((a) => (+ <MenuItem key={a} selected={value?.kind === "video" && value.aspect === a} disabled={!has("video")} onSelect={() => onChange({ kind: "video", aspect: a })}>{ASPECT_LABEL[a]}</MenuItem>+ ))}+ <MenuItem selected={value?.kind === "music"} disabled={!has("music")} onSelect={() => onChange({ kind: "music" })}>+ Music{using("music") ? ` · ${using("music")}` : ""}+ </MenuItem>+ {info && !has("image") && !has("video") && !has("music") && (+ <MenuItem disabled hint="Settings → AI → Media">No media models on your providers</MenuItem>+ )}+ </Menu>+ );+}+type ResearchNext = "off" | "on" | "plan";/** Research the next message: a full report from live sources, optionally with a plan to check first. */@@ -512,9 +605,9 @@ function ResearchToggle({ value, onChange }: { value: ResearchNext; onChange: (v<Menuside="top"trigger={- <button className={cx("flex h-8 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", on ? "bg-accent/10 text-accent" : "text-ink3")} aria-label="Research" aria-pressed={on}>+ <button className={cx("flex h-8 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", on ? "bg-accent/10 text-accent" : "text-ink3")} aria-label="Research" title={value === "plan" ? "Research · plan first" : "Research"} aria-pressed={on}><Telescope size={14} />- {on ? (value === "plan" ? "Research · plan first" : "Research") : "Research"}+ <span className="chip-label">{value === "plan" ? "Research · plan" : "Research"}</span></button>}>@@ -534,9 +627,9 @@ function ModePicker() {<Menuside="top"trigger={- <button className={cx("flex h-8 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", allowAll ? "text-accent" : "text-amber")} aria-label="Approval mode">+ <button className={cx("flex h-8 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", allowAll ? "text-accent" : "text-amber")} aria-label="Approval mode" title={allowAll ? "Allow All" : "Ask Me"}>{allowAll ? <ShieldCheck size={13} /> : <Shield size={13} />}- {mode !== null ? (allowAll ? "Allow All" : "Ask Me") : "…"}+ <span className="chip-label">{mode !== null ? (allowAll ? "Allow All" : "Ask Me") : "…"}</span></button>}>diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsxindex 2cf4ad13..cf52f20d 100644--- a/apps/desktop/src/views/chat/Conversation.tsx+++ b/apps/desktop/src/views/chat/Conversation.tsx@@ -10,6 +10,10 @@ import { StateLabel } from "~/components/indicators/StateOrb";import { Approval } from "~/components/indicators/Approval";import { ThinkingDots } from "~/components/indicators/Thinking";import { Message, StreamingMessage } from "./Message";+import { MediaSkeleton } from "~/components/MediaSkeleton";+import { useNow } from "~/components/TurnTimeline";+import { Mark } from "~/components/Logo";+import type { PendingMedia } from "~/api/types";import { Composer, type ComposerProps } from "./Composer";import { WaitingNotice } from "./Waiting";import { ResearchBar, ResearchPlan } from "./Research";@@ -17,6 +21,24 @@ import { AlertTriangle, Info } from "lucide-react";const PAGE = 30;+/** Videos and songs being made in the background: their places in the chat, until they arrive (media_ready). */+function PendingMediaList({ items }: { items: PendingMedia[] }) {+ const now = useNow(true);+ return (+ <>+ {items.map((p) => (+ <div key={p.jobId} className="flex gap-4">+ <span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center" aria-hidden="true"><Mark size={22} /></span>+ <div className="min-w-0 flex-1">+ <MediaSkeleton shape={{ kind: p.kind, aspect: p.aspect, prompt: p.prompt }} startedAt={p.startedAt} now={now} />+ <p className="mt-1 text-2xs text-ink4">It will appear here when it's ready — you can keep chatting.</p>+ </div>+ </div>+ ))}+ </>+ );+}+/*** One conversation column: header, messages (newest PAGE, older on* scroll-up with the place kept), approvals, composer. It reads the@@ -36,6 +58,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; econst waiting = useConversation((s) => s.waiting);const stopping = useConversation((s) => s.stopping);const notice = useConversation((s) => s.notice);+ const pendingMedia = useConversation((s) => s.pendingMedia);const researching = useConversation((s) => s.research?.run?.state === "running");const scroller = useRef<HTMLDivElement>(null);const content = useRef<HTMLDivElement>(null);@@ -111,6 +134,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e{(streaming || (live && (agent === "thinking" || agent === "working" || agent === "streaming" || agent === "needs-you"))) && (<StreamingMessage text={streaming} live={live} agent={agent} stopping={stopping} />)}+ {pendingMedia.length > 0 && <PendingMediaList items={pendingMedia} />}{waiting && !streaming ? (<WaitingNotice threadId={activeId} waiting={waiting} />) : !streaming && !live && (agent === "thinking" || agent === "working") && (diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsxindex cd9dd3e6..053da70d 100644--- a/apps/desktop/src/views/chat/Message.tsx+++ b/apps/desktop/src/views/chat/Message.tsx@@ -78,7 +78,7 @@ export const Message = memo(function Message({ message, undoable = false }: { me{stopped && <StoppedMarker partial={!!body} />}{message.research? <ResearchReport run={message.research} content={body} />- : message.artifacts && message.artifacts.length > 0 && <ArtifactStrip items={message.artifacts} />}+ : message.artifacts && message.artifacts.length > 0 && <ArtifactStrip items={message.artifacts} fresh={isFresh(message.timestamp)} />}{message.research && message.artifacts && message.artifacts.filter((a) => a.id !== message.research?.report?.id).length > 0 && (<ArtifactStrip items={message.artifacts.filter((a) => a.id !== message.research?.report?.id)} />)}@@ -89,6 +89,12 @@ export const Message = memo(function Message({ message, undoable = false }: { me);});+/** Arrived just now (not loaded from history): a generated picture is revealed, not just shown. */+function isFresh(timestamp: string): boolean {+ const t = Date.parse(timestamp);+ return Number.isFinite(t) && Date.now() - t < 60_000;+}+/** The honest end of a stopped turn: nothing after this was done. */function StoppedMarker({ partial }: { partial: boolean }) {return (diff --git a/apps/desktop/src/views/settings/Images.tsx b/apps/desktop/src/views/settings/Images.tsxnew file mode 100644index 00000000..0109f6f4--- /dev/null+++ b/apps/desktop/src/views/settings/Images.tsx@@ -0,0 +1,198 @@+import { Check, RefreshCw } from "lucide-react";+import { useEffect, useState } from "react";+import * as api from "~/api/mercury";+import { ApiError } from "~/api/client";+import type { MediaKindInfo, MediaModelsResponse, SpeechInfo, VoiceReplies } from "~/api/types";+import { Segmented, Spinner } from "~/components/ui/bits";+import { cx } from "~/lib/cx";++/**+ * Images (ADR-042): which model draws when you ask for an image. The list is+ * what your configured providers offer (OpenAI, OpenRouter, LiteLLM, AI/ML+ * API, Mercury Cloud, Ollama…), found automatically and checked again daily.+ * Automatic picks the best one, preferring the provider you chat with.+ */+export function ImageSettings() {+ const [info, setInfo] = useState<MediaModelsResponse["image"] | null>(null);+ const [speech, setSpeech] = useState<SpeechInfo | null>(null);+ const [video, setVideo] = useState<MediaKindInfo | null>(null);+ const [music, setMusic] = useState<MediaKindInfo | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ async function load(refresh = false) {+ setBusy(true);+ setError(null);+ try {+ const r = await api.media.models(refresh);+ setInfo(r.image);+ setSpeech(r.speech ?? null);+ setVideo(r.video ?? null);+ setMusic(r.music ?? null);+ } catch (e) {+ setError(e instanceof ApiError && e.status === 404+ ? "This Mercury can't make images yet. Update it to use image models."+ : e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(false);+ }+ }+ useEffect(() => { void load(); }, []);++ async function choose(ref: string | null, kind: "image" | "video" | "music" = "image") {+ setError(null);+ try {+ await api.media.setDefault(ref, kind);+ await load();+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ }+ }++ if (!info) return error ? <p className="text-sm text-ink3">{error}</p> : <div className="py-10 text-ink3"><Spinner size={18} /></div>;+ const groups = new Map<string, typeof info.models>();+ for (const m of info.models) groups.set(m.group, [...(groups.get(m.group) ?? []), m]);+ const chosen = info.default?.available ? info.default.ref : null;++ return (+ <div className="flex flex-col gap-6">+ <p className="text-sm text-ink3">+ Images, videos, music and speech made by real models from your providers. Pick one for each, or let Mercury choose. Use the Create button in the chat box, ask in your own words, or type <code className="font-mono">/image</code>, <code className="font-mono">/video</code>, <code className="font-mono">/music</code> or <code className="font-mono">/say</code> — in the terminal, Telegram and WhatsApp too.+ </p>+ {error && <p className="text-sm text-red" role="alert">{error}</p>}+ {info.default && !info.default.available && (+ <p className="text-sm text-amber">Your choice ({info.default.ref}) isn't offered by your providers right now, so the automatic pick is used.</p>+ )}+ <section className="flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <h3 className="text-sm font-medium text-ink">Image model</h3>+ <button onClick={() => void load(true)} disabled={busy} className="flex items-center gap-1.5 text-xs text-ink3 hover:text-ink disabled:opacity-50">+ <RefreshCw size={12} className={cx(busy && "animate-spin")} /> Check providers again+ </button>+ </div>+ <div className="flex flex-col divide-y divide-line rounded-lg border border-line bg-surface">+ <Row selected={!chosen} onSelect={() => void choose(null)} title="Automatic" detail={info.auto ? `Now: ${info.auto.label} · ${info.auto.group}` : "No image model found yet"} />+ {[...groups.entries()].map(([group, list]) => (+ <div key={group} className="flex flex-col">+ <div className="px-4 pb-1 pt-3 text-2xs font-medium uppercase tracking-wide text-ink4">{group}</div>+ {list.map((m) => (+ <Row key={m.ref} selected={chosen === m.ref} onSelect={() => void choose(m.ref)} title={m.label} detail={m.canEdit ? m.model : `${m.model} · can't edit images`} />+ ))}+ </div>+ ))}+ </div>+ {info.models.length === 0 && (+ <p className="text-xs text-ink3">+ None of your providers offers an image model. Add one that does — OpenAI (gpt-image), OpenRouter (Gemini image, FLUX…), LiteLLM, AI/ML API, Atlas Cloud, Runcrate, Mercury Cloud, or an Ollama image model — in Models, then check again.+ </p>+ )}+ </section>+ {video && <KindSection title="Video model" kind="video" info={video} onChoose={(ref) => void choose(ref, "video")}+ blurb="Short clips (3–15 seconds) for /video, the Create menu, or when you ask. They take a minute or a few and arrive in the chat when ready."+ none="No video model found. A Gemini key (Settings → Voice) gives Gemini Omni video; gateways such as LiteLLM or Mercury Cloud can serve others." />}+ {music && <KindSection title="Music model" kind="music" info={music} onChoose={(ref) => void choose(ref, "music")}+ blurb="Songs and instrumentals for /music, the Create menu, or when you ask. They arrive in the chat when ready."+ none="No music model found. A Gemini key (Lyria) or an ElevenLabs key (Settings → Voice) makes music." />}+ {speech && <SpeechSection speech={speech} onChange={async (update) => { setError(null); try { await api.media.setSpeech(update); await load(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } }} />}+ </div>+ );+}++/** One kind's models (video, music): Automatic or a model from your providers. */+function KindSection({ title, blurb, none, info, onChoose }: { title: string; kind: string; blurb: string; none: string; info: MediaKindInfo; onChoose: (ref: string | null) => void }) {+ const chosen = info.default?.available ? info.default.ref : null;+ const groups = new Map<string, typeof info.models>();+ for (const m of info.models) groups.set(m.group, [...(groups.get(m.group) ?? []), m]);+ return (+ <section className="flex flex-col gap-3">+ <h3 className="text-sm font-medium text-ink">{title}</h3>+ <p className="text-xs text-ink3">{blurb}</p>+ {info.models.length === 0 ? <p className="text-xs text-ink3">{none}</p> : (+ <div className="flex flex-col divide-y divide-line rounded-lg border border-line bg-surface">+ <Row selected={!chosen} onSelect={() => onChoose(null)} title="Automatic" detail={info.auto ? `Now: ${info.auto.label} · ${info.auto.group}` : "—"} />+ {[...groups.entries()].map(([group, list]) => (+ <div key={group} className="flex flex-col">+ <div className="px-4 pb-1 pt-3 text-2xs font-medium uppercase tracking-wide text-ink4">{group}</div>+ {list.map((m) => <Row key={m.ref} selected={chosen === m.ref} onSelect={() => onChoose(m.ref)} title={m.label} detail={m.model} />)}+ </div>+ ))}+ </div>+ )}+ </section>+ );+}++const REPLIES: Array<{ value: VoiceReplies; label: string }> = [+ { value: "off", label: "Never" },+ { value: "mirror", label: "When I send one" },+ { value: "always", label: "Always" },+];++/**+ * Speaking (phase 2): what reads replies aloud, makes voice notes and+ * /say audio, in which voice, and when chat-app replies also come as a+ * voice note.+ */+function SpeechSection({ speech, onChange }: { speech: SpeechInfo; onChange: (u: { choice?: string | null; voice?: string | null; replies?: VoiceReplies }) => void }) {+ const [voice, setVoice] = useState(speech.voice ?? "");+ useEffect(() => { setVoice(speech.voice ?? ""); }, [speech.voice]);+ const current = speech.options.find((o) => o.id === speech.current?.id);+ const groups = new Map<string, typeof speech.options>();+ for (const o of speech.options) groups.set(o.group, [...(groups.get(o.group) ?? []), o]);+ return (+ <section className="flex flex-col gap-3">+ <h3 className="text-sm font-medium text-ink">Speech</h3>+ <p className="text-xs text-ink3">Reads replies aloud, makes voice notes and audio when you ask (or <code className="font-mono">/say</code>), and speaks in Telegram and WhatsApp.</p>+ <div className="flex flex-col divide-y divide-line rounded-lg border border-line bg-surface">+ <Row selected={!speech.choice} onSelect={() => onChange({ choice: null })} title="Same as Settings → Voice" detail={speech.current && !speech.choice ? `Now: ${speech.current.label}` : speech.options.length ? "The voice you chose for calls" : "No speech service set up"} />+ {[...groups.entries()].map(([group, list]) => (+ <div key={group} className="flex flex-col">+ <div className="px-4 pb-1 pt-3 text-2xs font-medium uppercase tracking-wide text-ink4">{group}</div>+ {list.map((o) => <Row key={o.id} selected={speech.choice === o.id} onSelect={() => onChange({ choice: o.id })} title={o.label} detail={o.id} />)}+ </div>+ ))}+ </div>+ {speech.options.length === 0 && (+ <p className="text-xs text-ink3">Add an OpenAI key in Models, or a Gemini, Deepgram or ElevenLabs key in Voice, to let Mercury speak.</p>+ )}+ {speech.current && (+ <div className="flex flex-col gap-2 rounded-lg border border-line bg-surface px-4 py-3">+ <label className="text-sm text-ink" htmlFor="speech-voice">Voice</label>+ <div className="flex items-center gap-2">+ <input+ id="speech-voice"+ list="speech-voices"+ value={voice}+ onChange={(e) => setVoice(e.target.value)}+ onBlur={() => { if ((speech.voice ?? "") !== voice.trim()) onChange({ voice: voice.trim() || null }); }}+ onKeyDown={(e) => { if (e.key === "Enter") (e.target as HTMLInputElement).blur(); }}+ placeholder="The service's default"+ className="h-8 min-w-0 flex-1 rounded-md border border-line bg-bg px-2 text-sm text-ink outline-none focus:border-accent"+ />+ <datalist id="speech-voices">{(current?.voices ?? []).map((v) => <option key={v} value={v} />)}</datalist>+ </div>+ <p className="text-xs text-ink3">{current?.voices.length ? `For example: ${current.voices.slice(0, 6).join(", ")}.` : "A voice id from the service (ElevenLabs: from your voice library)."}</p>+ </div>+ )}+ <div className="flex flex-col gap-2 rounded-lg border border-line bg-surface px-4 py-3">+ <span className="text-sm text-ink">Answer with a voice note in chat apps</span>+ <Segmented value={speech.replies} onChange={(v) => onChange({ replies: v as VoiceReplies })} options={REPLIES} />+ <p className="text-xs text-ink3">Telegram and WhatsApp: the text reply always comes; a voice note follows when you sent one, or on every reply.</p>+ </div>+ </section>+ );+}++function Row({ selected, onSelect, title, detail }: { selected: boolean; onSelect: () => void; title: string; detail: string }) {+ return (+ <button onClick={onSelect} className="flex items-center gap-3 px-4 py-2.5 text-left hover:bg-ink/[0.03]" aria-pressed={selected}>+ <span className={cx("flex h-4 w-4 shrink-0 items-center justify-center rounded-full border", selected ? "border-accent bg-accent text-on-accent" : "border-line-strong")}>+ {selected && <Check size={10} strokeWidth={3} />}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm text-ink">{title}</span>+ <span className="block truncate font-mono text-2xs text-ink4">{detail}</span>+ </span>+ </button>+ );+}diff --git a/apps/desktop/src/views/settings/SettingsView.tsx b/apps/desktop/src/views/settings/SettingsView.tsxindex 9a719435..97113abe 100644--- a/apps/desktop/src/views/settings/SettingsView.tsx+++ b/apps/desktop/src/views/settings/SettingsView.tsx@@ -1,4 +1,5 @@import { Activity, Info, MessagesSquare, Palette, Server, Sparkles, UserRound } from "lucide-react";+import { ImageSettings } from "./Images";import { UpdatesSettings } from "~/updates/UpdatesSettings";import { useEffect, useState } from "react";import { cx } from "~/lib/cx";@@ -29,13 +30,13 @@ import { NotificationsSettings } from "./Notifications";* page shows them as tabs across the top. Everything about the models* (which ones, voice, what they may spend) sits together under AI.*/-type Section = "profile" | "models" | "voice" | "budgets" | "concurrency" | "channels" | "notifications" | "appearance" | "statusbar" | "startup" | "connections" | "devices" | "analytics" | "about";+type Section = "profile" | "models" | "images" | "voice" | "budgets" | "concurrency" | "channels" | "notifications" | "appearance" | "statusbar" | "startup" | "connections" | "devices" | "analytics" | "about";type GroupId = "profile" | "ai" | "messaging" | "app" | "connections" | "analytics" | "about";const GROUPS: Array<{ id: GroupId; label: string; icon: typeof Palette; tabs: Array<{ id: Section; label: string }> }> = [{ id: "profile", label: "Profile", icon: UserRound, tabs: [{ id: "profile", label: "Profile" }] },- { id: "ai", label: "AI", icon: Sparkles, tabs: [{ id: "models", label: "Models" }, { id: "voice", label: "Voice" }, { id: "budgets", label: "Budgets" }, { id: "concurrency", label: "Chats at once" }] },+ { id: "ai", label: "AI", icon: Sparkles, tabs: [{ id: "models", label: "Models" }, { id: "images", label: "Media" }, { id: "voice", label: "Voice" }, { id: "budgets", label: "Budgets" }, { id: "concurrency", label: "Chats at once" }] },{ id: "messaging", label: "Messaging", icon: MessagesSquare, tabs: [{ id: "channels", label: "Channels" }, { id: "notifications", label: "Notifications" }] },{ id: "app", label: "App", icon: Palette, tabs: [{ id: "appearance", label: "Appearance" }, { id: "statusbar", label: "Status bar" }, { id: "startup", label: "Start-up" }] },{ id: "connections", label: "Connections", icon: Server, tabs: [{ id: "connections", label: "Runtimes" }, { id: "devices", label: "Paired devices" }] },@@ -105,6 +106,7 @@ export function SettingsView({ connection, health, onSwitchConnection }: { conne{section === "voice" && <VoiceSettings onOpenModels={() => go("models")} />}{section === "budgets" && <BudgetsSettings />}{section === "concurrency" && <ConcurrencySettings />}+ {section === "images" && <ImageSettings />}{section === "notifications" && <NotificationsSettings />}{section === "channels" && <ChannelsSettings />}{section === "appearance" && <Appearance />}diff --git a/src/artifacts/collector.ts b/src/artifacts/collector.tsindex cec2edaa..29ff94ab 100644--- a/src/artifacts/collector.ts+++ b/src/artifacts/collector.ts@@ -63,6 +63,8 @@ export class ArtifactCollector {const args = (input ?? {}) as Record<string, unknown>;const text = typeof result === 'string' ? result : JSON.stringify(result ?? '');if (tool === 'send_file' && typeof args.path === 'string') this.add(expand(args.path, cwd), 'sent', tool);+ // Made for the owner by an image model: always a deliverable.+ else if (tool === 'generate_image' || tool === 'generate_speech') for (const p of pathsIn(text.slice(0, 4000), cwd, { relative: false })) this.add(p, 'sent', tool);else if ((tool === 'write_file' || tool === 'create_file') && typeof args.path === 'string') {if (!/^(Error|⚠)/.test(text.trim())) this.add(expand(args.path, cwd), 'written', tool);} else if (tool === 'run_command') {diff --git a/src/artifacts/ref.ts b/src/artifacts/ref.tsindex 2c887231..070a14d9 100644--- a/src/artifacts/ref.ts+++ b/src/artifacts/ref.ts@@ -2,10 +2,11 @@ import type { ArtifactKind } from './classify.js';import type { Artifact } from './store.js';/** What a message or an event carries about an artifact (never the stored path). */-export interface ArtifactRef { id: string; name: string; kind: ArtifactKind; mime: string; size: number; path: string }+export interface ArtifactRef { id: string; name: string; kind: ArtifactKind; mime: string; size: number; path: string; tool?: string }export function artifactRef(a: Artifact): ArtifactRef {- return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, path: a.originalPath };+ // `tool`: the apps show what a media model made (generate_*) large and playable.+ return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, path: a.originalPath, ...(a.tool ? { tool: a.tool } : {}) };}const LABEL: Record<ArtifactKind, string> = { image: 'image', video: 'video', audio: 'audio', pdf: 'PDF', document: 'document', text: 'notes', file: 'file' };diff --git a/src/capabilities/media/generate-image.test.ts b/src/capabilities/media/generate-image.test.tsnew file mode 100644index 00000000..b6d1ccb9--- /dev/null+++ b/src/capabilities/media/generate-image.test.ts@@ -0,0 +1,52 @@+import { mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createGenerateImageTool } from './generate-image.js';+import type { MediaService } from '../../media/service.js';++/** generate_image: real files from an image model, delivered, and an honest error when none is set up. */+const dir = mkdtempSync(join(tmpdir(), 'mercury-genimg-'));+afterEach(() => vi.restoreAllMocks());++function make(generate: MediaService['generateImage']) {+ const deliver = vi.fn(async () => 'Sent to this chat.');+ const permissions = { checkFsAccess: async (p: string) => ({ allowed: true, canonical: p }) };+ const t = createGenerateImageTool({+ media: { generateImage: generate } as unknown as MediaService,+ permissions: permissions as never,+ getCwd: () => dir,+ outputDir: () => join(dir, 'out'),+ deliver,+ });+ const run = (input: Record<string, unknown>) => (t as unknown as { execute: (i: unknown, o: unknown) => Promise<string> }).execute(input, { abortSignal: undefined, toolCallId: 't', messages: [] });+ return { run, deliver };+}++describe('generate_image', () => {+ it('generates, delivers, and tells the model the path for edits', async () => {+ const gen = vi.fn(async () => ({ files: [join(dir, 'out', 'fox.png')], model: { ref: 'openai::gpt-image-1', label: 'GPT Image 1', group: 'OpenAI API' }, failed: [], ms: 2100 }));+ const { run, deliver } = make(gen as never);+ const out = await run({ prompt: 'a fox', aspect: 'landscape' });+ expect(gen).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'a fox', aspect: 'landscape', references: [] }), join(dir, 'out'));+ expect(deliver).toHaveBeenCalledWith([join(dir, 'out', 'fox.png')], 'a fox');+ expect(out).toContain('Generated 1 image with GPT Image 1 (OpenAI API) in 2.1s');+ expect(out).toContain(`- ${join(dir, 'out', 'fox.png')}`);+ expect(out).toContain('Sent to this chat.');+ expect(out).toContain('reference_images');+ });++ it('passes reference images as resolved paths, and refuses missing ones', async () => {+ writeFileSync(join(dir, 'in.png'), 'x');+ const gen = vi.fn(async () => ({ files: [join(dir, 'b.png')], model: { label: 'M', group: 'G' }, failed: [], ms: 1 }));+ const { run } = make(gen as never);+ await run({ prompt: 'make it blue', reference_images: ['in.png'] });+ expect((gen.mock.calls as unknown as Array<[unknown]>)[0][0]).toMatchObject({ references: [join(dir, 'in.png')] });+ expect(await run({ prompt: 'x', reference_images: ['missing.png'] })).toContain('reference image not found');+ });++ it('no image model: says so instead of failing the turn', async () => {+ const { run } = make((async () => { throw new Error('No image model is set up. Add a provider…'); }) as never);+ expect(await run({ prompt: 'a fox' })).toBe('Error: No image model is set up. Add a provider…');+ });+});diff --git a/src/capabilities/media/generate-image.ts b/src/capabilities/media/generate-image.tsnew file mode 100644index 00000000..719d9b6b--- /dev/null+++ b/src/capabilities/media/generate-image.ts@@ -0,0 +1,72 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import { existsSync } from 'node:fs';+import type { PermissionManager } from '../permissions.js';+import { resolveToolPath, type CwdSource } from '../filesystem/resolve-path.js';+import { readDenialMessage } from '../filesystem/verified-read.js';+import type { MediaService } from '../../media/service.js';++export interface GenerateImageDeps {+ media: MediaService;+ permissions: PermissionManager;+ getCwd: CwdSource;+ /** Where this chat's images go. */+ outputDir(): string;+ /**+ * Send the images to the chat that asked (Telegram, WhatsApp…). Returns+ * how they were delivered, for the model's reply; apps show them as+ * artifacts and the terminal prints the path.+ */+ deliver(files: string[], caption: string): Promise<string>;+}++/**+ * Real image generation (ADR-042): an image model makes the picture. Without+ * this tool the only way a chat model could "make an image" was to write an+ * SVG with create_file.+ */+export function createGenerateImageTool(deps: GenerateImageDeps) {+ return tool({+ description: [+ 'Generate or edit an image with an image model (a picture, photo, illustration, logo, artwork, poster, mockup).',+ 'Use this whenever the user asks for an image; do not draw it as SVG or code unless they ask for SVG, a diagram or a vector file.',+ 'To change an image you made or one the user gave you, pass its path in reference_images and say what to change.',+ 'The image is saved and shown to the user; describe it briefly afterwards.',+ ].join(' '),+ inputSchema: zodSchema(z.object({+ prompt: z.string().min(1).max(4000).describe('What to draw, in detail: subject, style, composition, lighting, text to include.'),+ aspect: z.enum(['square', 'landscape', 'portrait']).optional().describe('Shape of the image (default square).'),+ quality: z.enum(['auto', 'low', 'medium', 'high']).optional().describe('Higher is slower and costs more (default auto).'),+ count: z.number().int().min(1).max(4).optional().describe('How many variations (default 1).'),+ reference_images: z.array(z.string()).max(5).optional().describe('Paths of images to edit or use as references.'),+ model: z.string().optional().describe('Only when the user names a model: "provider::model" from /media, or the model id.'),+ })),+ execute: async ({ prompt, aspect, quality, count, reference_images, model }, { abortSignal }) => {+ const references: string[] = [];+ for (const ref of reference_images ?? []) {+ const resolved = resolveToolPath(ref, deps.getCwd);+ const check = await deps.permissions.checkFsAccess(resolved, 'read');+ if (!check.allowed) return readDenialMessage(resolved, check);+ const target = check.canonical ?? resolved;+ if (!existsSync(target)) return `Error: reference image not found: ${ref}`;+ references.push(target);+ }+ try {+ const result = await deps.media.generateImage({ prompt, aspect, quality, count, references, model, signal: abortSignal }, deps.outputDir());+ const caption = prompt.length > 200 ? `${prompt.slice(0, 197)}…` : prompt;+ const delivered = await deps.deliver(result.files, caption).catch((err) => `not sent to the chat (${err instanceof Error ? err.message : String(err)})`);+ return [+ `Generated ${result.files.length} image${result.files.length === 1 ? '' : 's'} with ${result.model.label} (${result.model.group}) in ${(result.ms / 1000).toFixed(1)}s:`,+ ...result.files.map((f) => `- ${f}`),+ delivered,+ ...(result.failed.length ? [`(Tried first, failed: ${result.failed.map((f) => `${f.ref}: ${f.error}`).join('; ')})`] : []),+ ...(result.revisedPrompt ? [`The model's prompt: ${result.revisedPrompt}`] : []),+ ...(result.note ? [`The model said: ${result.note.slice(0, 500)}`] : []),+ `To edit it, call generate_image again with reference_images: ["${result.files[0]}"]. Don't send it again with send_file.`,+ ].join('\n');+ } catch (err) {+ return `Error: ${err instanceof Error ? err.message : String(err)}`;+ }+ },+ });+}diff --git a/src/capabilities/media/generate-speech.test.ts b/src/capabilities/media/generate-speech.test.tsnew file mode 100644index 00000000..42e0345b--- /dev/null+++ b/src/capabilities/media/generate-speech.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from 'vitest';+import { createGenerateSpeechTool } from './generate-speech.js';+import type { SpeechService } from '../../media/speech.js';++/** generate_speech: a voice note in chat apps, mp3 elsewhere, delivered, errors told plainly. */+function make(inChatApp: boolean, speakToFile: SpeechService['speakToFile']) {+ const deliver = vi.fn(async () => 'Sent to this chat.');+ const t = createGenerateSpeechTool({ speech: { speakToFile } as unknown as SpeechService, outputDir: () => '/out', inChatApp: () => inChatApp, deliver });+ const run = (input: Record<string, unknown>) => (t as unknown as { execute: (i: unknown, o: unknown) => Promise<string> }).execute(input, { abortSignal: undefined, toolCallId: 't', messages: [] });+ return { run, deliver };+}++describe('generate_speech', () => {+ it('a voice note (ogg) in a chat app, with the style and voice asked for', async () => {+ const speak = vi.fn(async () => ({ file: '/out/hello.ogg', label: 'OpenAI', ms: 900 }));+ const { run, deliver } = make(true, speak as never);+ const out = await run({ text: 'Hello Sam', voice: 'nova', style: 'warm' });+ expect(speak).toHaveBeenCalledWith('Hello Sam', '/out', expect.objectContaining({ format: 'ogg', voice: 'nova', instructions: 'warm' }));+ expect(deliver).toHaveBeenCalledWith(['/out/hello.ogg'], 'Hello Sam');+ expect(out).toContain('Spoke it with OpenAI in 0.9s');+ expect(out).toContain('- /out/hello.ogg');+ });++ it('mp3 in the apps and the terminal', async () => {+ const speak = vi.fn(async () => ({ file: '/out/a.mp3', label: 'Gemini', ms: 1 }));+ await make(false, speak as never).run({ text: 'x' });+ expect(speak).toHaveBeenCalledWith('x', '/out', expect.objectContaining({ format: 'mp3' }));+ });++ it('no speech service: an error the model can pass on', async () => {+ const { run } = make(true, (async () => { throw new Error('No speech service is set up: add an OpenAI key'); }) as never);+ expect(await run({ text: 'x' })).toBe('Error: No speech service is set up: add an OpenAI key');+ });+});diff --git a/src/capabilities/media/generate-speech.ts b/src/capabilities/media/generate-speech.tsnew file mode 100644index 00000000..5bfc7db0--- /dev/null+++ b/src/capabilities/media/generate-speech.ts@@ -0,0 +1,46 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import type { SpeechService } from '../../media/speech.js';++export interface GenerateSpeechDeps {+ speech: SpeechService;+ outputDir(): string;+ /** Is the current chat a messaging app (where audio goes as a voice note)? */+ inChatApp(): boolean;+ deliver(files: string[], caption: string): Promise<string>;+}++/**+ * Text to speech as a deliverable (ADR-042 phase 2): a voice note, a+ * narration, a spoken summary. Chat apps get it as a voice note; the apps+ * show a player; the terminal prints where it was saved.+ */+export function createGenerateSpeechTool(deps: GenerateSpeechDeps) {+ return tool({+ description: [+ 'Turn text into spoken audio (a voice note, narration, read-out, pronunciation).',+ 'Use when the user asks you to say something out loud, send a voice note or voice message, narrate, or make an audio version.',+ 'Write the text exactly as it should be spoken (no markdown). The audio is saved and sent to the user.',+ ].join(' '),+ inputSchema: zodSchema(z.object({+ text: z.string().min(1).max(4000).describe('What to say, word for word.'),+ voice: z.string().max(120).optional().describe('Only when the user names a voice (e.g. "nova", "Kore").'),+ style: z.string().max(300).optional().describe('How to say it, e.g. "calm and warm", "excited", "slowly, like a teacher".'),+ })),+ execute: async ({ text, voice, style }, { abortSignal }) => {+ try {+ const { file, label, ms } = await deps.speech.speakToFile(text, deps.outputDir(), {+ voice,+ instructions: style,+ // A voice note where the chat plays them (Telegram, WhatsApp); mp3 elsewhere.+ format: deps.inChatApp() ? 'ogg' : 'mp3',+ signal: abortSignal,+ });+ const delivered = await deps.deliver([file], text.slice(0, 200)).catch((err) => `not sent to the chat (${err instanceof Error ? err.message : String(err)})`);+ return [`Spoke it with ${label} in ${(ms / 1000).toFixed(1)}s:`, `- ${file}`, delivered, "Don't send it again with send_file."].join('\n');+ } catch (err) {+ return `Error: ${err instanceof Error ? err.message : String(err)}`;+ }+ },+ });+}diff --git a/src/capabilities/media/generate-video.test.ts b/src/capabilities/media/generate-video.test.tsnew file mode 100644index 00000000..245c6eae--- /dev/null+++ b/src/capabilities/media/generate-video.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it, vi } from 'vitest';+import { createGenerateMusicTool, createGenerateVideoTool } from './generate-video.js';+import type { MediaService } from '../../media/service.js';+import type { MediaJobs } from '../../media/jobs.js';++/** generate_video / generate_music start a background job and end the turn; no model, no job. */+function deps(models: number, channelType = 'telegram') {+ const start = vi.fn<(...args: unknown[]) => { id: string }>(() => ({ id: 'job1' }));+ const media = { chain: async () => Array.from({ length: models }, () => ({})) } as unknown as MediaService;+ const d = {+ media, jobs: { start } as unknown as MediaJobs,+ permissions: { checkFsAccess: async (p: string) => ({ allowed: true, canonical: p }) } as never,+ getCwd: () => '/tmp', outputDir: () => '/out', chat: () => ({ channelType, channelId: `${channelType}:1` }),+ };+ return { d, start };+}+const run = (t: unknown, input: Record<string, unknown>) => (t as { execute: (i: unknown, o: unknown) => Promise<string> }).execute(input, { toolCallId: 't', messages: [] });++describe('generate_video and generate_music', () => {+ it('start a job for this chat and tell the model not to wait', async () => {+ const { d, start } = deps(1);+ const out = await run(createGenerateVideoTool(d), { prompt: 'a cat surfing', aspect: 'portrait' });+ expect(start).toHaveBeenCalledWith('video', 'a cat surfing', { channelType: 'telegram', channelId: 'telegram:1' }, expect.any(Function), { aspect: 'portrait' });+ expect(out).toContain('job job1');+ expect(out).toContain('sent to this chat');+ expect(out).toContain('do not wait');+ });++ it('in the apps the result appears in the conversation', async () => {+ const { d } = deps(1, 'web');+ expect(await run(createGenerateMusicTool(d), { prompt: 'lo-fi' })).toContain('appear in this conversation');+ });++ it('no model: an error now, no job', async () => {+ const { d, start } = deps(0);+ expect(await run(createGenerateVideoTool(d), { prompt: 'x' })).toContain('no video model is set up');+ expect(await run(createGenerateMusicTool(d), { prompt: 'x' })).toContain('no music model is set up');+ expect(start).not.toHaveBeenCalled();+ });+});diff --git a/src/capabilities/media/generate-video.ts b/src/capabilities/media/generate-video.tsnew file mode 100644index 00000000..8f53869a--- /dev/null+++ b/src/capabilities/media/generate-video.ts@@ -0,0 +1,94 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import { existsSync } from 'node:fs';+import type { PermissionManager } from '../permissions.js';+import { resolveToolPath, type CwdSource } from '../filesystem/resolve-path.js';+import { readDenialMessage } from '../filesystem/verified-read.js';+import type { MediaService } from '../../media/service.js';+import type { ChatTarget, MediaJobs } from '../../media/jobs.js';++export interface MediaJobDeps {+ media: MediaService;+ jobs: MediaJobs;+ permissions: PermissionManager;+ getCwd: CwdSource;+ outputDir(): string;+ /** The chat to post the result to when it's ready. */+ chat(): ChatTarget;+}++const started = (kind: string, id: string, chatApp: boolean) => [+ `Started making the ${kind} (job ${id}). It takes a minute or a few;`,+ chatApp ? 'it will be sent to this chat when it is ready.' : 'it will appear in this conversation when it is ready.',+ `Tell the user that in one sentence and end your turn — do not wait, poll, or call generate_${kind} again for the same request.`,+].join(' ');++/**+ * Video (ADR-042 phase 3): an image-to-video or text-to-video model makes+ * a short clip in the background; the result is posted to the chat.+ */+export function createGenerateVideoTool(deps: MediaJobDeps) {+ return tool({+ description: [+ 'Make a short video clip (3–15 seconds, with sound on models that have it) with a video model.',+ 'Use when the user asks for a video, clip, animation or to animate an image. It runs in the background and is sent to the user when ready (minutes).',+ ].join(' '),+ inputSchema: zodSchema(z.object({+ prompt: z.string().min(1).max(4000).describe('The shot in detail: subject, action, camera movement, style, sound.'),+ aspect: z.enum(['landscape', 'portrait']).optional().describe('16:9 (default) or 9:16 for phones and stories.'),+ seconds: z.number().int().min(3).max(15).optional().describe('Length in seconds (default 8).'),+ reference_images: z.array(z.string()).max(6).optional().describe('Paths of images to animate or keep characters consistent with.'),+ model: z.string().optional().describe('Only when the user names a model: "provider::model" from /media.'),+ })),+ execute: async ({ prompt, aspect, seconds, reference_images, model }) => {+ const references: string[] = [];+ for (const ref of reference_images ?? []) {+ const resolved = resolveToolPath(ref, deps.getCwd);+ const check = await deps.permissions.checkFsAccess(resolved, 'read');+ if (!check.allowed) return readDenialMessage(resolved, check);+ const target = check.canonical ?? resolved;+ if (!existsSync(target)) return `Error: reference image not found: ${ref}`;+ references.push(target);+ }+ // Fail now (not in the background) when nothing can make videos.+ if (!(await deps.media.chain('video', model)).length) {+ return `Error: ${model ? `no video model "${model}" on the configured providers.` : 'no video model is set up. A Gemini key (Settings → Voice) gives Gemini Omni video; gateways such as LiteLLM or Mercury Cloud can serve others.'}`;+ }+ const outDir = deps.outputDir();+ const chat = deps.chat();+ const job = deps.jobs.start('video', prompt, chat, async (signal) => {+ const r = await deps.media.generateVideo({ prompt, aspect, seconds, references, model, signal }, outDir);+ return { file: r.file, madeWith: `${r.model.label} · ${r.model.group}`, ...(r.note ? { note: r.note } : {}) };+ }, { aspect: aspect ?? 'landscape' });+ return started('video', job.id, !['web', 'cli', 'internal'].includes(chat.channelType));+ },+ });+}++/** Music (phase 3): a song or instrumental clip, made in the background. */+export function createGenerateMusicTool(deps: MediaJobDeps) {+ return tool({+ description: [+ 'Compose music: a song (with vocals and lyrics) or an instrumental piece, jingle or background track.',+ 'Use when the user asks for music, a song, a beat, a jingle or a soundtrack. It runs in the background and is sent to the user when ready.',+ ].join(' '),+ inputSchema: zodSchema(z.object({+ prompt: z.string().min(1).max(4000).describe('Genre, mood, instruments, tempo, and lyrics or theme for vocals.'),+ seconds: z.number().int().min(5).max(300).optional().describe('Approximate length in seconds.'),+ instrumental: z.boolean().optional().describe('No vocals.'),+ model: z.string().optional().describe('Only when the user names a model: "provider::model" from /media.'),+ })),+ execute: async ({ prompt, seconds, instrumental, model }) => {+ if (!(await deps.media.chain('music', model)).length) {+ return `Error: ${model ? `no music model "${model}".` : 'no music model is set up. A Gemini key (Lyria) or an ElevenLabs key (Settings → Voice) makes music.'}`;+ }+ const outDir = deps.outputDir();+ const chat = deps.chat();+ const job = deps.jobs.start('music', prompt, chat, async (signal) => {+ const r = await deps.media.generateMusic({ prompt, seconds, instrumental, model, signal }, outDir);+ return { file: r.file, madeWith: `${r.model.label} · ${r.model.group}`, ...(r.note ? { note: r.note } : {}) };+ });+ return started('music', job.id, !['web', 'cli', 'internal'].includes(chat.channelType));+ },+ });+}diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex 614c703e..994475ac 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -8,6 +8,9 @@ import { createListDirTool } from './filesystem/list-dir.js';import { createDeleteFileTool } from './filesystem/delete-file.js';import { createEditFileTool } from './filesystem/edit-file.js';import { createSendFileTool } from './filesystem/send-file.js';+import { createGenerateImageTool, type GenerateImageDeps } from './media/generate-image.js';+import { createGenerateSpeechTool, type GenerateSpeechDeps } from './media/generate-speech.js';+import { createGenerateMusicTool, createGenerateVideoTool, type MediaJobDeps } from './media/generate-video.js';import { createSendMessageTool } from './messaging/send-message.js';import { createApproveScopeTool } from './filesystem/approve-scope.js';import { createRunCommandTool } from './shell/run-command.js';@@ -106,6 +109,9 @@ export class CapabilityRegistry {private spotifyClient?: SpotifyClient;private userMemory?: UserMemoryStore;private sendFileHandler?: (filePath: string, channel?: string) => Promise<void>;+ private imageGeneration?: Omit<GenerateImageDeps, 'permissions' | 'getCwd'>;+ private speechGeneration?: GenerateSpeechDeps;+ private mediaJobDeps?: Omit<MediaJobDeps, 'permissions' | 'getCwd'>;private sendMessageHandler?: (content: string) => Promise<void>;private chatCommandContext?: ChatCommandContext;/** Per turn while a turn claims it (ADR-037); the registry-wide cwd otherwise. */@@ -259,6 +265,21 @@ export class CapabilityRegistry {this.sendFileHandler = handler;}+ /** Video and music as background jobs (ADR-042 phase 3): registers generate_video, generate_music. */+ setMediaJobs(deps: Omit<MediaJobDeps, 'permissions' | 'getCwd'>): void {+ this.mediaJobDeps = deps;+ }++ /** Text to speech as a deliverable (ADR-042 phase 2): registers generate_speech. */+ setSpeechGeneration(deps: GenerateSpeechDeps): void {+ this.speechGeneration = deps;+ }++ /** Real image generation (ADR-042): registers generate_image. */+ setImageGeneration(deps: Omit<GenerateImageDeps, 'permissions' | 'getCwd'>): void {+ this.imageGeneration = deps;+ }+setSendMessageHandler(handler: (content: string) => Promise<void>): void {this.sendMessageHandler = handler;}@@ -311,6 +332,18 @@ export class CapabilityRegistry {this.tools.approve_scope = createApproveScopeTool(this.permissions, this.cwdSource);+ if (this.imageGeneration) {+ this.tools.generate_image = createGenerateImageTool({ ...this.imageGeneration, permissions: this.permissions, getCwd: this.cwdSource });+ }+ if (this.speechGeneration) {+ this.tools.generate_speech = createGenerateSpeechTool(this.speechGeneration);+ }+ if (this.mediaJobDeps) {+ const deps = { ...this.mediaJobDeps, permissions: this.permissions, getCwd: this.cwdSource };+ this.tools.generate_video = createGenerateVideoTool(deps);+ this.tools.generate_music = createGenerateMusicTool(deps);+ }+logger.info('Filesystem tools registered');}diff --git a/src/channels/discord.ts b/src/channels/discord.tsindex 3cad4a68..062ba55b 100644--- a/src/channels/discord.ts+++ b/src/channels/discord.ts@@ -1012,6 +1012,7 @@ export class DiscordChannel extends BaseChannel {{ name: 'memory', description: 'View and manage second brain memory (admin only)' },{ name: 'permissions', description: 'Change permission mode' },{ name: 'models', description: 'List providers or switch AI model' },+ { name: 'media', description: 'Image model in use, and choosing one' },{ name: 'unpair', description: 'Reset all Discord DM access (admin only)' },],guildId,diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex 9c0f095d..899fe71e 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -1,4 +1,7 @@import fs from 'node:fs';+import os from 'node:os';+import { currentSpeechEngine, NO_SPEECH_SERVICE } from '../plugins/speech-choice.js';+import { transcribeFile } from '../plugins/transcribe.js';import path from 'node:path';import { Bot, InputFile, InlineKeyboard } from 'grammy';import { autoRetry } from '@grammyjs/auto-retry';@@ -248,6 +251,65 @@ export class TelegramChannel extends BaseChannel {this.emit(msg);});+ // Voice notes and audio messages: heard (transcribed), then handled like text.+ bot.on(['message:voice', 'message:audio'], async (ctx) => {+ const chatId = ctx.chat.id;+ const userId = ctx.from?.id;+ if (!userId || ctx.chat.type !== 'private') return;+ const dedupKey = `${chatId}:${ctx.message.message_id}`;+ if (this.processedMessages.has(dedupKey)) return;+ this.processedMessages.set(dedupKey, Date.now());+ if (!findTelegramApprovedUser(this.config, userId)) {+ await this.sendDirectMessage(chatId, 'This bot is not available to you. Send /start to request access.');+ return;+ }+ const media = ctx.message.voice ?? ctx.message.audio;+ if (!media) return;+ if ((media.file_size ?? 0) > 20 * 1024 * 1024) {+ await this.sendDirectMessage(chatId, '🎤 That recording is too long for me to fetch (Telegram lets bots download up to 20 MB). Could you send a shorter one, or type it?');+ return;+ }+ const engine = currentSpeechEngine('listen');+ if (!engine) {+ await this.sendDirectMessage(chatId, `🎤 I can't listen to voice notes yet: that needs ${NO_SPEECH_SERVICE} Meanwhile, please type it.`);+ return;+ }+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-tg-voice-'));+ let said = '';+ try {+ const file = await ctx.api.getFile(media.file_id);+ if (!file.file_path) throw new Error('Telegram gave no file');+ const res = await fetch(`https://api.telegram.org/file/bot${bot.token}/${file.file_path}`);+ if (!res.ok) throw new Error(`download failed (${res.status})`);+ const local = path.join(dir, `voice${path.extname(file.file_path) || '.ogg'}`);+ fs.writeFileSync(local, Buffer.from(await res.arrayBuffer()));+ said = (await transcribeFile(local, engine)).trim();+ } catch (err) {+ await this.sendDirectMessage(chatId, `🎤 I couldn't understand that voice note (${(err as Error).message.slice(0, 160)}). Could you type it?`);+ return;+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ if (!said) {+ await this.sendDirectMessage(chatId, "🎤 I couldn't hear any words in that. Could you try again, or type it?");+ return;+ }+ this.lastActiveChatId = chatId;+ const caption = ctx.message.caption?.trim();+ this.emit({+ id: ctx.message.message_id.toString(),+ channelId: `telegram:${chatId}`,+ channelType: 'telegram',+ senderId: userId.toString(),+ senderName: ctx.from?.first_name,+ senderRole: this.isAdminUser(userId) ? 'admin' : 'member',+ content: caption ? `${caption}\n${said}` : said,+ timestamp: ctx.message.date * 1000,+ // voiceNote: a reply can come back as a voice note (/media replies).+ metadata: { chatId, messageId: ctx.message.message_id, voiceNote: true },+ });+ });+bot.on('callback_query:data', (ctx) => this.handleCallbackQuery(ctx));bot.catch((err) => {@@ -297,6 +359,11 @@ export class TelegramChannel extends BaseChannel {{ command: 'memory', description: 'View and manage second brain memory' },{ command: 'permissions', description: 'Change permission mode (Ask Me / Allow All)' },{ command: 'models', description: 'List providers or switch AI model' },+ { command: 'image', description: 'Make an image: /image <what to draw>' },+ { command: 'media', description: 'Image and speech models, voice replies' },+ { command: 'say', description: 'Say it as a voice note: /say <text>' },+ { command: 'video', description: 'Make a short video: /video <the shot>' },+ { command: 'music', description: 'Make a song: /music <style, mood, lyrics>' },{ command: 'code', description: 'Programming mode (plan / execute / off)' },{ command: 'agents', description: 'List and manage sub-agents' },{ command: 'bots', description: 'Your bots: roster with controls, cost, outputs, stop/start' },@@ -411,8 +478,18 @@ export class TelegramChannel extends BaseChannel {const inputFile = new InputFile(resolved);try {- if (this.isImageFile(ext)) {+ // Telegram takes photos up to 10 MB as JPEG/PNG/WebP; anything else goes as a file.+ if (this.isImageFile(ext) && fs.statSync(resolved).size <= 10 * 1024 * 1024) {await this.bot.api.sendPhoto(chatId, inputFile, { caption: filename });+ } else if (ext === '.gif') {+ await this.bot.api.sendAnimation(chatId, inputFile, { caption: filename });+ } else if (['.ogg', '.oga', '.opus'].includes(ext)) {+ // Ogg/Opus plays as a voice note; anything Telegram won't take as one goes as audio.+ try {+ await this.bot.api.sendVoice(chatId, inputFile);+ } catch {+ await this.bot.api.sendAudio(chatId, new InputFile(resolved), { title: filename });+ }} else if (this.isAudioFile(ext)) {await this.bot.api.sendAudio(chatId, inputFile, { title: filename });} else if (this.isVideoFile(ext)) {@@ -1737,7 +1814,7 @@ export class TelegramChannel extends BaseChannel {}private isImageFile(ext: string): boolean {- return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg'].includes(ext);+ return ['.jpg', '.jpeg', '.png', '.webp'].includes(ext);}private isAudioFile(ext: string): boolean {diff --git a/src/channels/web-live-steps.test.ts b/src/channels/web-live-steps.test.tsindex 429b9390..be1f46b3 100644--- a/src/channels/web-live-steps.test.ts+++ b/src/channels/web-live-steps.test.ts@@ -42,4 +42,17 @@ describe('web channel live tool events', () => {expect(sent.some((e) => e.type === 'text_done')).toBe(false);expect(sent[2].data).toMatchObject({ name: 'anthropic', provider: 'anthropic' });});++ it('a media tool says what it is making, so a screen can hold its place', () => {+ const ch = new WebChannel('Mercury');+ const sent = capture(ch);+ ch.sendToolStarted('c', 'generate_image', { prompt: 'a fox', aspect: 'landscape', count: 9 }, 's1');+ ch.sendToolStarted('d', 'read_file', { path: 'x' }, 's1');+ expect(sent[0].data?.media).toEqual({ kind: 'image', aspect: 'landscape', count: 4, prompt: 'a fox' });+ expect(sent[1].data).not.toHaveProperty('media');+ ch.sendMediaPending({ id: 'j1', kind: 'video', prompt: 'surf', createdAt: 5, aspect: 'portrait' }, 's1');+ ch.sendMediaReady('ready', [], 's1', 'j1');+ expect(sent[2]).toEqual({ type: 'media_pending', data: { jobId: 'j1', kind: 'video', prompt: 'surf', startedAt: 5, aspect: 'portrait', targetId: 's1' } });+ expect(sent[3].data).toMatchObject({ jobId: 'j1' });+ });});diff --git a/src/channels/web.ts b/src/channels/web.tsindex 8fad9169..16995edc 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -13,6 +13,24 @@ function safeJson(value: unknown): string {try { return JSON.stringify(value) ?? ''; } catch { return String(value); }}+/**+ * What a media tool is making, so a screen can hold a placeholder of the+ * right shape while it works (ADR-042): kind, aspect, how many, the prompt.+ */+function mediaShape(toolName: string, args: Record<string, unknown>): { media?: Record<string, unknown> } {+ const kind = toolName === 'generate_image' ? 'image' : toolName === 'generate_speech' ? 'speech' : toolName === 'generate_video' ? 'video' : toolName === 'generate_music' ? 'music' : null;+ if (!kind) return {};+ const prompt = typeof args.prompt === 'string' ? args.prompt : typeof args.text === 'string' ? args.text : '';+ return {+ media: {+ kind,+ ...(typeof args.aspect === 'string' ? { aspect: args.aspect } : {}),+ ...(typeof args.count === 'number' ? { count: Math.min(Math.max(args.count, 1), 4) } : {}),+ ...(prompt ? { prompt: prompt.slice(0, 200) } : {}),+ },+ };+}+/** "Read src/x.ts", "Run npm test": the tool's label without its icon. */function toolTitle(toolName: string, args: Record<string, unknown>): string {return formatToolStep(toolName, args).replace(/^[^\p{L}\p{N}]+/u, '').trim() || toolName;@@ -32,7 +50,7 @@ interface PendingInteraction {}export interface ChatEvent {- type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'progress' | 'phase' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued' | 'queue_dropped' | 'research' | 'research_plan' | 'research_plan_resolved' | 'notice' | 'owner_approval';+ type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'progress' | 'phase' | 'media_ready' | 'media_pending' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued' | 'queue_dropped' | 'research' | 'research_plan' | 'research_plan_resolved' | 'notice' | 'owner_approval';data?: Record<string, unknown>;}@@ -406,6 +424,7 @@ export class WebChannel extends BaseChannel {}async send(content: string, targetId?: string, elapsedMs?: number, usage?: Record<string, unknown>): Promise<void> {+ if (targetId) this.liveText.delete(targetId);const delivered = this.broadcast({type: 'text_done',data: { fullText: content, elapsedMs, targetId, ...(usage ? { usage } : {}) },@@ -417,11 +436,26 @@ export class WebChannel extends BaseChannel {// Not needed for web — files are referenced in text}+ /** The reply text streamed so far per chat, for a screen that comes back mid-turn. */+ private liveText = new Map<string, string>();++ clearLiveText(targetId: string): void {+ this.liveText.delete(targetId);+ }++ /** What this chat's running reply has written so far ('' when none). */+ liveTextFor(targetId: string): string {+ return this.liveText.get(targetId) ?? '';+ }+async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {let fullText = '';+ // A later round of the same turn writes on after the earlier text.+ const before = targetId ? this.liveText.get(targetId) ?? '' : '';for await (const chunk of content) {fullText += chunk;if (!chunk) continue;+ if (targetId) this.liveText.set(targetId, before + fullText);this.broadcast({type: 'text_delta',data: { text: chunk, targetId },@@ -511,7 +545,7 @@ export class WebChannel extends BaseChannel {: toolName;this.broadcast({type: 'step_start',- data: { id, step, tool: toolName, label: String(label), title: toolTitle(toolName, args), targetId },+ data: { id, step, tool: toolName, label: String(label), title: toolTitle(toolName, args), ...mediaShape(toolName, args), targetId },});}@@ -586,6 +620,20 @@ export class WebChannel extends BaseChannel {this.broadcast({ type: 'plan', data: { steps: plan.steps, updatedAt: plan.updatedAt, targetId } });}+ /**+ * A video or song made in the background is ready (or failed), after its+ * turn ended: a message of its own, so a turn running in the chat now is+ * left alone.+ */+ sendMediaReady(text: string, artifacts: unknown[], targetId?: string, jobId?: string): void {+ this.broadcast({ type: 'media_ready', data: { text, artifacts, targetId, ...(jobId ? { jobId } : {}) } });+ }++ /** A video or song started in the background: a screen holds a placeholder for it until media_ready. */+ sendMediaPending(job: { id: string; kind: string; prompt: string; createdAt: number; aspect?: string }, targetId: string): void {+ this.broadcast({ type: 'media_pending', data: { jobId: job.id, kind: job.kind, prompt: job.prompt.slice(0, 200), startedAt: job.createdAt, ...(job.aspect ? { aspect: job.aspect } : {}), targetId } });+ }+/** Artifacts this turn made (images, PDFs, reports…), for the conversation's live view. */sendArtifacts(items: unknown[], targetId?: string): void {if (!items.length) return;@@ -645,7 +693,7 @@ export class WebChannel extends BaseChannel {* `attachments` are files already on disk (see `web/api/uploads.ts`); them being* present is what lets the runtime hand a photo to a vision model instead of a path.*/- emitMessageInThread(content: string, threadId: string, sessionId?: string, requestId?: string, externalConversationId?: string, messageId?: string, attachments?: ChannelAttachment[], scope?: { programming?: string; cwd?: string; thisComputer?: boolean }): void {+ emitMessageInThread(content: string, threadId: string, sessionId?: string, requestId?: string, externalConversationId?: string, messageId?: string, attachments?: ChannelAttachment[], scope?: { programming?: string; cwd?: string; thisComputer?: boolean; media?: { kind: 'image' | 'video' | 'music'; aspect?: string } }): void {if (this.restrictUser) {throw new Error('Web user is restricted. Disable restrict mode to continue.');}@@ -670,6 +718,8 @@ export class WebChannel extends BaseChannel {...(scope?.cwd ? { programmingCwd: scope.cwd } : {}),// Sent from this computer (Mercury Desktop or an attached terminal here): /server is allowed....(scope?.thisComputer ? { thisComputer: true } : {}),+ // The desktop's Image switch: this message asks for an image (media/intent.ts).+ ...(scope?.media ? { media: scope.media } : {}),},};this.emit(msg);diff --git a/src/core/agent.ts b/src/core/agent.tsindex 70accbc3..910decfb 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1,7 +1,7 @@import { generateText, streamText, stepCountIs } from 'ai';import path from 'node:path';-import { homedir } from 'node:os';-import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';+import { homedir, tmpdir } from 'node:os';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';import type { ChannelMessage, ChannelType } from '../types/channel.js';import type { ProviderRegistry } from '../providers/registry.js';import type { Identity } from '../soul/identity.js';@@ -138,6 +138,10 @@ import { runReflection } from '../learning/reflection.js';import { createOwnerSectionsMemo } from '../learning/owner-brief.js';import type { ApplyResult } from '../memory/beliefs.js';import { TurnTrace, toolSummary } from './turn-trace.js';+import { applyMediaIntent } from '../media/intent.js';+import { getSpeechService, speakableText, voiceReplyWanted } from '../media/speech.js';+import { loadMediaPrefs } from '../media/prefs.js';+import { mediaJobs, type MediaJob } from '../media/jobs.js';import { claimEffortChat } from '../utils/model-prefs.js';import { TurnUsage, billingEntries, type SourceUsageTotals, type StepUsageLike, type TurnUsageTotals } from './turn-usage.js';@@ -1477,6 +1481,18 @@ export class Agent {}/** Every running turn, oldest first: what each chat is doing (for /progress, status screens). */+ /**+ * The reply a chat is working on right now, as far as it got: thinking and+ * tool steps (with what still runs), and what it is doing. Undefined when+ * the chat is idle. Lets a screen that left the chat and came back show+ * the turn again instead of a blank.+ */+ liveTurn(id: string): { startedAt: number; activity: string; trace: import('./turn-trace.js').StoredTrace } | undefined {+ const turn = this.turnForSession(id) ?? this.turnForChannel(id);+ if (!turn || turn.done) return undefined;+ return { startedAt: turn.startedAt, activity: turn.activity, trace: turn.trace.peek(turn.startedAt) };+ }+runningTurns(): Array<{ laneKey: string; channelType: string; channelId: string; sessionId?: string; content: string; activity: string; startedAt: number; completedSteps: number; narrative: import('../utils/tool-label.js').NarrativeStep[] }> {return [...this.activeTurns.values()].sort((a, b) => a.startedAt - b.startedAt)@@ -1804,6 +1820,8 @@ export class Agent {|| (turn !== undefined && laneKeyFor(m) === turn.laneKey), label);const channelId = turn?.message.channelId ?? target.channelId;const halted = this.supervisor && channelId ? await this.supervisor.haltForChannel(channelId) : [];+ // Videos and songs this chat is still making stop too (ADR-042).+ const jobsStopped = channelId ? mediaJobs()?.stop({ channelId }) ?? 0 : 0;const others = [...this.activeTurns.values()].filter((t) => t !== turn && t.id !== caller?.id && !t.abort?.signal.aborted).length;// Nothing else running anywhere: the full stop it always was (locks@@ -1816,18 +1834,20 @@ export class Agent {}const tail = cleared ? ' Locks released, task board cleared.' : '';const elsewhere = others > 0 ? ` ${others} task${others === 1 ? '' : 's'} in other chats keep${others === 1 ? 's' : ''} running — /halt stops everything.` : '';- if (!turn && halted.length === 0 && dropped === 0) {+ if (!turn && halted.length === 0 && dropped === 0 && jobsStopped === 0) {return cleared ? `Nothing was running.${tail}` : `Nothing is running in this chat.${elsewhere}`;}const parts = [turn ? 'Stopped this chat\'s task' : null,halted.length ? `halted ${halted.length} sub-agent${halted.length === 1 ? '' : 's'} it started` : null,dropped ? `dropped ${dropped} waiting message${dropped === 1 ? '' : 's'}` : null,+ jobsStopped ? `stopped ${jobsStopped} video or song being made` : null,].filter(Boolean) as string[];parts[0] = parts[0].charAt(0).toUpperCase() + parts[0].slice(1);return `${parts.join(', ')}.${tail}${elsewhere}`;}this.dropWaiting(() => true, label);+ mediaJobs()?.stop();let stoppedTurns = 0;for (const turn of this.activeTurns.values()) {if (caller && turn.id === caller.id) continue;@@ -2397,6 +2417,72 @@ export class Agent {return ch;}+ /**+ * A video or song finished (or failed) after its turn ended (media/jobs.ts):+ * post it to the chat that asked. The apps get it as a new message with+ * the file attached (kept with the conversation, so a reopened chat shows+ * it); chat apps get a note and the file; the terminal a notice with the path.+ */+ async deliverMediaJob(job: MediaJob, note?: string): Promise<void> {+ const channel = this.channels.get(job.chat.channelType as Parameters<ChannelRegistry['get']>[0]);+ const what = job.kind === 'video' ? 'video' : 'music';+ const icon = job.kind === 'video' ? '🎬' : '🎵';+ const text = job.status === 'done' && job.file+ ? `${icon} Your ${what} is ready${job.madeWith ? ` (${job.madeWith})` : ''}.${note ? `\n\n${note.trim().slice(0, 500)}` : ''}`+ : `⚠ I couldn't make the ${what}: ${job.error ?? 'it failed'}`;+ const file = job.status === 'done' && job.file && existsSync(job.file) ? job.file : undefined;+ if (job.chat.channelType === 'web') {+ const sessionId = job.chat.sessionId ?? job.chat.channelId;+ let refs: ReturnType<typeof artifactRef>[] = [];+ if (file) {+ try {+ const kind = /\.(mp4|webm|mov|m4v)$/i.test(file) ? 'video' : 'audio';+ refs = [artifactRef(artifactStore().add({ threadId: sessionId, path: file, kind, tool: `generate_${job.kind}` }))];+ } catch (err) { logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Keeping a media job artifact failed'); }+ }+ try {+ this.sessions.appendMessage(sessionId, {+ role: 'assistant',+ content: text,+ externalMessageId: `media-job:${job.id}`,+ metadata: { channelType: 'web', channelId: job.chat.channelId, ...(refs.length ? { artifacts: refs } : {}) },+ });+ } catch { /* the chat was deleted meanwhile */ }+ if (channel instanceof WebChannel) channel.sendMediaReady(text, refs, job.chat.channelId, job.id);+ return;+ }+ if (!channel) return;+ if (channel instanceof CLIChannel) {+ channel.sendSystemNotice(`${text}${file ? `\n ${file}` : ''}`);+ return;+ }+ await channel.send(text, job.chat.channelId).catch(() => {});+ if (file) await channel.sendFile(file, job.chat.channelId);+ }++ /**+ * Say the reply as a voice note in a chat app: when the owner sent a voice+ * note ("mirror", the default), on every reply ("always"), or never+ * ("off"); /media replies. The text was already sent: this is extra and+ * never fails the turn.+ */+ private async maybeVoiceReply(channel: { sendFile(path: string, targetId?: string): Promise<void> }, msg: ChannelMessage, text: string): Promise<void> {+ if (this.turnCancelled() || !voiceReplyWanted(msg.channelType, msg.metadata?.voiceNote === true, loadMediaPrefs().speech?.replies)) return;+ const spoken = speakableText(text);+ if (!spoken || /^\s*⏹/.test(text)) return;+ const speech = getSpeechService();+ if (!speech) return;+ const dir = mkdtempSync(path.join(tmpdir(), 'mercury-voice-reply-'));+ try {+ const { file } = await speech.speakToFile(spoken, dir, { format: 'ogg' });+ await channel.sendFile(file, msg.channelId);+ } catch (err) {+ logger.warn({ err: err instanceof Error ? err.message : String(err), channel: msg.channelType }, 'Voice reply failed (the text reply was sent)');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }+/*** A note while the turn keeps working ("Checking my work…"). On the web* channel a plain send is a finished reply, which would end the turn on@@ -2777,6 +2863,9 @@ export class Agent {await this.runQueuedItem(item);} finally {this.rememberLaneCwd(laneKey, this.capabilities.getCwd());+ // However the turn ended (reply, error, stop), its streamed text is no longer "live".+ const ch = this.channels.getChannelForMessage(msg);+ if (ch instanceof WebChannel) ch.clearLiveText(msg.channelId);}}))).catch((err) => {logger.error({ err, turn: turn.id }, 'Turn failed outside its handler');@@ -3788,6 +3877,8 @@ export class Agent {// `#skill-name` is the user's explicit pick; any other skill choice is// the model's (ADR-040).this.applyExplicitSkillPick(msg, trimmed, messages);+ // `/image …` or the desktop's Image switch: an image model makes it (ADR-042).+ applyMediaIntent(msg, trimmed, messages);this.lifecycle.transition('responding');@@ -5483,6 +5574,8 @@ export class Agent {// Progress, without the typing refresh: a "thinking" event after the// reply would make a screen think a new turn started.this.lastProgressAt = Date.now();+ // A chat-app reply can follow as a voice note (ADR-042 phase 2).+ if (channel) void this.maybeVoiceReply(channel, msg, finalText);} else {replyDelivered();logger.debug('Internal prompt processed, no channel response needed');diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.tsindex 8a02cfb9..dbc0f78c 100644--- a/src/core/commands/chat-command.ts+++ b/src/core/commands/chat-command.ts@@ -37,6 +37,12 @@ import {import { MAX_STEPS } from '../agent.js';import { displayModelName, effortFor, effortLabel, setChatEffort, setModelPref, type ReasoningLevel } from '../../utils/model-prefs.js';import { discoverReasoningCaps } from '../../providers/reasoning-discovery.js';+import { mediaService } from '../../media/runtime.js';+import { setMediaDefault, setSpeechPrefs } from '../../media/prefs.js';+import { getSpeechService, type SpeechService } from '../../media/speech.js';+import { mediaJobs } from '../../media/jobs.js';+import { unusableReason, type MediaService } from '../../media/service.js';+import type { MediaModel } from '../../media/catalog.js';import path from 'node:path';import type { ChannelType } from '../../types/channel.js';import { createProvider, ProviderRegistry as ProviderRegistryImpl } from '../../providers/registry.js';@@ -289,6 +295,28 @@ export async function handleChatCommand(agent: Agent, content: string, channelTyreturn true;}+ if (cmd === '/media' || cmd.startsWith('/media ') || cmd === '/image' || cmd === '/imagine' || cmd === '/img' || cmd === '/video' || cmd === '/music' || cmd === '/song') {+ const media = mediaService();+ if (!media) {+ await channel.send('Media generation is not available in this process.', channelId);+ return true;+ }+ const arg = cmd.startsWith('/media') ? trimmed.slice('/media'.length).trim() : '';+ const reply = await mediaCommand(media, arg, getSpeechService());+ await channel.send(reply.text, channelId);+ // On an owner screen, offer the models as a picker.+ if (reply.pick && isOwnerScreen(channel, channelType) && reply.pick.length > 1) {+ const labels = [...reply.pick.map((m) => `${m.label} · ${m.group}`), 'Automatic', 'Keep as is'];+ const picked = await pickOnOwnerScreen(agent, channel, channelType, channelId, 'Default image model?', labels);+ if (picked && picked !== 'Keep as is') {+ const chosen = picked === 'Automatic' ? null : reply.pick[labels.indexOf(picked)]?.ref ?? null;+ setMediaDefault('image', chosen);+ await channel.send(chosen ? `Images now use **${picked}**.` : 'Images now use the best model available automatically.', channelId);+ }+ }+ return true;+ }+if (cmd === '/effort' || cmd.startsWith('/effort ')) {await channel.send(await effortCommand(agent, trimmed.slice('/effort'.length).trim().toLowerCase()), channelId);return true;@@ -1868,3 +1896,153 @@ function effortStatusLine(agent: Agent): string {}}+/**+ * /media (ADR-042): which model makes images, and choosing it.+ * /media the image model in use and the ones available+ * /media image <n|ref|auto> set the default (a number from the list, "provider::model", or auto)+ * /media refresh ask the providers again+ * /image (no prompt) the same overview; /image <prompt> makes one+ */+export async function mediaCommand(media: MediaService, arg: string, speech: SpeechService | null = null): Promise<{ text: string; pick?: MediaModel[] }> {+ const [verb, ...rest] = arg.split(/\s+/).filter(Boolean);+ if (speech && (verb === 'speech' || verb === 'voice' || verb === 'replies')) {+ return { text: await speechVerb(speech, verb, rest.join(' ').trim()) };+ }+ if (verb === 'video' || verb === 'videos' || verb === 'music' || verb === 'song') {+ return { text: await jobKindVerb(media, verb.startsWith('video') ? 'video' : 'music', rest.join(' ').trim()) };+ }+ if (verb === 'jobs') return { text: jobsSummary() };+ const refresh = verb === 'refresh';+ const setup = await media.imageSetup({ refresh });+ const list = setup.models;+ const numbered = list.slice(0, 30);+ if (verb === 'image' || verb === 'images') {+ const value = rest.join(' ').trim();+ if (!value) return { text: 'Usage: `/media image <number|provider::model|auto>` — see `/media` for the list.' };+ if (/^(auto|automatic|default|clear)$/i.test(value)) {+ setMediaDefault('image', null);+ return { text: `Images now use the best model available automatically${setup.auto ? ` (now: **${setup.auto.label}** · ${setup.auto.group})` : ''}.` };+ }+ const byNumber = /^\d+$/.test(value) ? numbered[Number(value) - 1] : undefined;+ const chosen = byNumber ?? list.find((m) => m.ref === value || m.model === value);+ if (!chosen) return { text: `No image model "${value}". Use a number from \`/media\`, or provider::model.` };+ setMediaDefault('image', chosen.ref);+ return { text: `Images now use **${chosen.label}** · ${chosen.group}.` };+ }+ if (!list.length) {+ return {+ text: [+ '**Images** · no image model found on your providers.',+ 'Image models come from providers that serve them: OpenAI (gpt-image), OpenRouter (Gemini image, FLUX, …), LiteLLM, AI/ML API, Atlas Cloud, Runcrate, Mercury Cloud, or an Ollama image model.',+ 'Add one with `mercury doctor` (or Mercury Desktop → Settings → AI), then `/media refresh`.',+ ].join('\n'),+ };+ }+ const inUse = setup.default?.available+ ? list.find((m) => m.ref === setup.default!.ref)+ : setup.auto;+ const lines = [+ `**Images** · ${inUse ? `${inUse.label} · ${inUse.group}` : 'none'} (${setup.default?.available ? 'your default' : 'automatic'})`,+ ...(setup.default && !setup.default.available ? [`Your default (${setup.default.ref}) isn't offered right now, so the automatic pick is used.`] : []),+ '',+ ...numbered.map((m, i) => `${i + 1}. ${m.label} · ${m.group}${m.canEdit ? '' : ' (no edits)'}${inUse?.ref === m.ref ? ' ← in use' : ''}${unusableReason(m.ref) ? ` (skipped: ${unusableReason(m.ref)})` : ''}`),+ ...(list.length > numbered.length ? [`…and ${list.length - numbered.length} more`] : []),+ '',+ 'Make one: `/image <what to draw>` (add `--landscape` or `--portrait`). Change the default: `/media image <number>` or `/media image auto`.',+ ...(speech ? ['', await speechSummary(speech)] : []),+ '',+ await jobKindSummary(media, 'video'),+ '',+ await jobKindSummary(media, 'music'),+ ];+ return { text: lines.join('\n'), pick: numbered };+}++const REPLY_LABEL = { off: 'never', mirror: 'when you send a voice note', always: 'on every reply' } as const;++/** The Speech part of /media. */+async function speechSummary(speech: SpeechService): Promise<string> {+ const [target, options] = await Promise.all([speech.target(), speech.options()]);+ const prefs = speech.prefs();+ const replies = prefs.replies ?? 'mirror';+ if (!target) {+ return '**Speech** · no speech service. Add an OpenAI key (Settings → Models) or a Gemini, Deepgram or ElevenLabs key (Settings → Voice).';+ }+ return [+ `**Speech** · ${target.label}${target.voice ? ` · voice ${target.voice}` : ''} (${prefs.choice ? 'your choice' : 'from Settings → Voice'})`,+ ...options.slice(0, 20).map((o, i) => `${i + 1}. ${o.label} · ${o.group}${o.id === target.id ? ' ← in use' : ''}`),+ `Voice-note replies in chat apps: ${REPLY_LABEL[replies]}.`,+ 'Say something: `/say <text>`. Change: `/media speech <number|auto>`, `/media voice <name>`, `/media replies off|mirror|always`.',+ ].join('\n');+}++async function speechVerb(speech: SpeechService, verb: string, value: string): Promise<string> {+ try {+ if (verb === 'replies') {+ if (!['off', 'mirror', 'always'].includes(value)) return 'Usage: `/media replies off|mirror|always` — mirror answers a voice note with a voice note.';+ setSpeechPrefs({ replies: value as 'off' | 'mirror' | 'always' });+ return `Voice-note replies: ${REPLY_LABEL[value as keyof typeof REPLY_LABEL]}.`;+ }+ if (verb === 'voice') {+ if (!value) {+ const target = await speech.target();+ const option = (await speech.options()).find((o) => o.id === target?.id);+ return `Voice: ${target?.voice ?? 'the service default'}.${option?.voices.length ? ` Voices: ${option.voices.join(', ')}.` : ''} Use \`/media voice <name>\` or \`/media voice default\`.`;+ }+ setSpeechPrefs({ voice: /^(default|auto|clear)$/i.test(value) ? null : value });+ return /^(default|auto|clear)$/i.test(value) ? "Voice: the service's default." : `Voice: **${value}**.`;+ }+ if (!value) return 'Usage: `/media speech <number|auto>` — see `/media` for the list.';+ if (/^(auto|default|clear)$/i.test(value)) {+ setSpeechPrefs({ choice: null });+ const t = await speech.target();+ return `Speech now follows Settings → Voice${t ? ` (now: **${t.label}**)` : ''}.`;+ }+ const options = await speech.options();+ const chosen = /^\d+$/.test(value) ? options[Number(value) - 1] : options.find((o) => o.id === value || o.label.toLowerCase() === value.toLowerCase());+ if (!chosen) return `No speech service "${value}". Use a number from \`/media\`.`;+ setSpeechPrefs({ choice: chosen.id });+ return `Speech now uses **${chosen.label}** · ${chosen.group}.`;+ } catch (err) {+ return `Couldn't change that: ${err instanceof Error ? err.message : String(err)}`;+ }+}++/** The Video / Music part of /media. */+async function jobKindSummary(media: MediaService, kind: 'video' | 'music'): Promise<string> {+ const setup = await media.setup(kind);+ const title = kind === 'video' ? '**Video**' : '**Music**';+ if (!setup.models.length) {+ return `${title} · none found. ${kind === 'video' ? 'A Gemini key (Settings → Voice) gives Gemini Omni video; gateways (LiteLLM, Mercury Cloud) can serve others.' : 'A Gemini key (Lyria) or an ElevenLabs key (Settings → Voice) makes music.'}`;+ }+ const inUse = setup.default?.available ? setup.models.find((m) => m.ref === setup.default!.ref) : setup.auto;+ return [+ `${title} · ${inUse ? `${inUse.label} · ${inUse.group}` : 'none'} (${setup.default?.available ? 'your default' : 'automatic'})`,+ ...setup.models.slice(0, 15).map((m, i) => `${i + 1}. ${m.label} · ${m.group}${inUse?.ref === m.ref ? ' ← in use' : ''}${unusableReason(m.ref) ? ` (skipped: ${unusableReason(m.ref)})` : ''}`),+ kind === 'video'+ ? 'Make one: `/video <the shot>` (`--portrait`, `--seconds 6`). Change: `/media video <number|auto>`. It arrives here when ready.'+ : 'Make one: `/music <genre, mood, lyrics>` (`--instrumental`, `--seconds 60`). Change: `/media music <number|auto>`.',+ ].join('\n');+}++async function jobKindVerb(media: MediaService, kind: 'video' | 'music', value: string): Promise<string> {+ if (!value) return jobKindSummary(media, kind);+ if (/^(auto|automatic|default|clear)$/i.test(value)) {+ setMediaDefault(kind, null);+ return `${kind === 'video' ? 'Videos' : 'Music'} now use the best model available automatically.`;+ }+ const list = await media.models(kind);+ const chosen = /^\d+$/.test(value) ? list[Number(value) - 1] : list.find((m) => m.ref === value || m.model === value);+ if (!chosen) return `No ${kind} model "${value}". Use a number from \`/media ${kind}\`.`;+ setMediaDefault(kind, chosen.ref);+ return `${kind === 'video' ? 'Videos' : 'Music'} now use **${chosen.label}** · ${chosen.group}.`;+}++/** /media jobs: videos and songs being made, and the last few made. */+function jobsSummary(): string {+ const list = mediaJobs()?.list(undefined, 10) ?? [];+ if (!list.length) return 'No videos or songs made yet. `/video <shot>` or `/music <style>` makes one.';+ const ago = (t: number) => { const s = Math.round((Date.now() - t) / 1000); return s < 90 ? `${s}s ago` : s < 5400 ? `${Math.round(s / 60)} min ago` : `${Math.round(s / 3600)} h ago`; };+ return ['**Media jobs**', ...list.map((j) => `• ${j.kind === 'video' ? '🎬' : '🎵'} ${j.prompt.slice(0, 60)}${j.prompt.length > 60 ? '…' : ''} — ${j.status === 'running' ? `making (started ${ago(j.createdAt)})` : j.status === 'done' ? `ready ${ago(j.finishedAt ?? j.createdAt)}` : `failed: ${(j.error ?? '').slice(0, 80)}`}`)].join('\n');+}+diff --git a/src/core/commands/slash-list.ts b/src/core/commands/slash-list.tsindex 4814b416..8a561924 100644--- a/src/core/commands/slash-list.ts+++ b/src/core/commands/slash-list.ts@@ -96,6 +96,19 @@ export const SLASH_COMMANDS: readonly string[] = ['/memory','/models','/models use ',+ '/image ',+ '/media',+ '/media image ',+ '/media refresh',+ '/media speech ',+ '/media voice ',+ '/media replies ',+ '/say ',+ '/video ',+ '/music ',+ '/media video ',+ '/media music ',+ '/media jobs','/effort','/effort default','/effort global ',diff --git a/src/core/system-prompt.ts b/src/core/system-prompt.tsindex 54ffc90a..561f77b5 100644--- a/src/core/system-prompt.ts+++ b/src/core/system-prompt.ts@@ -43,7 +43,8 @@ export const TOOL_USAGE_GUIDELINES = `**Tool Usage Guidelines:**- Use run_command for building, testing, installing dependencies, running the project, git, and for real work on data: converting formats, processing many files, extracting, transforming, downloading.- Pick the strongest tool for the job before doing anything by hand. For conversions and bulk work (EPUB/PDF/DOCX/HTML to Markdown, images, audio/video, CSV/JSON, renaming or reorganising many files) use an established CLI or library — pandoc, ffmpeg, ImageMagick, jq, a Python package such as ebooklib, markdownify or pypdf — through run_command, or one short script that handles every file in one run. Never read and rewrite many files one by one yourself.- Not sure what the best tool is? Spend one web_search finding out. Check it is installed (e.g. \`command -v pandoc\`, \`python3 -c "import ebooklib"\`) and install it or fall back to the next best option.-- After a bulk or conversion step, check the output (count the files, open a sample) before saying it is done.`;+- After a bulk or conversion step, check the output (count the files, open a sample) before saying it is done.+- Asked for an image (a picture, photo, illustration, logo, poster, artwork), call generate_image; to change one, call it again with the image in reference_images. Write SVG or code only when the user asks for SVG, a diagram, a chart or a vector file. If generate_image says no image model is set up, tell the user that, and how to add one, instead of drawing it as code.`;/*** How to work in plain chat (programming mode off). Mercury Code has itsdiff --git a/src/core/turn-trace.ts b/src/core/turn-trace.tsindex 36d3b8c8..c0c098d7 100644--- a/src/core/turn-trace.ts+++ b/src/core/turn-trace.ts@@ -97,6 +97,15 @@ export class TurnTrace {return this.items.length;}+ /**+ * The trace so far, without ending anything: running tools stay running,+ * thinking still streaming stays open. For a screen that comes back to a+ * chat whose reply is still being worked on.+ */+ peek(startedAt: number): StoredTrace {+ return { startedAt, endedAt: this.now(), items: this.items.map((item) => ({ ...item })) };+ }+/** The trace to keep with the reply; undefined when the turn neither thought nor ran anything. */snapshot(startedAt: number): StoredTrace | undefined {this.reasoningEnded();diff --git a/src/index.ts b/src/index.tsindex a032cdf5..efb4172b 100644--- a/src/index.ts+++ b/src/index.ts@@ -1,4 +1,10 @@import { readFileSync, writeFileSync, existsSync, statSync, chmodSync } from 'node:fs';+import { MediaJobs, setMediaJobs } from './media/jobs.js';+import { mediaKeySources } from './media/key-sources.js';+import { SpeechService, setSpeechService } from './media/speech.js';+import { MediaService } from './media/service.js';+import { setMediaService } from './media/runtime.js';+import { outputRoot } from './artifacts/output-dir.js';import { createHash, randomBytes } from 'node:crypto';import { fileURLToPath } from 'node:url';import { dirname, join, resolve as pathResolve } from 'node:path';@@ -2722,6 +2728,65 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {setGitHubToken(process.env.GITHUB_TOKEN);}+ // Image generation (ADR-042): image models on the configured providers.+ const media = new MediaService({+ sources: () => [+ ...providers.listAvailable().flatMap((name) => {+ const p = providers.get(name);+ return p ? [{ name, baseUrl: p.getBaseUrl(), endpoint: () => p.mediaEndpoint() }] : [];+ }),+ // Keys saved for voice (Settings → Voice) make media too: Gemini (images, Omni video, Lyria music), ElevenLabs (music).+ ...mediaKeySources(),+ ],+ currentProvider: () => providers.getDefault()?.name,+ });+ setMediaService(media);+ const mediaOutputDir = () => {+ // A chat works in its own artifacts folder; the terminal's media go to Images/ there, not into a project.+ const root = outputRoot(config.artifacts?.outputDir);+ const cwd = capabilities.getCwd();+ return cwd.startsWith(root) ? cwd : join(root, 'Images');+ };+ const deliverMedia = async (files: string[]): Promise<string> => {+ const { channelId, channelType } = capabilities.getChannelContext();+ if (channelType === 'web') return 'It is shown in the app.';+ if (channelType === 'cli') return 'The terminal shows its path; it is also in Mercury Desktop → Artifacts.';+ if (channelType === 'internal') return 'Saved.';+ const channel = channels.get(channelType as Parameters<typeof channels.get>[0]);+ if (!channel) return 'Saved (this chat can\'t receive files).';+ for (const file of files) await channel.sendFile(file, channelId);+ return 'Sent to this chat.';+ };+ const speech = new SpeechService(media.sourcesForSpeech());+ setSpeechService(speech);+ capabilities.setSpeechGeneration({+ speech,+ outputDir: mediaOutputDir,+ inChatApp: () => !['web', 'cli', 'internal'].includes(capabilities.getChannelContext().channelType),+ deliver: deliverMedia,+ });+ capabilities.setImageGeneration({ media, outputDir: mediaOutputDir, deliver: deliverMedia });+ // Videos and songs take minutes: background jobs, posted to the chat when ready (phase 3).+ // `agent` is created below; jobs only finish after it exists.+ const jobs = new MediaJobs(+ (job, note) => agentRef.current ? agentRef.current.deliverMediaJob(job, note) : Promise.resolve(),+ undefined,+ // The apps hold a placeholder for it until it arrives.+ (job) => { if (job.chat.channelType === 'web') (channels.get('web') as WebChannel | undefined)?.sendMediaPending(job, job.chat.channelId); },+ );+ setMediaJobs(jobs);+ const agentRef: { current: Agent | null } = { current: null };+ capabilities.setMediaJobs({+ media,+ jobs,+ outputDir: mediaOutputDir,+ chat: () => {+ const { channelId, channelType } = capabilities.getChannelContext();+ const sessionId = agentRef.current?.currentChatKey();+ return { channelType, channelId, ...(channelType === 'web' && sessionId ? { sessionId } : {}) };+ },+ });+capabilities.registerAll();const mcpConfig = validateMcpConfig(config.mcp);@@ -2739,7 +2804,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {void mcpManager.connectAll();}- const agent = new Agent(+ const agent = agentRef.current = new Agent(config, providers, identity, shortTerm, longTerm, episodic, userMemory, channels, tokenBudget, capabilities, scheduler, sessions,async ({ userMessage, assistantMessage, providerName }) => {const provider = providers.get(providerName) ?? providers.getDefault();@@ -2748,6 +2813,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {},);+ // Videos or songs cut off by the last restart: tell their chats (once the channels are up).+ // Only the process that runs them: a terminal attached to the daemon must not touch the daemon's jobs.+ if (!daemonOwnsRuntime) setTimeout(() => { void jobs.recover().catch(() => {}); }, 10_000).unref?.();agent.setSkillLoader(skillLoader);agent.terminalOnly = daemonOwnsRuntime;@@ -3572,6 +3640,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {channelType: t.channelType, channelId: t.channelId, startedAt: t.startedAt, activity: t.activity, steps: t.completedSteps,})),waiting: () => agent.waitingChats(),+ live: (id) => agent.liveTurn(id),limit: () => ({ limit: agent.governor.limit(), configured: config.concurrency?.maxTurns ?? 0, auto: autoTurnLimit(machineFacts()) }),setLimit: (configured) => {config.concurrency = { ...(config.concurrency ?? {}), maxTurns: configured };diff --git a/src/media/catalog.ts b/src/media/catalog.tsnew file mode 100644index 00000000..e2d5b4eb--- /dev/null+++ b/src/media/catalog.ts@@ -0,0 +1,354 @@+/**+ * Which of the owner's configured providers can make images, and with which+ * models (ADR-042). Model ids change too fast to hard-code (Sora's API and+ * Imagen were retired in 2026), so they are discovered from each provider:+ *+ * OpenRouter /api/v1/models?output_modalities=image (generated via chat, modalities)+ * LiteLLM /model/info model_info.mode == "image_generation"+ * any /models output_modalities ∋ "image" (Runcrate, Atlas Cloud, Mercury Cloud),+ * type ∋ "image" (AI/ML API), or a known image-model name+ * (gpt-image-*, dall-e-*, flux*, imagen*, seedream*, …)+ * Ollama /api/tags names of its (experimental) image models+ *+ * Everything but OpenRouter is called through the OpenAI Images API+ * (/images/generations, /images/edits), which those servers expose.+ * Cached for a day in ~/.mercury/media-models.json; a failed provider keeps+ * what was known about it.+ */+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';+import { isOpenRouterUrl } from '../utils/model-prefs.js';+import { humanizeModelName, modelGroupLabel } from '../utils/model-prefs.js';+import { logger } from '../utils/logger.js';+import type { MediaEndpoint } from '../providers/base.js';++export type MediaKind = 'image' | 'speech' | 'video' | 'music';++/** How a model is called: the OpenAI Images API, or OpenRouter's chat with image output. */+/**+ * How a model is called: the OpenAI Images / Videos / Speech APIs,+ * OpenRouter's chat with image output, Gemini (generateContent for images,+ * the Interactions API for Omni video and Lyria music), or ElevenLabs Music.+ */+export type ImageBackend = 'openai-images' | 'openrouter-chat' | 'openai-speech' | 'openai-videos' | 'gemini-image' | 'gemini-omni' | 'gemini-lyria' | 'elevenlabs-music';++/** Sources that aren't chat providers: keys saved for voice (Settings → Voice). */+export const GEMINI_SOURCE = 'gemini';+export const ELEVENLABS_SOURCE = 'elevenlabs';++export interface MediaModel {+ /** "provider::model" — what settings and /media store. */+ ref: string;+ provider: string;+ model: string;+ kind: MediaKind;+ backend: ImageBackend;+ label: string;+ group: string;+ /** Takes reference images (edits). */+ canEdit: boolean;+}++/** A configured provider Mercury can ask about media models. */+export interface MediaSource {+ name: string;+ /** The provider's chat base URL (decides OpenRouter / Ollama handling). */+ baseUrl: string;+ endpoint(): Promise<MediaEndpoint | undefined>;+}++const TTL_MS = 24 * 60 * 60 * 1000;+const TIMEOUT_MS = 5000;++/** Image models by name, for servers whose model list says nothing more. */+export const IMAGE_MODEL_NAME = /(^|[/:._-])(gpt-image|chatgpt-image|dall-e|dalle|flux|imagen|seedream|seededit|stable-diffusion|sdxl|sd3|sd-?3\.5|hidream|recraft|ideogram|qwen-image|z-image|nano-banana|playground-v|kandinsky|grok-(2-)?image|grok-imagine-image|cogview|hunyuan-image|wan.*-t2i|gemini-[\w.-]*-image)/i;+/** Names that look like image models but generate something else (or only read images). */+const NOT_IMAGE_OUTPUT = /(vision|-vl\b|embedding|caption|ocr|upscal|video|t2v|i2v|tts|audio)/i;++export function refOf(provider: string, model: string): string {+ return `${provider}::${model}`;+}++export function parseRef(ref: string): { provider: string; model: string } | null {+ const i = ref.indexOf('::');+ if (i <= 0 || i === ref.length - 2) return null;+ return { provider: ref.slice(0, i), model: ref.slice(i + 2) };+}++function model(provider: string, id: string, backend: ImageBackend): MediaModel {+ const editable = backend === 'openrouter-chat'+ || /gpt-image|chatgpt-image|dall-e-2|flux.*(kontext|edit|fill)|seededit|qwen-image-edit|nano-banana|gemini-[\w.-]*-image/i.test(id);+ return {+ ref: refOf(provider, id),+ provider,+ model: id,+ kind: 'image',+ backend,+ label: /dall-e-?(\d)/i.test(id) ? `DALL·E ${/dall-e-?(\d)/i.exec(id)![1]}` : humanizeModelName(id),+ group: modelGroupLabel(provider, id),+ canEdit: editable,+ };+}++async function getJson(url: string, headers: Record<string, string>, fetchImpl: typeof fetch): Promise<unknown> {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);+ try {+ const res = await fetchImpl(url, { headers, signal: ctrl.signal });+ if (!res.ok) return undefined;+ return await res.json();+ } catch {+ return undefined;+ } finally {+ clearTimeout(timer);+ }+}++interface ListedModel {+ id?: string;+ type?: string;+ output_modalities?: unknown;+ architecture?: { output_modalities?: unknown };+}++/** Is a /models entry an image generator? */+export function isImageModelEntry(m: ListedModel): boolean {+ const id = typeof m.id === 'string' ? m.id : '';+ if (!id) return false;+ const outputs = Array.isArray(m.output_modalities) ? m.output_modalities+ : Array.isArray(m.architecture?.output_modalities) ? m.architecture!.output_modalities as unknown[]+ : undefined;+ if (outputs) return outputs.includes('image');+ if (typeof m.type === 'string') return /image-generation|images?\/generations|text-to-image|image_generation/i.test(m.type);+ return IMAGE_MODEL_NAME.test(id) && !NOT_IMAGE_OUTPUT.test(id);+}++/** The image models one provider offers; undefined when it couldn't be asked. */+export async function listImageModels(src: MediaSource, fetchImpl: typeof fetch = globalThis.fetch): Promise<MediaModel[] | undefined> {+ if (src.name === ELEVENLABS_SOURCE) return [];+ if (src.name === GEMINI_SOURCE) return (await listGeminiModels(src, fetchImpl))?.filter((m) => m.kind === 'image');+ const ep = await src.endpoint().catch(() => undefined);+ if (!ep) return undefined;+ if (isOpenRouterUrl(src.baseUrl)) {+ const list = await getJson('https://openrouter.ai/api/v1/models?output_modalities=image', ep.headers, fetchImpl) as { data?: ListedModel[] } | undefined;+ if (!list?.data) return undefined;+ return list.data.filter((m) => typeof m.id === 'string' && isImageModelEntry(m)).map((m) => model(src.name, m.id!, 'openrouter-chat'));+ }+ if (src.name === 'litellm') {+ const root = ep.baseUrl.replace(/\/v1$/i, '');+ const info = await getJson(`${root}/model/info`, ep.headers, fetchImpl) as { data?: Array<{ model_name?: string; model_info?: { mode?: string } }> } | undefined;+ if (info?.data) {+ return [...new Set(info.data.filter((m) => m.model_info?.mode === 'image_generation' && m.model_name).map((m) => m.model_name!))]+ .map((id) => model(src.name, id, 'openai-images'));+ }+ }+ if (src.name === 'ollamaLocal' || src.name === 'ollamaCloud') {+ const root = ep.baseUrl.replace(/\/v1$/i, '');+ const tags = await getJson(`${root}/api/tags`, ep.headers, fetchImpl) as { models?: Array<{ name?: string }> } | undefined;+ if (!tags?.models) return undefined;+ return tags.models.map((m) => m.name ?? '').filter((n) => n && IMAGE_MODEL_NAME.test(n) && !NOT_IMAGE_OUTPUT.test(n)).map((n) => model(src.name, n, 'openai-images'));+ }+ const list = await getJson(`${ep.baseUrl}/models`, ep.headers, fetchImpl) as { data?: ListedModel[] } | undefined;+ if (!list?.data) return undefined;+ return withoutSnapshots(list.data.filter(isImageModelEntry).map((m) => model(src.name, m.id!, 'openai-images')));+}++/** Speech (text-to-speech) models by name, for servers whose model list says nothing more. */+export const SPEECH_MODEL_NAME = /(^|[/:._-])(tts|[\w.-]*-tts([\w.-]*)?|speech-\d|kokoro|orpheus|sesame|chatterbox|xtts|eleven[\w-]*|aura-[\w-]+)($|[/:._-])/i;+const NOT_SPEECH = /(transcri|whisper|stt|asr|realtime|audio-preview)/i;++/** Is a /models entry a text-to-speech model (served at /audio/speech)? */+export function isSpeechModelEntry(m: ListedModel): boolean {+ const id = typeof m.id === 'string' ? m.id : '';+ if (!id || NOT_SPEECH.test(id)) return false;+ const outputs = Array.isArray(m.output_modalities) ? m.output_modalities : undefined;+ if (outputs?.includes('speech')) return true;+ if (typeof m.type === 'string' && /text-to-speech|audio\/speech|audio_speech/i.test(m.type)) return true;+ return SPEECH_MODEL_NAME.test(id);+}++function speechModel(provider: string, id: string): MediaModel {+ return { ref: refOf(provider, id), provider, model: id, kind: 'speech', backend: 'openai-speech', label: humanizeModelName(id), group: modelGroupLabel(provider, id), canEdit: false };+}++/** The speech models one provider offers through /audio/speech; undefined when it couldn't be asked. */+export async function listSpeechModels(src: MediaSource, fetchImpl: typeof fetch = globalThis.fetch): Promise<MediaModel[] | undefined> {+ // Gemini and ElevenLabs speak as direct services (speech.ts), not as listed models.+ if (isOpenRouterUrl(src.baseUrl) || src.name === 'ollamaLocal' || src.name === 'ollamaCloud' || src.name === GEMINI_SOURCE || src.name === ELEVENLABS_SOURCE) return [];+ const ep = await src.endpoint().catch(() => undefined);+ if (!ep) return undefined;+ if (src.name === 'litellm') {+ const root = ep.baseUrl.replace(/\/v1$/i, '');+ const info = await getJson(`${root}/model/info`, ep.headers, fetchImpl) as { data?: Array<{ model_name?: string; model_info?: { mode?: string } }> } | undefined;+ if (info?.data) {+ return [...new Set(info.data.filter((m) => m.model_info?.mode === 'audio_speech' && m.model_name).map((m) => m.model_name!))].map((id) => speechModel(src.name, id));+ }+ }+ const list = await getJson(`${ep.baseUrl}/models`, ep.headers, fetchImpl) as { data?: ListedModel[] } | undefined;+ if (!list?.data) return undefined;+ return withoutSnapshots(list.data.filter(isSpeechModelEntry).map((m) => speechModel(src.name, m.id!)));+}++/* ── Gemini (a key saved for voice), video and music ── */++function mediaModel(provider: string, id: string, kind: MediaKind, backend: ImageBackend, label?: string, canEdit = false): MediaModel {+ return { ref: refOf(provider, id), provider, model: id, kind, backend, label: label ?? humanizeModelName(id), group: provider === GEMINI_SOURCE ? 'Gemini' : provider === ELEVENLABS_SOURCE ? 'ElevenLabs' : modelGroupLabel(provider, id), canEdit };+}++/**+ * What a Gemini key offers: image models (generateContent with image+ * output), Omni video and Lyria music (Interactions API). Lyria RealTime+ * (a live stream, bidiGenerateMusic) is not a file and is left out.+ */+export async function listGeminiModels(src: MediaSource, fetchImpl: typeof fetch = globalThis.fetch): Promise<MediaModel[] | undefined> {+ const ep = await src.endpoint().catch(() => undefined);+ if (!ep) return undefined;+ const list = await getJson(`${ep.baseUrl}/models?pageSize=1000`, ep.headers, fetchImpl) as { models?: Array<{ name?: string; displayName?: string; supportedGenerationMethods?: string[] }> } | undefined;+ if (!list?.models) return undefined;+ const out: MediaModel[] = [];+ for (const m of list.models) {+ const id = (m.name ?? '').replace(/^models\//, '');+ const methods = m.supportedGenerationMethods ?? [];+ if (!id || !methods.includes('generateContent')) continue;+ if (/-image(\b|-|$)/.test(id)) out.push(mediaModel(GEMINI_SOURCE, id, 'image', 'gemini-image', m.displayName, true));+ else if (/omni/.test(id)) out.push(mediaModel(GEMINI_SOURCE, id, 'video', 'gemini-omni', m.displayName, true));+ else if (/lyria/.test(id)) out.push(mediaModel(GEMINI_SOURCE, id, 'music', 'gemini-lyria', m.displayName));+ }+ return out;+}++/** ElevenLabs Music: the models its API takes (it has no listing for them). */+export const ELEVENLABS_MUSIC_MODELS: Array<{ id: string; label: string }> = [+ { id: 'music_v2_5', label: 'Eleven Music v2.5' },+ { id: 'music_v2', label: 'Eleven Music v2' },+ { id: 'music_v1', label: 'Eleven Music v1' },+];++/** Video models by name, for servers whose model list says nothing more. */+export const VIDEO_MODEL_NAME = /(^|[/:._-])(sora|veo|kling|hailuo|seedance|runway|gen-?4|luma|ray-?\d|ltx-?video|ltxv|hunyuan-?video|pika|mochi|vidu|wan[\w.-]*-(t2v|i2v)|minimax-video|cogvideo|grok-imagine-video)/i;++/** Video models one provider offers through the OpenAI Videos API (/videos). */+export async function listVideoModels(src: MediaSource, fetchImpl: typeof fetch = globalThis.fetch): Promise<MediaModel[] | undefined> {+ if (src.name === GEMINI_SOURCE) return (await listGeminiModels(src, fetchImpl))?.filter((m) => m.kind === 'video');+ if (src.name === ELEVENLABS_SOURCE || isOpenRouterUrl(src.baseUrl) || src.name === 'ollamaLocal' || src.name === 'ollamaCloud') return [];+ const ep = await src.endpoint().catch(() => undefined);+ if (!ep) return undefined;+ if (src.name === 'litellm') {+ const root = ep.baseUrl.replace(/\/v1$/i, '');+ const info = await getJson(`${root}/model/info`, ep.headers, fetchImpl) as { data?: Array<{ model_name?: string; model_info?: { mode?: string } }> } | undefined;+ if (info?.data) {+ return [...new Set(info.data.filter((m) => m.model_info?.mode === 'video_generation' && m.model_name).map((m) => m.model_name!))].map((id) => mediaModel(src.name, id, 'video', 'openai-videos', undefined, true));+ }+ }+ const list = await getJson(`${ep.baseUrl}/models`, ep.headers, fetchImpl) as { data?: ListedModel[] } | undefined;+ if (!list?.data) return undefined;+ return withoutSnapshots(list.data.filter((m) => {+ const id = typeof m.id === 'string' ? m.id : '';+ if (!id) return false;+ const outputs = Array.isArray(m.output_modalities) ? m.output_modalities : undefined;+ if (outputs) return outputs.includes('video');+ if (typeof m.type === 'string') return /video-generation|videos\/generations|text-to-video/i.test(m.type);+ return VIDEO_MODEL_NAME.test(id);+ }).map((m) => mediaModel(src.name, m.id!, 'video', 'openai-videos', undefined, true)));+}++/** Music: Gemini Lyria and ElevenLabs Music (no OpenAI-style music API exists). */+export async function listMusicModels(src: MediaSource, fetchImpl: typeof fetch = globalThis.fetch): Promise<MediaModel[] | undefined> {+ if (src.name === GEMINI_SOURCE) return (await listGeminiModels(src, fetchImpl))?.filter((m) => m.kind === 'music');+ if (src.name === ELEVENLABS_SOURCE) return ELEVENLABS_MUSIC_MODELS.map((m) => mediaModel(ELEVENLABS_SOURCE, m.id, 'music', 'elevenlabs-music', m.label));+ return [];+}++/** Drop dated snapshots ("gpt-image-2-2026-04-21", "tts-1-1106") when the plain name is offered too. */+export function withoutSnapshots(models: MediaModel[]): MediaModel[] {+ const ids = new Set(models.map((m) => `${m.provider}::${m.model}`));+ return models.filter((m) => {+ const base = m.model.replace(/-(\d{4}-\d{2}-\d{2}|\d{4})$/, '');+ return base === m.model || !ids.has(`${m.provider}::${base}`);+ });+}++/* ── cache ── */++interface CacheEntry { at: number; models: MediaModel[] }+let cache: Record<string, CacheEntry> | null = null;++function cachePath(): string {+ return join(getMercuryHome(), 'media-models.json');+}++function loadCache(): Record<string, CacheEntry> {+ if (cache) return cache;+ cache = {};+ try {+ const raw = existsSync(cachePath()) ? JSON.parse(readFileSync(cachePath(), 'utf-8')) : {};+ if (raw && typeof raw === 'object') {+ for (const [k, v] of Object.entries(raw as Record<string, CacheEntry>)) {+ if (v && typeof v.at === 'number' && Array.isArray(v.models)) cache[k] = { at: v.at, models: v.models.filter((m) => m && typeof m.ref === 'string' && ['image', 'speech', 'video', 'music'].includes(m.kind)) };+ }+ }+ } catch { /* start empty */ }+ return cache;+}++function saveCache(): void {+ try {+ const tmp = `${cachePath()}.tmp`;+ writeFileSync(tmp, JSON.stringify(loadCache(), null, 2), 'utf-8');+ renameSync(tmp, cachePath());+ } catch { /* best effort */ }+}++/** Test hook. */+export function resetMediaCatalogCache(): void {+ cache = null;+}++/**+ * Models of a kind across the configured providers, in their order.+ * Providers are asked again after a day (or with `refresh`); one that can't+ * be reached keeps its last answer.+ */+async function discover(kind: MediaKind, sources: MediaSource[], lister: (src: MediaSource, f?: typeof fetch) => Promise<MediaModel[] | undefined>, opts: { refresh?: boolean; fetchImpl?: typeof fetch; now?: number }): Promise<MediaModel[]> {+ const now = opts.now ?? Date.now();+ const all = loadCache();+ const keyOf = (src: Pick<MediaSource, 'name' | 'baseUrl'>) => `${kind === 'image' ? '' : `${kind}|`}${src.name}|${src.baseUrl}`;+ await Promise.all(sources.map(async (src) => {+ const known = all[keyOf(src)];+ if (known && !opts.refresh && now - known.at < TTL_MS) return;+ const found = await lister(src, opts.fetchImpl).catch((err) => {+ logger.debug({ provider: src.name, kind, err: err instanceof Error ? err.message : String(err) }, 'Media model discovery failed');+ return undefined;+ });+ if (found) all[keyOf(src)] = { at: now, models: found };+ }));+ saveCache();+ return sources.flatMap((src) => all[keyOf(src)]?.models ?? []);+}++/** Image models across the configured providers. */+export function imageModels(sources: MediaSource[], opts: { refresh?: boolean; fetchImpl?: typeof fetch; now?: number } = {}): Promise<MediaModel[]> {+ return discover('image', sources, listImageModels, opts);+}++/** Text-to-speech models across the configured providers. */+export function speechModels(sources: MediaSource[], opts: { refresh?: boolean; fetchImpl?: typeof fetch; now?: number } = {}): Promise<MediaModel[]> {+ return discover('speech', sources, listSpeechModels, opts);+}++/** Video models across the configured providers (and a Gemini key). */+export function videoModels(sources: MediaSource[], opts: { refresh?: boolean; fetchImpl?: typeof fetch; now?: number } = {}): Promise<MediaModel[]> {+ return discover('video', sources, listVideoModels, opts);+}++/** Music models: Gemini Lyria, ElevenLabs Music. */+export function musicModels(sources: MediaSource[], opts: { refresh?: boolean; fetchImpl?: typeof fetch; now?: number } = {}): Promise<MediaModel[]> {+ return discover('music', sources, listMusicModels, opts);+}++/** What is known without asking anyone (for synchronous callers). */+export function knownImageModels(sources: Array<Pick<MediaSource, 'name' | 'baseUrl'>>): MediaModel[] {+ const all = loadCache();+ return sources.flatMap((src) => all[`${src.name}|${src.baseUrl}`]?.models ?? []);+}diff --git a/src/media/image.ts b/src/media/image.tsnew file mode 100644index 00000000..e393cd02--- /dev/null+++ b/src/media/image.ts@@ -0,0 +1,235 @@+/**+ * Calling an image model. Two wire formats cover the providers Mercury has:+ *+ * - OpenAI Images API: POST /images/generations (JSON) and /images/edits+ * (multipart, reference images). OpenAI itself, LiteLLM, AI/ML API,+ * Runcrate, Atlas Cloud, Mercury Cloud, Ollama and most self-hosted+ * servers expose it. Results come back as b64_json or a URL.+ * - OpenRouter: chat completions with modalities ["image","text"]; images+ * come back in choices[0].message.images[].image_url.url as data URLs.+ * Reference images go in the user message.+ *+ * Options are simple (aspect, quality, count) and mapped to what each+ * format takes; a value a server doesn't take is left out, not guessed.+ */+import { readFileSync } from 'node:fs';+import { basename } from 'node:path';+import type { MediaEndpoint } from '../providers/base.js';+import type { MediaModel } from './catalog.js';+import { mimeOf } from '../artifacts/classify.js';++export type Aspect = 'square' | 'landscape' | 'portrait';+export type Quality = 'auto' | 'low' | 'medium' | 'high';++export interface ImageRequest {+ prompt: string;+ aspect?: Aspect;+ quality?: Quality;+ count?: number;+ /** Local files to edit or take as references. */+ references?: string[];+ signal?: AbortSignal;+}++export interface GeneratedImage {+ bytes: Buffer;+ mime: string;+}++export interface ImageResult {+ images: GeneratedImage[];+ /** The prompt as the model rewrote it, when it says. */+ revisedPrompt?: string;+ /** Text the model wrote alongside (OpenRouter chat). */+ note?: string;+}++const TIMEOUT_MS = 180_000;++export class ImageGenerationError extends Error {+ constructor(message: string, readonly status?: number) {+ super(message);+ this.name = 'ImageGenerationError';+ }+}++function sizeFor(model: string, aspect: Aspect): string {+ if (/dall-e-3/i.test(model)) return aspect === 'landscape' ? '1792x1024' : aspect === 'portrait' ? '1024x1792' : '1024x1024';+ if (/dall-e-2/i.test(model)) return '1024x1024';+ return aspect === 'landscape' ? '1536x1024' : aspect === 'portrait' ? '1024x1536' : '1024x1024';+}++const RATIO: Record<Aspect, string> = { square: '1:1', landscape: '16:9', portrait: '9:16' };++function withTimeout(signal: AbortSignal | undefined): { signal: AbortSignal; done: () => void } {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(new Error('Image generation timed out')), TIMEOUT_MS);+ const onAbort = () => ctrl.abort(signal?.reason);+ signal?.addEventListener('abort', onAbort, { once: true });+ return { signal: ctrl.signal, done: () => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); } };+}++async function errorOf(res: Response): Promise<ImageGenerationError> {+ const text = await res.text().catch(() => '');+ let message = text.slice(0, 400);+ try {+ const j = JSON.parse(text) as { error?: { message?: string } | string; message?: string; detail?: string };+ message = (typeof j.error === 'string' ? j.error : j.error?.message) ?? j.message ?? j.detail ?? message;+ } catch { /* not JSON */ }+ return new ImageGenerationError(`${res.status}: ${message || res.statusText}`, res.status);+}++function decodeDataUrl(url: string): GeneratedImage | undefined {+ const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(url);+ if (!m) return undefined;+ return { mime: m[1] || 'image/png', bytes: m[2] ? Buffer.from(m[3], 'base64') : Buffer.from(decodeURIComponent(m[3])) };+}++async function download(url: string, fetchImpl: typeof fetch, signal: AbortSignal): Promise<GeneratedImage> {+ const data = decodeDataUrl(url);+ if (data) return data;+ const res = await fetchImpl(url, { signal });+ if (!res.ok) throw new ImageGenerationError(`Downloading the image failed (${res.status})`, res.status);+ return { mime: res.headers.get('content-type')?.split(';')[0] || 'image/png', bytes: Buffer.from(await res.arrayBuffer()) };+}++function sniffMime(bytes: Buffer, fallback = 'image/png'): string {+ if (bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';+ if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg';+ if (bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP') return 'image/webp';+ if (bytes.subarray(0, 3).toString('ascii') === 'GIF') return 'image/gif';+ return fallback;+}++async function openAIImages(m: MediaModel, ep: MediaEndpoint, req: ImageRequest, fetchImpl: typeof fetch): Promise<ImageResult> {+ const aspect = req.aspect ?? 'square';+ const n = Math.min(Math.max(req.count ?? 1, 1), 4);+ const quality = req.quality && req.quality !== 'auto' && /gpt-image|chatgpt-image/i.test(m.model) ? req.quality : undefined;+ const t = withTimeout(req.signal);+ try {+ let res: Response;+ if (req.references?.length) {+ const form = new FormData();+ form.set('model', m.model);+ form.set('prompt', req.prompt);+ form.set('n', String(n));+ form.set('size', sizeFor(m.model, aspect));+ if (quality) form.set('quality', quality);+ for (const file of req.references.slice(0, 5)) {+ const blob = new Blob([new Uint8Array(readFileSync(file))], { type: mimeOf(file) || 'image/png' });+ form.append(/gpt-image|chatgpt-image/i.test(m.model) ? 'image[]' : 'image', blob, basename(file));+ }+ res = await fetchImpl(`${ep.baseUrl}/images/edits`, { method: 'POST', headers: ep.headers, body: form, signal: t.signal });+ } else {+ res = await fetchImpl(`${ep.baseUrl}/images/generations`, {+ method: 'POST',+ headers: { ...ep.headers, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: m.model,+ prompt: req.prompt,+ n,+ size: sizeFor(m.model, aspect),+ ...(quality ? { quality } : {}),+ // dall-e answers with a URL unless asked; gpt-image always sends base64 and rejects the field.+ ...(/dall-e/i.test(m.model) ? { response_format: 'b64_json' } : {}),+ }),+ signal: t.signal,+ });+ }+ if (!res.ok) throw await errorOf(res);+ const body = await res.json() as { data?: Array<{ b64_json?: string; url?: string; revised_prompt?: string }> };+ const images: GeneratedImage[] = [];+ for (const d of body.data ?? []) {+ if (d.b64_json) {+ const bytes = Buffer.from(d.b64_json, 'base64');+ images.push({ bytes, mime: sniffMime(bytes) });+ } else if (d.url) {+ images.push(await download(d.url, fetchImpl, t.signal));+ }+ }+ if (!images.length) throw new ImageGenerationError('The model returned no image');+ const revised = body.data?.find((d) => d.revised_prompt)?.revised_prompt;+ return { images, ...(revised ? { revisedPrompt: revised } : {}) };+ } finally {+ t.done();+ }+}++async function openRouterChat(m: MediaModel, ep: MediaEndpoint, req: ImageRequest, fetchImpl: typeof fetch): Promise<ImageResult> {+ const t = withTimeout(req.signal);+ try {+ const content: Array<Record<string, unknown>> = [{ type: 'text', text: req.prompt }];+ for (const file of req.references?.slice(0, 5) ?? []) {+ content.push({ type: 'image_url', image_url: { url: `data:${mimeOf(file) || 'image/png'};base64,${readFileSync(file).toString('base64')}` } });+ }+ const res = await fetchImpl(`${ep.baseUrl}/chat/completions`, {+ method: 'POST',+ headers: { ...ep.headers, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: m.model,+ messages: [{ role: 'user', content }],+ modalities: ['image', 'text'],+ ...(req.aspect ? { image_config: { aspect_ratio: RATIO[req.aspect] } } : {}),+ }),+ signal: t.signal,+ });+ if (!res.ok) throw await errorOf(res);+ const body = await res.json() as { choices?: Array<{ message?: { content?: string; images?: Array<{ image_url?: { url?: string } }> } }> };+ const message = body.choices?.[0]?.message;+ const images: GeneratedImage[] = [];+ for (const img of message?.images ?? []) {+ if (img.image_url?.url) images.push(await download(img.image_url.url, fetchImpl, t.signal));+ }+ if (!images.length) throw new ImageGenerationError(message?.content ? `The model answered in words instead: ${message.content.slice(0, 200)}` : 'The model returned no image');+ return { images, ...(message?.content ? { note: message.content } : {}) };+ } finally {+ t.done();+ }+}++/** Gemini image models (Nano Banana): generateContent with image output; references go in as inline images. */+async function geminiImage(m: MediaModel, ep: MediaEndpoint, req: ImageRequest, fetchImpl: typeof fetch): Promise<ImageResult> {+ const t = withTimeout(req.signal);+ try {+ const parts: Array<Record<string, unknown>> = [{ text: req.prompt }];+ for (const file of req.references?.slice(0, 5) ?? []) {+ parts.push({ inlineData: { mimeType: mimeOf(file) || 'image/png', data: readFileSync(file).toString('base64') } });+ }+ const count = Math.min(Math.max(req.count ?? 1, 1), 4);+ const images: GeneratedImage[] = [];+ let note = '';+ // One image per call: Gemini returns a single picture per candidate.+ for (let i = 0; i < count; i++) {+ const res = await fetchImpl(`${ep.baseUrl}/models/${encodeURIComponent(m.model)}:generateContent`, {+ method: 'POST',+ headers: { ...ep.headers, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ contents: [{ role: 'user', parts }],+ generationConfig: {+ responseModalities: ['TEXT', 'IMAGE'],+ ...(req.aspect ? { imageConfig: { aspectRatio: RATIO[req.aspect] } } : {}),+ },+ }),+ signal: t.signal,+ });+ if (!res.ok) throw await errorOf(res);+ const body = await res.json() as { candidates?: Array<{ content?: { parts?: Array<{ text?: string; inlineData?: { mimeType?: string; data?: string } }> }; finishReason?: string }> };+ for (const p of body.candidates?.[0]?.content?.parts ?? []) {+ if (p.inlineData?.data) images.push({ bytes: Buffer.from(p.inlineData.data, 'base64'), mime: p.inlineData.mimeType || 'image/png' });+ else if (p.text) note += p.text;+ }+ if (!images.length) {+ const reason = body.candidates?.[0]?.finishReason;+ throw new ImageGenerationError(note ? `The model answered in words instead: ${note.slice(0, 200)}` : `The model returned no image${reason ? ` (${reason})` : ''}`);+ }+ }+ return { images, ...(note ? { note } : {}) };+ } finally {+ t.done();+ }+}++export async function generateWith(m: MediaModel, ep: MediaEndpoint, req: ImageRequest, fetchImpl: typeof fetch = globalThis.fetch): Promise<ImageResult> {+ if (m.backend === 'gemini-image') return geminiImage(m, ep, req, fetchImpl);+ return m.backend === 'openrouter-chat' ? openRouterChat(m, ep, req, fetchImpl) : openAIImages(m, ep, req, fetchImpl);+}diff --git a/src/media/intent.ts b/src/media/intent.tsnew file mode 100644index 00000000..fe659329--- /dev/null+++ b/src/media/intent.ts@@ -0,0 +1,172 @@+/**+ * The owner asked for an image outright: `/image [--landscape|--portrait]+ * [--model <ref>] <prompt>`, or the desktop's Image switch (message+ * metadata `media: {kind: "image", aspect?}`). The chat model still runs the+ * turn (it can ask a question, or describe what it made) but is told to call+ * generate_image first, so the request never turns into an SVG.+ */+import type { ChannelMessage } from '../types/channel.js';++export interface MediaIntent {+ kind: 'image';+ prompt: string;+ aspect?: 'square' | 'landscape' | 'portrait';+ model?: string;+}++/** "/image --portrait --model openai::gpt-image-1 a fox" → the request; null when it isn't one. */+export function parseImageCommand(text: string): MediaIntent | null {+ const m = /^\/(?:image|imagine|img)(?:\s+([\s\S]*))?$/i.exec(text.trim());+ if (!m) return null;+ let rest = (m[1] ?? '').trim();+ let aspect: MediaIntent['aspect'];+ let model: string | undefined;+ for (;;) {+ const flag = /^--?(landscape|portrait|square|wide|tall|model(?:=|\s+)(\S+))\s*/i.exec(rest);+ if (!flag) break;+ const word = flag[1].toLowerCase();+ if (flag[2]) model = flag[2];+ else aspect = word === 'wide' ? 'landscape' : word === 'tall' ? 'portrait' : word as MediaIntent['aspect'];+ rest = rest.slice(flag[0].length);+ }+ return rest ? { kind: 'image', prompt: rest, ...(aspect ? { aspect } : {}), ...(model ? { model } : {}) } : null;+}++function jobFromMetadata(msg: ChannelMessage, text: string): JobIntent | null {+ const media = msg.metadata?.media as { kind?: unknown; aspect?: unknown } | undefined;+ if (!media || (media.kind !== 'video' && media.kind !== 'music') || !text) return null;+ const aspect = media.aspect === 'portrait' || media.aspect === 'landscape' ? media.aspect : undefined;+ return { kind: media.kind, prompt: text, ...(aspect ? { aspect } : {}) };+}++function fromMetadata(msg: ChannelMessage, text: string): MediaIntent | null {+ const media = msg.metadata?.media as { kind?: unknown; aspect?: unknown; model?: unknown } | undefined;+ if (!media || media.kind !== 'image' || !text) return null;+ const aspect = media.aspect === 'landscape' || media.aspect === 'portrait' || media.aspect === 'square' ? media.aspect : undefined;+ return { kind: 'image', prompt: text, ...(aspect ? { aspect } : {}), ...(typeof media.model === 'string' && media.model ? { model: media.model } : {}) };+}++export function imageRoutingNote(intent: MediaIntent, attachedImages: string[] = []): string {+ const args = [+ intent.aspect ? `aspect "${intent.aspect}"` : '',+ intent.model ? `model "${intent.model}"` : '',+ ].filter(Boolean).join(', ');+ const attached = attachedImages.length+ ? ` They attached ${attachedImages.map((p) => JSON.stringify(p)).join(', ')}: pass it in reference_images when they want it changed or used as a reference.`+ : '';+ return `[Routing] The user asked for an image. Call generate_image now${args ? ` with ${args}` : ''}, turning their request into a detailed prompt (if they refer to an earlier image, pass it in reference_images).${attached} Then reply in a sentence or two. Do not draw it as SVG or code.`;+}++/** Image files sent with this message (already on disk). */+function attachedImagePaths(msg: ChannelMessage): string[] {+ const list = msg.metadata?.attachments;+ if (!Array.isArray(list)) return [];+ return list+ .filter((a): a is { kind: string; path: string } => !!a && typeof a === 'object' && (a as { kind?: unknown }).kind === 'image' && typeof (a as { path?: unknown }).path === 'string')+ .map((a) => a.path)+ .slice(0, 5);+}++/** Put the prompt in place of "/image …" in the user's message, keeping attached files. */+function withPrompt(content: unknown, prompt: string): unknown {+ if (!Array.isArray(content)) return prompt;+ let replaced = false;+ const parts = content.map((part) => {+ if (!replaced && part && typeof part === 'object' && (part as { type?: unknown }).type === 'text') {+ replaced = true;+ return { ...(part as object), text: prompt };+ }+ return part;+ });+ return replaced ? parts : [{ type: 'text', text: prompt }, ...parts];+}++export interface JobIntent {+ kind: 'video' | 'music';+ prompt: string;+ aspect?: 'landscape' | 'portrait';+ seconds?: number;+ instrumental?: boolean;+ model?: string;+}++/** "/video --portrait --seconds 6 a cat surfing", "/music --instrumental lo-fi beat" → the request. */+export function parseJobCommand(text: string): JobIntent | null {+ const m = /^\/(video|music|song)(?:\s+([\s\S]*))?$/i.exec(text.trim());+ if (!m) return null;+ const kind = m[1].toLowerCase() === 'video' ? 'video' : 'music';+ let rest = (m[2] ?? '').trim();+ const out: Omit<JobIntent, 'prompt'> = { kind };+ for (;;) {+ const flag = /^--?(portrait|landscape|tall|wide|instrumental|seconds(?:=|\s+)(\d+)|model(?:=|\s+)(\S+))\s*/i.exec(rest);+ if (!flag) break;+ const word = flag[1].toLowerCase();+ if (flag[2]) out.seconds = Number(flag[2]);+ else if (flag[3]) out.model = flag[3];+ else if (word === 'instrumental') out.instrumental = true;+ else out.aspect = word === 'portrait' || word === 'tall' ? 'portrait' : 'landscape';+ rest = rest.slice(flag[0].length);+ }+ return rest ? { ...out, prompt: rest } : null;+}++function jobRoutingNote(intent: JobIntent, attachedImages: string[] = []): string {+ const tool = intent.kind === 'video' ? 'generate_video' : 'generate_music';+ const args = [+ intent.aspect ? `aspect "${intent.aspect}"` : '',+ intent.seconds ? `seconds ${intent.seconds}` : '',+ intent.instrumental ? 'instrumental true' : '',+ intent.model ? `model "${intent.model}"` : '',+ ].filter(Boolean).join(', ');+ const attached = intent.kind === 'video' && attachedImages.length+ ? ` They attached ${attachedImages.map((p) => JSON.stringify(p)).join(', ')}: pass it in reference_images to animate it or keep it consistent.`+ : '';+ return `[Routing] The user asked for ${intent.kind === 'video' ? 'a video' : 'music'}. Call ${tool} now${args ? ` with ${args}` : ''}, turning their request into a detailed prompt.${attached} It runs in the background: tell them in one sentence that it is being made and will arrive here.`;+}++/** "/say [--style calm] Good morning!" → the words and how to say them; null when it isn't one. */+export function parseSayCommand(text: string): { text: string; style?: string } | null {+ const m = /^\/(?:say|tts)(?:\s+([\s\S]*))?$/i.exec(text.trim());+ if (!m) return null;+ let rest = (m[1] ?? '').trim();+ let style: string | undefined;+ const flag = /^--style(?:=|\s+)("([^"]+)"|(\S+))\s*/i.exec(rest);+ if (flag) {+ style = flag[2] ?? flag[3];+ rest = rest.slice(flag[0].length);+ }+ return rest ? { text: rest, ...(style ? { style } : {}) } : null;+}++/** Rewrite the turn's messages for an explicit image or speech request; does nothing otherwise. */+export function applyMediaIntent(msg: ChannelMessage, trimmed: string, messages: Array<{ role: string; content: unknown }>): MediaIntent | JobIntent | { kind: 'speech'; text: string } | null {+ if (msg.channelType === 'internal') return null;+ const jobCommand = parseJobCommand(trimmed);+ const job = jobCommand ?? jobFromMetadata(msg, trimmed);+ if (job) {+ if (jobCommand && messages.length) {+ const last = messages[messages.length - 1];+ messages[messages.length - 1] = { ...last, role: 'user', content: withPrompt(last.content, jobCommand.prompt) };+ }+ messages.push({ role: 'user', content: jobRoutingNote(job, attachedImagePaths(msg)) });+ return job;+ }+ const say = parseSayCommand(trimmed);+ if (say) {+ if (messages.length) {+ const last = messages[messages.length - 1];+ messages[messages.length - 1] = { ...last, role: 'user', content: withPrompt(last.content, `Say this out loud: ${say.text}`) };+ }+ messages.push({ role: 'user', content: `[Routing] Call generate_speech now with exactly this text${say.style ? ` and style ${JSON.stringify(say.style)}` : ''}: ${JSON.stringify(say.text)}. Then reply in one short sentence.` });+ return { kind: 'speech', text: say.text };+ }+ const command = parseImageCommand(trimmed);+ const intent = command ?? fromMetadata(msg, trimmed);+ if (!intent) return null;+ if (command && messages.length) {+ const last = messages[messages.length - 1];+ messages[messages.length - 1] = { ...last, role: 'user', content: withPrompt(last.content, command.prompt) };+ }+ messages.push({ role: 'user', content: imageRoutingNote(intent, attachedImagePaths(msg)) });+ return intent;+}diff --git a/src/media/jobs.ts b/src/media/jobs.tsnew file mode 100644index 00000000..0b84f65a--- /dev/null+++ b/src/media/jobs.ts@@ -0,0 +1,163 @@+/**+ * Background media jobs (ADR-042 phase 3): a video or song can take+ * minutes, so the tool starts a job and the turn ends. When the job is+ * done, its file goes to the chat that asked (Telegram, WhatsApp, the+ * desktop, the terminal), even if that chat has moved on, exactly once.+ *+ * Jobs are kept in ~/.mercury/media-jobs.json. A job still "running" when+ * Mercury starts was cut off by a restart (the provider call is gone): it is+ * marked failed and the chat is told, so nothing waits forever.+ */+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { getMercuryHome } from '../utils/config.js';+import { logger } from '../utils/logger.js';++export type JobKind = 'video' | 'music';++export interface ChatTarget {+ channelType: string;+ channelId: string;+ /** The canonical session (desktop thread), for keeping the result with the conversation. */+ sessionId?: string;+}++export interface MediaJob {+ id: string;+ kind: JobKind;+ prompt: string;+ /** The shape asked for (video: landscape/portrait), for placeholders. */+ aspect?: string;+ status: 'running' | 'done' | 'failed';+ chat: ChatTarget;+ createdAt: number;+ finishedAt?: number;+ file?: string;+ /** "Gemini Omni Flash · Gemini" */+ madeWith?: string;+ error?: string;+ delivered: boolean;+}++export interface JobOutcome {+ file: string;+ madeWith: string;+ note?: string;+}++const MAX_KEPT = 200;++export class MediaJobs {+ private jobs: MediaJob[] | null = null;+ private running = new Map<string, AbortController>();++ constructor(+ /** Post a finished (or failed) job to its chat. Must not throw for "chat gone". */+ private readonly deliver: (job: MediaJob, note?: string) => Promise<void>,+ private readonly file = join(getMercuryHome(), 'media-jobs.json'),+ /** A job started (a screen shows a placeholder for it). */+ private readonly announce?: (job: MediaJob) => void,+ ) {}++ private load(): MediaJob[] {+ if (this.jobs) return this.jobs;+ try {+ const raw = existsSync(this.file) ? JSON.parse(readFileSync(this.file, 'utf-8')) : [];+ this.jobs = Array.isArray(raw) ? raw.filter((j) => j && typeof j.id === 'string' && j.chat) : [];+ } catch {+ this.jobs = [];+ }+ return this.jobs;+ }++ private save(): void {+ try {+ const all = this.load();+ if (all.length > MAX_KEPT) all.splice(0, all.length - MAX_KEPT);+ const tmp = `${this.file}.tmp`;+ writeFileSync(tmp, JSON.stringify(all, null, 2), 'utf-8');+ renameSync(tmp, this.file);+ } catch (err) {+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Media jobs: saving failed');+ }+ }++ /**+ * Start a job; resolves at once with it. `run` does the work and may take+ * minutes; its result (or error) is delivered to `chat` when it ends.+ */+ start(kind: JobKind, prompt: string, chat: ChatTarget, run: (signal: AbortSignal) => Promise<JobOutcome>, opts: { aspect?: string } = {}): MediaJob {+ const job: MediaJob = { id: randomUUID().slice(0, 8), kind, prompt: prompt.slice(0, 500), ...(opts.aspect ? { aspect: opts.aspect } : {}), status: 'running', chat, createdAt: Date.now(), delivered: false };+ this.load().push(job);+ this.save();+ try { this.announce?.(job); } catch { /* telling a screen must never stop the job */ }+ const ctrl = new AbortController();+ this.running.set(job.id, ctrl);+ void (async () => {+ let note: string | undefined;+ try {+ const out = await run(ctrl.signal);+ Object.assign(job, { status: 'done', file: out.file, madeWith: out.madeWith, finishedAt: Date.now() });+ note = out.note;+ } catch (err) {+ Object.assign(job, { status: 'failed', error: ctrl.signal.aborted ? 'Stopped.' : err instanceof Error ? err.message : String(err), finishedAt: Date.now() });+ } finally {+ this.running.delete(job.id);+ }+ this.save();+ await this.deliverOnce(job, note);+ })();+ return job;+ }++ private async deliverOnce(job: MediaJob, note?: string): Promise<void> {+ if (job.delivered) return;+ job.delivered = true;+ this.save();+ try {+ await this.deliver(job, note);+ } catch (err) {+ logger.warn({ job: job.id, err: err instanceof Error ? err.message : String(err) }, 'Media job: delivering the result failed');+ }+ }++ /** Mercury restarted: jobs that were running are gone; tell their chats. */+ async recover(): Promise<number> {+ const cut = this.load().filter((j) => j.status === 'running' && !this.running.has(j.id));+ for (const job of cut) {+ Object.assign(job, { status: 'failed', error: 'Mercury restarted while it was being made. Ask again to make it.', finishedAt: Date.now() });+ }+ if (cut.length) this.save();+ for (const job of cut) await this.deliverOnce(job);+ // A job that finished but whose delivery never ran (a crash in between).+ for (const job of this.load().filter((j) => j.status !== 'running' && !j.delivered)) await this.deliverOnce(job);+ return cut.length;+ }++ /** Stop running jobs for a chat (or all). */+ stop(chat?: Pick<ChatTarget, 'channelId'>): number {+ let n = 0;+ for (const job of this.load()) {+ if (job.status !== 'running' || (chat && job.chat.channelId !== chat.channelId)) continue;+ this.running.get(job.id)?.abort();+ n++;+ }+ return n;+ }++ /** Newest first; a chat's own, or every chat's. */+ list(chat?: Pick<ChatTarget, 'channelId'>, limit = 10): MediaJob[] {+ return [...this.load()].reverse().filter((j) => !chat || j.chat.channelId === chat.channelId).slice(0, limit);+ }++ /** Test hook: wait for running jobs to settle. */+ async idle(): Promise<void> {+ while (this.running.size) await new Promise((r) => setTimeout(r, 5));+ await new Promise((r) => setTimeout(r, 5));+ }+}++let jobs: MediaJobs | null = null;+export function setMediaJobs(j: MediaJobs | null): void { jobs = j; }+export function mediaJobs(): MediaJobs | null { return jobs; }diff --git a/src/media/key-sources.ts b/src/media/key-sources.tsnew file mode 100644index 00000000..2b2e4083--- /dev/null+++ b/src/media/key-sources.ts@@ -0,0 +1,29 @@+/**+ * Media sources that aren't chat providers: API keys the owner saved for+ * voice (Settings → Voice). Gemini makes images, Omni video and Lyria+ * music; ElevenLabs makes music. Read on each use, so adding a key applies+ * at once.+ */+import { secretValue } from '../plugins/store.js';+import { ELEVENLABS_SOURCE, GEMINI_SOURCE, type MediaSource } from './catalog.js';++export function mediaKeySources(secret: (name: string) => string | undefined = secretValue): MediaSource[] {+ const out: MediaSource[] = [];+ const gemini = secret('GEMINI_API_KEY');+ if (gemini) {+ out.push({+ name: GEMINI_SOURCE,+ baseUrl: 'https://generativelanguage.googleapis.com/v1beta',+ endpoint: async () => ({ baseUrl: 'https://generativelanguage.googleapis.com/v1beta', headers: { 'x-goog-api-key': gemini } }),+ });+ }+ const eleven = secret('ELEVENLABS_API_KEY');+ if (eleven) {+ out.push({+ name: ELEVENLABS_SOURCE,+ baseUrl: 'https://api.elevenlabs.io/v1',+ endpoint: async () => ({ baseUrl: 'https://api.elevenlabs.io/v1', headers: { 'xi-api-key': eleven } }),+ });+ }+ return out;+}diff --git a/src/media/media.test.ts b/src/media/media.test.tsnew file mode 100644index 00000000..2191de40--- /dev/null+++ b/src/media/media.test.ts@@ -0,0 +1,264 @@+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { imageModels, isImageModelEntry, listImageModels, resetMediaCatalogCache, withoutSnapshots, type MediaSource } from './catalog.js';+import { generateWith } from './image.js';+import { autoOrder, MediaService, resetUnusable, slug } from './service.js';+import { loadMediaPrefs, resetMediaPrefsCache, setMediaDefault } from './prefs.js';+import { applyMediaIntent, parseImageCommand } from './intent.js';+import { mediaCommand } from '../core/commands/chat-command.js';+import { ArtifactCollector } from '../artifacts/collector.js';++/**+ * Image generation (ADR-042): image models are found on the owner's+ * providers, called through the OpenAI Images API or OpenRouter's chat,+ * the owner's default and fallbacks are honoured, and an explicit request+ * is routed to generate_image instead of becoming an SVG.+ */+let home: string;+const previousHome = process.env.MERCURY_HOME;+beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-media-'));+ process.env.MERCURY_HOME = home;+ resetMediaCatalogCache();+ resetMediaPrefsCache();+});+afterEach(() => {+ resetMediaCatalogCache();+ resetMediaPrefsCache();+ if (previousHome === undefined) delete process.env.MERCURY_HOME;+ else process.env.MERCURY_HOME = previousHome;+ rmSync(home, { recursive: true, force: true });+});++const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);+const src = (name: string, baseUrl: string): MediaSource => ({ name, baseUrl, endpoint: async () => ({ baseUrl: baseUrl.replace(/\/$/, ''), headers: { Authorization: 'Bearer k' } }) });++describe('finding image models', () => {+ it('reads output modalities, types and names; skips vision and video models', () => {+ expect(isImageModelEntry({ id: 'x/any', output_modalities: ['image'] })).toBe(true);+ expect(isImageModelEntry({ id: 'x/chat', output_modalities: ['text'] })).toBe(false);+ expect(isImageModelEntry({ id: 'flux-pro', type: 'openai/image-generations' })).toBe(true);+ expect(isImageModelEntry({ id: 'gpt-image-1' })).toBe(true);+ expect(isImageModelEntry({ id: 'dall-e-3' })).toBe(true);+ expect(isImageModelEntry({ id: 'black-forest-labs/flux-1.1-pro' })).toBe(true);+ expect(isImageModelEntry({ id: 'gpt-4o' })).toBe(false);+ expect(isImageModelEntry({ id: 'qwen2.5-vl-72b' })).toBe(false);+ expect(isImageModelEntry({ id: 'gpt-image-1-video' })).toBe(false);+ });++ it('OpenRouter: image-output models, generated through chat', async () => {+ const seen: string[] = [];+ const fake = (async (url: string) => {+ seen.push(url);+ return json({ data: [+ { id: 'google/gemini-2.5-flash-image', architecture: { output_modalities: ['image', 'text'] } },+ { id: 'openai/gpt-4o', architecture: { output_modalities: ['text'] } },+ ] });+ }) as unknown as typeof fetch;+ const models = await listImageModels(src('openaiCompat', 'https://openrouter.ai/api/v1'), fake);+ expect(seen[0]).toBe('https://openrouter.ai/api/v1/models?output_modalities=image');+ expect(models?.map((m) => [m.ref, m.backend, m.canEdit])).toEqual([['openaiCompat::google/gemini-2.5-flash-image', 'openrouter-chat', true]]);+ });++ it('LiteLLM: mode image_generation', async () => {+ const fake = (async () => json({ data: [+ { model_name: 'dalle', model_info: { mode: 'image_generation' } },+ { model_name: 'claude', model_info: { mode: 'chat' } },+ ] })) as unknown as typeof fetch;+ const models = await listImageModels(src('litellm', 'http://proxy:4000/v1'), fake);+ expect(models?.map((m) => m.model)).toEqual(['dalle']);+ });++ it('any other server: its /models list; a failure keeps what was known', async () => {+ let up = true;+ const fake = (async () => (up ? json({ data: [{ id: 'gpt-image-1' }, { id: 'gpt-4.1' }] }) : json({}, 500))) as unknown as typeof fetch;+ const sources = [src('openai', 'https://api.openai.com/v1')];+ expect((await imageModels(sources, { fetchImpl: fake })).map((m) => m.ref)).toEqual(['openai::gpt-image-1']);+ up = false;+ expect((await imageModels(sources, { fetchImpl: fake, refresh: true })).map((m) => m.ref)).toEqual(['openai::gpt-image-1']);+ });+});++describe('calling an image model', () => {+ const model = (id: string, backend: 'openai-images' | 'openrouter-chat' = 'openai-images') => ({ ref: `p::${id}`, provider: 'p', model: id, kind: 'image' as const, backend, label: id, group: 'P', canEdit: true });+ const ep = { baseUrl: 'http://srv/v1', headers: { Authorization: 'Bearer k' } };++ it('OpenAI Images: size from the aspect, base64 decoded, no response_format for gpt-image', async () => {+ let body: Record<string, unknown> = {};+ let url = '';+ const fake = (async (u: string, init?: RequestInit) => { url = u; body = JSON.parse(String(init?.body)); return json({ data: [{ b64_json: PNG.toString('base64'), revised_prompt: 'a fox, watercolor' }] }); }) as unknown as typeof fetch;+ const r = await generateWith(model('gpt-image-1'), ep, { prompt: 'fox', aspect: 'landscape', quality: 'high' }, fake);+ expect(url).toBe('http://srv/v1/images/generations');+ expect(body).toEqual({ model: 'gpt-image-1', prompt: 'fox', n: 1, size: '1536x1024', quality: 'high' });+ expect(r.images[0]).toEqual({ bytes: PNG, mime: 'image/png' });+ expect(r.revisedPrompt).toBe('a fox, watercolor');+ });++ it('a server that answers with a URL: the image is downloaded', async () => {+ const fake = (async (u: string) => (u.endsWith('/generations') ? json({ data: [{ url: 'http://cdn/x.png' }] }) : new Response(PNG, { headers: { 'content-type': 'image/png' } }))) as unknown as typeof fetch;+ const r = await generateWith(model('flux-schnell'), ep, { prompt: 'fox' }, fake);+ expect(r.images[0].bytes.equals(PNG)).toBe(true);+ });++ it('edits go to /images/edits as multipart with the reference image', async () => {+ const ref = join(home, 'in.png');+ writeFileSync(ref, PNG);+ let url = '';+ let form: FormData | undefined;+ const fake = (async (u: string, init?: RequestInit) => { url = u; form = init?.body as FormData; return json({ data: [{ b64_json: PNG.toString('base64') }] }); }) as unknown as typeof fetch;+ await generateWith(model('gpt-image-1'), ep, { prompt: 'make it blue', references: [ref] }, fake);+ expect(url).toBe('http://srv/v1/images/edits');+ expect(form?.get('prompt')).toBe('make it blue');+ expect(form?.getAll('image[]')).toHaveLength(1);+ });++ it('OpenRouter chat: modalities and aspect ratio sent, data-URL images read back', async () => {+ let body: Record<string, unknown> = {};+ const fake = (async (_u: string, init?: RequestInit) => {+ body = JSON.parse(String(init?.body));+ return json({ choices: [{ message: { content: 'Here it is', images: [{ image_url: { url: `data:image/png;base64,${PNG.toString('base64')}` } }] } }] });+ }) as unknown as typeof fetch;+ const r = await generateWith(model('google/gemini-2.5-flash-image', 'openrouter-chat'), ep, { prompt: 'fox', aspect: 'portrait' }, fake);+ expect(body.modalities).toEqual(['image', 'text']);+ expect(body.image_config).toEqual({ aspect_ratio: '9:16' });+ expect(r.images[0].bytes.equals(PNG)).toBe(true);+ expect(r.note).toBe('Here it is');+ });++ it('a server error is reported with its message', async () => {+ const fake = (async () => json({ error: { message: 'Your request was rejected by the safety system' } }, 400)) as unknown as typeof fetch;+ await expect(generateWith(model('gpt-image-1'), ep, { prompt: 'x' }, fake)).rejects.toThrow('400: Your request was rejected by the safety system');+ });+});++describe('which model makes the image', () => {+ function service(listing: Record<string, string[]>, current = 'openai', generate?: (url: string, model: string) => Response) {+ const sources = Object.keys(listing).map((name) => src(name, `http://${name}/v1`));+ const fake = (async (url: string, init?: RequestInit) => {+ if (url.endsWith('/models')) return json({ data: listing[new URL(url).hostname].map((id) => ({ id })) });+ const model = JSON.parse(String(init?.body)).model as string;+ return generate?.(url, model) ?? json({ data: [{ b64_json: PNG.toString('base64') }] });+ }) as unknown as typeof fetch;+ return new MediaService({ sources: () => sources, currentProvider: () => current }, fake);+ }++ it('automatic: the chat provider first, better-known models first', async () => {+ const s = service({ litellm: ['dall-e-3', 'flux-dev'], openai: ['dall-e-3', 'gpt-image-1'] });+ expect((await s.imageChain()).map((m) => m.ref)).toEqual(['openai::gpt-image-1', 'openai::dall-e-3', 'litellm::flux-dev']);+ expect(autoOrder((await s.imageModels()), 'litellm')[0].ref).toBe('litellm::flux-dev');+ });++ it("the owner's default and fallbacks come first", async () => {+ const s = service({ litellm: ['flux-dev'], openai: ['gpt-image-1'] });+ setMediaDefault('image', 'litellm::flux-dev');+ expect((await s.imageChain())[0].ref).toBe('litellm::flux-dev');+ expect(loadMediaPrefs().image?.primary).toBe('litellm::flux-dev');+ setMediaDefault('image', null);+ expect((await s.imageChain())[0].ref).toBe('openai::gpt-image-1');+ });++ it('a failing model hands over to the next, and the file is saved', async () => {+ const s = service({ openai: ['gpt-image-1', 'dall-e-3'] }, 'openai', (_u, model) => (model === 'gpt-image-1' ? json({ error: { message: 'rate limited' } }, 429) : json({ data: [{ b64_json: PNG.toString('base64') }] })));+ const out = join(home, 'out');+ const r = await s.generateImage({ prompt: 'A red fox in the snow' }, out);+ expect(r.model.ref).toBe('openai::dall-e-3');+ expect(r.failed).toEqual([{ ref: 'openai::gpt-image-1', error: '429: rate limited' }]);+ expect(r.files).toEqual([join(out, 'red-fox-in-snow.png')]);+ expect(readFileSync(r.files[0]).equals(PNG)).toBe(true);+ // A second one doesn't overwrite the first.+ const again = await s.generateImage({ prompt: 'A red fox in the snow', model: 'openai::dall-e-3' }, out);+ expect(again.files[0]).toBe(join(out, 'red-fox-in-snow (2).png'));+ });++ it('no image model anywhere: a clear error, not an SVG', async () => {+ const s = service({ openai: ['gpt-4.1'] });+ await expect(s.generateImage({ prompt: 'fox' }, join(home, 'out'))).rejects.toThrow(/No image model is set up/);+ });++ it('/media lists models, sets the default by number, and back to automatic', async () => {+ const s = service({ openai: ['gpt-image-1', 'dall-e-3'] });+ const shown = await mediaCommand(s, '');+ expect(shown.text).toContain('1. GPT Image 1');+ expect(shown.text).toContain('automatic');+ expect((await mediaCommand(s, 'image 2')).text).toContain('Images now use');+ expect(loadMediaPrefs().image?.primary).toBe('openai::dall-e-3');+ await mediaCommand(s, 'image auto');+ expect(loadMediaPrefs().image?.primary).toBeUndefined();+ resetMediaCatalogCache();+ expect((await mediaCommand(service({ other: ['gpt-4.1'] }), '')).text).toContain('no image model found');+ });+});++describe('asking for an image outright', () => {+ it('parses /image with flags', () => {+ expect(parseImageCommand('/image --landscape --model openai::gpt-image-1 a fox')).toEqual({ kind: 'image', prompt: 'a fox', aspect: 'landscape', model: 'openai::gpt-image-1' });+ expect(parseImageCommand('/imagine a fox')).toEqual({ kind: 'image', prompt: 'a fox' });+ expect(parseImageCommand('/image')).toBeNull();+ expect(parseImageCommand('/images of cats')).toBeNull();+ });++ it('routes the turn to generate_image, keeping attached files', () => {+ const messages: Array<{ role: string; content: unknown }> = [{ role: 'user', content: [{ type: 'text', text: '/image make this blue' }, { type: 'image', image: 'x' }] }];+ const msg = { channelType: 'telegram', metadata: { attachments: [{ kind: 'image', path: '/tmp/up/a.png' }] } } as never;+ expect((applyMediaIntent(msg, '/image make this blue', messages) as { prompt?: string } | null)?.prompt).toBe('make this blue');+ expect(messages[0].content).toEqual([{ type: 'text', text: 'make this blue' }, { type: 'image', image: 'x' }]);+ expect(String(messages[1].content)).toContain('Call generate_image now');+ expect(String(messages[1].content)).toContain('"/tmp/up/a.png"');+ });++ it("the desktop's Image switch", () => {+ const messages: Array<{ role: string; content: unknown }> = [{ role: 'user', content: 'a lighthouse at dusk' }];+ const msg = { channelType: 'web', metadata: { media: { kind: 'image', aspect: 'portrait' } } } as never;+ applyMediaIntent(msg, 'a lighthouse at dusk', messages);+ expect(messages[0].content).toBe('a lighthouse at dusk');+ expect(String(messages[1].content)).toContain('aspect "portrait"');+ });++ it('an ordinary message is left alone', () => {+ const messages = [{ role: 'user', content: 'hello' }];+ expect(applyMediaIntent({ channelType: 'web', metadata: {} } as never, 'hello', messages)).toBeNull();+ expect(messages).toHaveLength(1);+ });+});++it('generated images are kept as deliverables', () => {+ const file = join(home, 'fox.png');+ writeFileSync(file, PNG);+ const c = new ArtifactCollector({ startedAt: Date.now() - 1000, cwd: home, surface: 'chat', mercuryHome: home });+ c.observe('generate_image', { prompt: 'fox' }, `Generated 1 image with GPT Image 1 (OpenAI API) in 2.0s:\n- ${file}\nIt is shown in the app.`);+ expect(c.size).toBe(1);+ expect(existsSync(file)).toBe(true);+});++it('file names come from the prompt', () => {+ expect(slug('Generate an image of a red fox, watercolor!')).toBe('red-fox-watercolor');+ expect(slug('!!!')).toBe('image');+});++it('dated snapshots are hidden when the plain name is offered', () => {+ const m = (id: string) => ({ ref: `o::${id}`, provider: 'o', model: id, kind: 'image' as const, backend: 'openai-images' as const, label: id, group: 'O', canEdit: true });+ expect(withoutSnapshots([m('gpt-image-2'), m('gpt-image-2-2026-04-21'), m('gpt-image-9-2026-01-01'), m('tts-1'), m('tts-1-1106')]).map((x) => x.model))+ .toEqual(['gpt-image-2', 'gpt-image-9-2026-01-01', 'tts-1']);+});++it('a model the account has no quota for is skipped by automatic picks for a day', async () => {+ resetUnusable();+ const sources = [src('openai', 'http://quota/v1')];+ const fake = (async (url: string, init?: RequestInit) => {+ if (url.endsWith('/models')) return json({ data: [{ id: 'gpt-image-1' }, { id: 'dall-e-3' }] });+ const m = JSON.parse(String(init?.body)).model;+ return m === 'gpt-image-1' ? json({ error: { message: 'Rate limit exceeded (limit: 0 requests per day on Free Tier)' } }, 429) : json({ data: [{ b64_json: PNG.toString('base64') }] });+ }) as unknown as typeof fetch;+ const s = new MediaService({ sources: () => sources, currentProvider: () => 'openai' }, fake);+ expect((await s.imageChain())[0].ref).toBe('openai::gpt-image-1');+ await s.generateImage({ prompt: 'x' }, join(home, 'q'));+ expect((await s.imageChain()).map((m) => m.ref)).toEqual(['openai::dall-e-3']);+ expect((await s.imageSetup()).auto?.ref).toBe('openai::dall-e-3');+ // Asked for by name: still tried.+ expect((await s.imageChain('openai::gpt-image-1'))[0].ref).toBe('openai::gpt-image-1');+ resetUnusable();+});+diff --git a/src/media/prefs.ts b/src/media/prefs.tsnew file mode 100644index 00000000..bcb49811--- /dev/null+++ b/src/media/prefs.ts@@ -0,0 +1,113 @@+/**+ * The owner's media model choices: one default per kind, plus fallbacks+ * tried in order when it fails. Kept in ~/.mercury/media-prefs.json (not+ * mercury.yaml: the agent rewrites that file on provider switches).+ * No default means "pick automatically" (service.ts).+ */+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';+import { parseRef, type MediaKind } from './catalog.js';++export interface KindPrefs {+ primary?: string;+ fallbacks?: string[];+}++/** Speaking (phase 2): the service or model, the voice, and when chat replies come as voice notes. */+export interface SpeechPrefs {+ /** "openai" | "gemini" | "deepgram" | "elevenlabs", or "provider::model"; absent = the voice in Settings → Voice. */+ choice?: string;+ voice?: string;+ /** off: never; mirror: when they sent a voice note; always: every chat-app reply. */+ replies?: 'off' | 'mirror' | 'always';+}++export type MediaPrefs = Partial<Record<MediaKind, KindPrefs>> & { speech?: SpeechPrefs };++let prefs: MediaPrefs | null = null;++function path(): string {+ return join(getMercuryHome(), 'media-prefs.json');+}++const validRef = (v: unknown): v is string => typeof v === 'string' && v.length <= 512 && parseRef(v) !== null;++export function loadMediaPrefs(): MediaPrefs {+ if (prefs) return prefs;+ prefs = {};+ try {+ const raw = existsSync(path()) ? JSON.parse(readFileSync(path(), 'utf-8')) : {};+ for (const kind of ['image', 'video', 'music'] as const) {+ const k = raw?.[kind];+ if (!k || typeof k !== 'object') continue;+ prefs[kind] = {+ ...(validRef(k.primary) ? { primary: k.primary } : {}),+ ...(Array.isArray(k.fallbacks) ? { fallbacks: k.fallbacks.filter(validRef).slice(0, 5) } : {}),+ };+ }+ const speech = raw?.speech;+ if (speech && typeof speech === 'object') {+ prefs.speech = {+ ...(typeof speech.choice === 'string' && speech.choice.length <= 512 && (SPEECH_ENGINES.includes(speech.choice) || validRef(speech.choice)) ? { choice: speech.choice } : {}),+ ...(typeof speech.voice === 'string' && speech.voice.trim() && speech.voice.length <= 120 ? { voice: speech.voice.trim() } : {}),+ ...(speech.replies === 'off' || speech.replies === 'mirror' || speech.replies === 'always' ? { replies: speech.replies } : {}),+ };+ }+ } catch { /* unreadable: automatic */ }+ return prefs;+}++/** Speech services Mercury calls directly (keys in Settings → Voice / Models). */+export const SPEECH_ENGINES: readonly string[] = ['openai', 'gemini', 'deepgram', 'elevenlabs'];++function save(all: MediaPrefs): void {+ const tmp = `${path()}.tmp`;+ writeFileSync(tmp, JSON.stringify(all, null, 2), 'utf-8');+ renameSync(tmp, path());+}++/**+ * Change speaking prefs. `undefined` leaves a field, `null` clears it.+ * Throws on a value that can't be right.+ */+export function setSpeechPrefs(update: { choice?: string | null; voice?: string | null; replies?: SpeechPrefs['replies'] | null }): SpeechPrefs {+ const all = loadMediaPrefs();+ const next: SpeechPrefs = { ...all.speech };+ if (update.choice !== undefined) {+ if (update.choice === null) delete next.choice;+ else if (SPEECH_ENGINES.includes(update.choice) || validRef(update.choice)) next.choice = update.choice;+ else throw new Error(`Not a speech service or model: ${update.choice}`);+ // A voice belongs to a service: a new service starts from its own default.+ delete next.voice;+ }+ if (update.voice !== undefined) {+ if (update.voice === null || !update.voice.trim()) delete next.voice;+ else if (update.voice.length > 120) throw new Error('Voice name too long');+ else next.voice = update.voice.trim();+ }+ if (update.replies !== undefined) {+ if (update.replies === null) delete next.replies;+ else if (['off', 'mirror', 'always'].includes(update.replies)) next.replies = update.replies;+ else throw new Error(`Voice replies must be off, mirror or always`);+ }+ all.speech = next;+ save(all);+ return next;+}++/** Set (or with null clear) the default model for a kind. A new default leaves the fallbacks. */+export function setMediaDefault(kind: MediaKind, ref: string | null): void {+ const all = loadMediaPrefs();+ const current = all[kind] ?? {};+ if (ref !== null && !validRef(ref)) throw new Error(`Not a model reference: ${ref}`);+ all[kind] = { ...current, ...(ref ? { primary: ref } : {}) };+ if (!ref) delete all[kind]!.primary;+ if (ref && all[kind]!.fallbacks) all[kind]!.fallbacks = all[kind]!.fallbacks!.filter((f) => f !== ref);+ save(all);+}++/** Test hook. */+export function resetMediaPrefsCache(): void {+ prefs = null;+}diff --git a/src/media/runtime.ts b/src/media/runtime.tsnew file mode 100644index 00000000..42370ee1--- /dev/null+++ b/src/media/runtime.ts@@ -0,0 +1,15 @@+/**+ * The process's one MediaService, for the parts that aren't handed it+ * directly (slash commands, the web API). Set once at start-up (index.ts).+ */+import type { MediaService } from './service.js';++let service: MediaService | null = null;++export function setMediaService(s: MediaService | null): void {+ service = s;+}++export function mediaService(): MediaService | null {+ return service;+}diff --git a/src/media/service.ts b/src/media/service.tsnew file mode 100644index 00000000..47a383a6--- /dev/null+++ b/src/media/service.ts@@ -0,0 +1,296 @@+/**+ * Media generation for the agent, its commands and the apps (ADR-042).+ *+ * Which model makes an image, in order:+ * 1. the one asked for (a tool argument, /image --model, a desktop pick)+ * 2. the owner's default for images, then its fallbacks (media-prefs.json)+ * 3. automatic: the best image model found on the configured providers,+ * the current chat provider's first+ * A model that fails hands over to the next (at most three are tried).+ */+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { freeName } from '../artifacts/output-dir.js';+import { logger } from '../utils/logger.js';+import { imageModels, knownImageModels, musicModels, parseRef, videoModels, type MediaKind, type MediaModel, type MediaSource } from './catalog.js';+import { generateMusicWith, generateVideoWith, type MusicRequest, type VideoRequest } from './video.js';+import { generateWith, ImageGenerationError, type ImageRequest } from './image.js';+import { loadMediaPrefs } from './prefs.js';++export interface MediaHost {+ /** The configured providers, in the registry's order. */+ sources(): MediaSource[];+ /** The provider the chat is using now (preferred for automatic picks). */+ currentProvider(): string | undefined;+}++export interface ImageJob extends Omit<ImageRequest, 'signal'> {+ /** "provider::model" to use this one only. */+ model?: string;+ signal?: AbortSignal;+}++export interface ImageJobResult {+ files: string[];+ model: MediaModel;+ /** Models that failed before this one, with why. */+ failed: Array<{ ref: string; error: string }>;+ revisedPrompt?: string;+ note?: string;+ ms: number;+}++/**+ * Models the provider says this account can't use (a free tier with no+ * quota, no billing): skipped by automatic picks for a day instead of+ * failing first on every request. A model asked for by name is still tried.+ */+const NO_QUOTA = /limit:\s*0\b|free tier|upgrade your (tier|plan)|billing (is )?(not|required)|insufficient[_ ]quota|not available (on|for) your (plan|tier)|payment required/i;+const NO_QUOTA_MS = 24 * 60 * 60 * 1000;+const unusable = new Map<string, { until: number; why: string }>();++export function noteMediaFailure(ref: string, error: string, now = Date.now()): void {+ if (NO_QUOTA.test(error)) unusable.set(ref, { until: now + NO_QUOTA_MS, why: 'no quota on this account' });+}++/** Why a model is being skipped right now, if it is. */+export function unusableReason(ref: string, now = Date.now()): string | undefined {+ const u = unusable.get(ref);+ if (!u) return undefined;+ if (u.until < now) { unusable.delete(ref); return undefined; }+ return u.why;+}++/** Test hook. */+export function resetUnusable(): void {+ unusable.clear();+}++/** Better-known models first when picking automatically, per kind. */+const PREFERENCE: Record<string, RegExp[]> = {+ image: [/gpt-image|chatgpt-image/i, /nano-banana|gemini-[\w.-]*-image/i, /flux/i, /seedream/i, /imagen/i, /grok-imagine|grok-2-image/i, /qwen-image|z-image/i, /dall-e-3/i],+ video: [/omni/i, /veo/i, /sora/i, /kling/i, /seedance/i, /hailuo|minimax/i, /runway|gen-?4/i, /luma|ray/i, /wan/i, /ltx/i],+ music: [/lyria-3\.5|lyria-3-pro/i, /music_v2_5/i, /lyria/i, /music_v2/i, /music/i],+ speech: [],+};++function rank(m: MediaModel): number {+ const list = PREFERENCE[m.kind] ?? [];+ const i = list.findIndex((re) => re.test(m.model));+ return i < 0 ? list.length : i;+}++/** The automatic pick order among known models. */+export function autoOrder(models: MediaModel[], currentProvider?: string): MediaModel[] {+ return [...models].sort((a, b) => {+ const pa = a.provider === currentProvider ? 0 : 1;+ const pb = b.provider === currentProvider ? 0 : 1;+ if (pa !== pb) return pa - pb;+ const r = rank(a) - rank(b);+ if (r) return r;+ // Newer versions tend to sort later by name ("gpt-image-1.5" > "gpt-image-1").+ return b.model.localeCompare(a.model, undefined, { numeric: true });+ });+}++export interface ImageSetup {+ /** The owner's default, if set (and whether it is still offered). */+ default?: { ref: string; available: boolean };+ /** What "automatic" would use now. */+ auto?: MediaModel;+ models: MediaModel[];+}++export class MediaService {+ constructor(private readonly host: MediaHost, private readonly fetchImpl: typeof fetch = globalThis.fetch) {}++ /** A configured provider's endpoint and auth (fresh), for other callers that need it. */+ async endpointFor(name: string): Promise<import('../providers/base.js').MediaEndpoint | undefined> {+ return this.host.sources().find((s) => s.name === name)?.endpoint().catch(() => undefined);+ }++ /** The providers, for the speech service (same sources as images). */+ sourcesForSpeech(): () => MediaSource[] {+ return () => this.host.sources();+ }++ async imageModels(opts: { refresh?: boolean } = {}): Promise<MediaModel[]> {+ return imageModels(this.host.sources(), { refresh: opts.refresh, fetchImpl: this.fetchImpl });+ }++ /** Known without network: for tool descriptions and quick checks. */+ knownImageModels(): MediaModel[] {+ return knownImageModels(this.host.sources());+ }++ async models(kind: Exclude<MediaKind, 'speech'>, opts: { refresh?: boolean } = {}): Promise<MediaModel[]> {+ const lister = kind === 'video' ? videoModels : kind === 'music' ? musicModels : imageModels;+ return lister(this.host.sources(), { refresh: opts.refresh, fetchImpl: this.fetchImpl });+ }++ async setup(kind: Exclude<MediaKind, 'speech'>, opts: { refresh?: boolean } = {}): Promise<ImageSetup> {+ const models = await this.models(kind, opts);+ const primary = loadMediaPrefs()[kind]?.primary;+ return {+ ...(primary ? { default: { ref: primary, available: models.some((m) => m.ref === primary) } } : {}),+ auto: autoOrder(models, this.host.currentProvider()).find((m) => !unusableReason(m.ref)),+ models,+ };+ }++ async imageSetup(opts: { refresh?: boolean } = {}): Promise<ImageSetup> {+ const models = await this.imageModels(opts);+ const primary = loadMediaPrefs().image?.primary;+ return {+ ...(primary ? { default: { ref: primary, available: models.some((m) => m.ref === primary) } } : {}),+ auto: autoOrder(models, this.host.currentProvider()).find((m) => !unusableReason(m.ref)),+ models,+ };+ }++ /** The models to try, in order (at most three). */+ async imageChain(requested?: string): Promise<MediaModel[]> {+ return this.chain('image', requested);+ }++ async chain(kind: Exclude<MediaKind, 'speech'>, requested?: string): Promise<MediaModel[]> {+ const models = await this.models(kind);+ const byRef = new Map(models.map((m) => [m.ref, m]));+ const fromRef = (ref: string): MediaModel | undefined => {+ const known = byRef.get(ref);+ if (known) return known;+ // A model the owner named that discovery didn't list: try it through its provider's Images API.+ const p = parseRef(ref);+ if (!p || !this.host.sources().some((s) => s.name === p.provider) || kind === 'music') return undefined;+ return { ref, provider: p.provider, model: p.model, kind, backend: kind === 'video' ? 'openai-videos' : 'openai-images', label: p.model, group: p.provider, canEdit: true };+ };+ if (requested) {+ const exact = fromRef(requested) ?? models.find((m) => m.model === requested || m.label.toLowerCase() === requested.toLowerCase());+ return exact ? [exact] : [];+ }+ const prefs = loadMediaPrefs()[kind];+ const chain: MediaModel[] = [];+ for (const ref of [prefs?.primary, ...(prefs?.fallbacks ?? [])]) {+ const m = ref ? fromRef(ref) : undefined;+ if (m && !chain.some((c) => c.ref === m.ref)) chain.push(m);+ }+ for (const m of autoOrder(models, this.host.currentProvider())) {+ if (chain.length >= 3) break;+ if (!chain.some((c) => c.ref === m.ref) && !unusableReason(m.ref)) chain.push(m);+ }+ return chain.slice(0, 3);+ }++ /** A video: Gemini Omni or an OpenAI Videos API gateway; can take minutes (run it as a job). */+ generateVideo(req: VideoRequest & { model?: string }, outDir: string): Promise<MediaJobResult> {+ return runChain(this, this.host, 'video', req, outDir, (m, ep) => generateVideoWith(m, ep, req, this.fetchImpl));+ }++ /** A song or clip: Gemini Lyria or ElevenLabs Music. */+ generateMusic(req: MusicRequest & { model?: string }, outDir: string): Promise<MediaJobResult> {+ return runChain(this, this.host, 'music', req, outDir, (m, ep) => generateMusicWith(m, ep, req, this.fetchImpl));+ }++ /** Generate, save into `outDir`, and say which model made it. */+ async generateImage(job: ImageJob, outDir: string): Promise<ImageJobResult> {+ const started = Date.now();+ let chain = await this.imageChain(job.model);+ if (job.references?.length) {+ const editors = chain.filter((m) => m.canEdit);+ chain = editors.length ? editors : chain;+ }+ if (!chain.length) {+ throw new ImageGenerationError(job.model+ ? `No image model "${job.model}" on the configured providers.`+ : 'No image model is set up. Add a provider that makes images (OpenAI, OpenRouter, LiteLLM, AI/ML API, Mercury Cloud…) and pick one with /media.');+ }+ const failed: ImageJobResult['failed'] = [];+ for (const m of chain) {+ if (job.signal?.aborted) break;+ const src = this.host.sources().find((s) => s.name === m.provider);+ const ep = await src?.endpoint().catch(() => undefined);+ if (!ep) { failed.push({ ref: m.ref, error: 'provider not reachable' }); continue; }+ try {+ const result = await generateWith(m, ep, job, this.fetchImpl);+ mkdirSync(outDir, { recursive: true });+ const stem = slug(job.prompt);+ const files = result.images.map((img, i) => {+ const ext = img.mime === 'image/jpeg' ? 'jpg' : img.mime === 'image/webp' ? 'webp' : img.mime === 'image/gif' ? 'gif' : 'png';+ const name = freeName(outDir, `${stem}${result.images.length > 1 ? `-${i + 1}` : ''}.${ext}`);+ const file = join(outDir, name);+ writeFileSync(file, img.bytes);+ return file;+ });+ return { files, model: m, failed, ms: Date.now() - started, ...(result.revisedPrompt ? { revisedPrompt: result.revisedPrompt } : {}), ...(result.note ? { note: result.note } : {}) };+ } catch (err) {+ if (job.signal?.aborted) throw err;+ const error = err instanceof Error ? err.message : String(err);+ logger.warn({ model: m.ref, error }, 'Image generation failed; trying the next model');+ noteMediaFailure(m.ref, error);+ failed.push({ ref: m.ref, error });+ }+ }+ throw new ImageGenerationError(`Image generation failed: ${failed.map((f) => `${f.ref} (${f.error})`).join('; ')}`);+ }+}++/** A video or song, saved into `outDir`. */+export interface MediaJobResult {+ file: string;+ model: MediaModel;+ failed: Array<{ ref: string; error: string }>;+ note?: string;+ ms: number;+}++const EXT: Record<string, string> = { 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'audio/mpeg': 'mp3', 'audio/mp3': 'mp3', 'audio/wav': 'wav', 'audio/x-wav': 'wav', 'audio/ogg': 'ogg', 'audio/flac': 'flac' };++/** Try each model in turn; save what the first one that works makes. */+export async function runChain<R extends { signal?: AbortSignal }>(+ service: MediaService,+ host: MediaHost,+ kind: 'video' | 'music',+ req: R & { prompt: string; model?: string; references?: string[] },+ outDir: string,+ call: (m: MediaModel, ep: NonNullable<Awaited<ReturnType<MediaSource['endpoint']>>>) => Promise<{ bytes: Buffer; mime: string; note?: string }>,+): Promise<MediaJobResult> {+ const started = Date.now();+ let chain = await service.chain(kind, req.model);+ if (req.references?.length) {+ const editors = chain.filter((m) => m.canEdit);+ chain = editors.length ? editors : chain;+ }+ if (!chain.length) {+ throw new ImageGenerationError(req.model+ ? `No ${kind} model "${req.model}" on the configured providers.`+ : kind === 'video'+ ? 'No video model is set up. A Gemini key (Settings → Voice) gives Gemini Omni video; gateways such as LiteLLM or Mercury Cloud can serve others. Pick one with /media.'+ : 'No music model is set up. A Gemini key (Lyria) or an ElevenLabs key (Settings → Voice) makes music. Pick one with /media.');+ }+ const failed: MediaJobResult['failed'] = [];+ for (const m of chain) {+ if (req.signal?.aborted) break;+ const ep = await host.sources().find((s) => s.name === m.provider)?.endpoint().catch(() => undefined);+ if (!ep) { failed.push({ ref: m.ref, error: 'provider not reachable' }); continue; }+ try {+ const out = await call(m, ep);+ mkdirSync(outDir, { recursive: true });+ const file = join(outDir, freeName(outDir, `${slug(req.prompt)}.${EXT[out.mime] ?? (kind === 'video' ? 'mp4' : 'mp3')}`));+ writeFileSync(file, out.bytes);+ return { file, model: m, failed, ms: Date.now() - started, ...(out.note ? { note: out.note } : {}) };+ } catch (err) {+ if (req.signal?.aborted) throw err;+ const error = err instanceof Error ? err.message : String(err);+ logger.warn({ model: m.ref, kind, error }, 'Media generation failed; trying the next model');+ noteMediaFailure(m.ref, error);+ failed.push({ ref: m.ref, error });+ }+ }+ throw new ImageGenerationError(`${kind === 'video' ? 'Video' : 'Music'} generation failed: ${failed.map((f) => `${f.ref} (${f.error})`).join('; ')}`);+}++/** "A red fox in snow, watercolor" → "red-fox-in-snow-watercolor". */+export function slug(prompt: string): string {+ const words = prompt.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, ' ').split(/\s+/).filter((w) => w && !/^(a|an|the|of|and|image|picture|photo|generate|create|make|draw)$/.test(w));+ return words.slice(0, 6).join('-').slice(0, 60) || 'image';+}diff --git a/src/media/speech.test.ts b/src/media/speech.test.tsnew file mode 100644index 00000000..7e8936bc--- /dev/null+++ b/src/media/speech.test.ts@@ -0,0 +1,215 @@+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// mercury.yaml's path is fixed when config.ts loads: point Mercury at an empty+// home before anything imports it, so no real key (or request) is ever used.+const fixedHome = await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ for (const k of ['OPENAI_API_KEY', 'GEMINI_API_KEY', 'DEEPGRAM_API_KEY', 'ELEVENLABS_API_KEY']) delete process.env[k];+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-speech-home-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');+ process.env.MERCURY_HOME = dir;+ return dir;+});+import { isSpeechModelEntry, listSpeechModels, resetMediaCatalogCache, type MediaSource } from './catalog.js';+import { loadMediaPrefs, resetMediaPrefsCache, setSpeechPrefs } from './prefs.js';+import { speakableText, SpeechService, toOggOpus, voiceReplyWanted } from './speech.js';+import { synthesizeSpeech } from '../plugins/speak.js';+import { applyMediaIntent, parseSayCommand } from './intent.js';+import { mediaCommand } from '../core/commands/chat-command.js';+import { MediaService } from './service.js';++/**+ * Speaking (ADR-042 phase 2): one choice of speech service and voice, found+ * on the owner's providers or keys, voice notes as Ogg/Opus, and replies+ * as voice notes when asked.+ */+let home: string;+const noNetwork = (async () => { throw new Error('network is off in this test'); }) as unknown as typeof fetch;+beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-speech-'));+ process.env.MERCURY_HOME = fixedHome;+ rmSync(join(fixedHome, 'media-prefs.json'), { force: true });+ rmSync(join(fixedHome, 'media-models.json'), { force: true });+ for (const k of ['OPENAI_API_KEY', 'GEMINI_API_KEY', 'DEEPGRAM_API_KEY', 'ELEVENLABS_API_KEY']) delete process.env[k];+ resetMediaCatalogCache();+ resetMediaPrefsCache();+});+afterEach(() => {+ resetMediaCatalogCache();+ resetMediaPrefsCache();+ delete process.env.DEEPGRAM_API_KEY;+ rmSync(home, { recursive: true, force: true });+});++const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+const MP3 = new Uint8Array([0xff, 0xfb, 0x90, 0x44, 1, 2, 3]);+const src = (name: string, baseUrl: string): MediaSource => ({ name, baseUrl, endpoint: async () => ({ baseUrl, headers: { Authorization: 'Bearer cloud-jwt', 'X-Agent-Id': 'a1' } }) });++describe('finding speech models', () => {+ it('by output, type or name; never transcription or realtime models', () => {+ expect(isSpeechModelEntry({ id: 'tts-1' })).toBe(true);+ expect(isSpeechModelEntry({ id: 'gpt-4o-mini-tts' })).toBe(true);+ expect(isSpeechModelEntry({ id: 'kokoro-82m' })).toBe(true);+ expect(isSpeechModelEntry({ id: 'x', output_modalities: ['speech'] })).toBe(true);+ expect(isSpeechModelEntry({ id: 'y', type: 'text-to-speech' })).toBe(true);+ expect(isSpeechModelEntry({ id: 'gpt-4o-mini-transcribe' })).toBe(false);+ expect(isSpeechModelEntry({ id: 'whisper-1' })).toBe(false);+ expect(isSpeechModelEntry({ id: 'gpt-4o-audio-preview' })).toBe(false);+ expect(isSpeechModelEntry({ id: 'gpt-4.1' })).toBe(false);+ });++ it('LiteLLM mode audio_speech; others from /models', async () => {+ const litellm = (async () => json({ data: [{ model_name: 'voice', model_info: { mode: 'audio_speech' } }, { model_name: 'c', model_info: { mode: 'chat' } }] })) as unknown as typeof fetch;+ expect((await listSpeechModels(src('litellm', 'http://p/v1'), litellm))?.map((m) => m.ref)).toEqual(['litellm::voice']);+ const openai = (async () => json({ data: [{ id: 'tts-1' }, { id: 'gpt-4o-mini-tts' }, { id: 'gpt-4o-mini-tts-2025-03-20' }, { id: 'gpt-5' }] })) as unknown as typeof fetch;+ expect((await listSpeechModels(src('openai', 'http://o/v1'), openai))?.map((m) => m.model)).toEqual(['tts-1', 'gpt-4o-mini-tts']);+ });+});++describe('what speaks', () => {+ function service(fetchImpl: typeof fetch) {+ return new SpeechService(() => [src('mercuryCloud', 'https://backend/v1')], fetchImpl);+ }++ it('nothing set up: a clear error', async () => {+ await expect(service(noNetwork).speak('hi')).rejects.toThrow(/No speech service is set up/);+ });++ it("a provider's speech model: its endpoint, auth, model and the chosen voice; Ogg/Opus for a voice note", async () => {+ let url = '';+ let headers: Record<string, string> = {};+ let body: Record<string, unknown> = {};+ const fake = (async (u: string, init?: RequestInit) => {+ url = u; headers = init?.headers as Record<string, string>; body = JSON.parse(String(init?.body));+ return new Response(MP3);+ }) as unknown as typeof fetch;+ setSpeechPrefs({ choice: 'mercuryCloud::voice-1' });+ setSpeechPrefs({ voice: 'nova' });+ const s = service(fake);+ const out = await s.speak('Hello there', { format: 'ogg', instructions: 'warm' });+ expect(url).toBe('https://backend/v1/audio/speech');+ expect(headers.Authorization).toBe('Bearer cloud-jwt');+ expect(headers['X-Agent-Id']).toBe('a1');+ expect(body).toEqual({ model: 'voice-1', voice: 'nova', input: 'Hello there', response_format: 'opus', instructions: 'warm' });+ expect(out.mime).toBe('audio/ogg');+ expect(out.ext).toBe('ogg');+ });++ it('a direct service key (Deepgram) chosen, and saved to a file', async () => {+ process.env.DEEPGRAM_API_KEY = 'dg-key';+ let url = '';+ const fake = (async (u: string) => { url = u; return new Response(MP3); }) as unknown as typeof fetch;+ setSpeechPrefs({ choice: 'deepgram' });+ const s = service(fake);+ expect((await s.options()).map((o) => o.id)).toContain('deepgram');+ const { file, label } = await s.speakToFile('Good morning, team!', join(home, 'out'), { format: 'ogg', voice: 'aura-2-orion-en' });+ expect(url).toContain('model=aura-2-orion-en');+ expect(url).toContain('encoding=opus&container=ogg');+ expect(label).toBe('Deepgram');+ expect(file).toBe(join(home, 'out', 'good-morning-team.ogg'));+ expect(readFileSync(file)).toEqual(Buffer.from(MP3));+ });++ it('a choice that is no longer there falls back to Settings → Voice', async () => {+ setSpeechPrefs({ choice: 'elevenlabs' });+ expect(await service(noNetwork).target()).toBeNull();+ });++ it('prefs: a new service clears the voice; bad values are refused', () => {+ setSpeechPrefs({ choice: 'gemini' });+ setSpeechPrefs({ voice: 'Kore' });+ setSpeechPrefs({ choice: 'openai' });+ expect(loadMediaPrefs().speech).toEqual({ choice: 'openai' });+ expect(() => setSpeechPrefs({ choice: 'nonsense' })).toThrow();+ expect(() => setSpeechPrefs({ replies: 'sometimes' as never })).toThrow();+ setSpeechPrefs({ replies: 'always' });+ resetMediaPrefsCache();+ expect(loadMediaPrefs().speech?.replies).toBe('always');+ });+});++describe('the speech services themselves', () => {+ it('Gemini takes the style as words in front, and the chosen voice', async () => {+ let body: { contents: Array<{ parts: Array<{ text: string }> }>; generationConfig: { speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: string } } } } } | undefined;+ const fake = (async (_u: string, init?: RequestInit) => {+ body = JSON.parse(String(init?.body));+ return json({ candidates: [{ content: { parts: [{ inlineData: { mimeType: 'audio/wav', data: Buffer.from('RIFFxxxxWAVE').toString('base64') } }] } }] });+ }) as unknown as typeof fetch;+ await synthesizeSpeech('Hello', { kind: 'gemini', label: 'Gemini', apiKey: 'g' }, { fetch: fake, voice: 'Puck', instructions: 'cheerfully.' });+ expect(body?.contents[0].parts[0].text).toBe('Say this cheerfully: Hello');+ expect(body?.generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName).toBe('Puck');+ });++ it('tts-1 never gets a style (it rejects the field)', async () => {+ let body: Record<string, unknown> = {};+ const fake = (async (_u: string, init?: RequestInit) => { body = JSON.parse(String(init?.body)); return new Response(MP3); }) as unknown as typeof fetch;+ await synthesizeSpeech('Hi', { kind: 'openai', label: 'OpenAI', apiKey: 'k', model: 'tts-1' }, { fetch: fake, instructions: 'calm' });+ expect(body).not.toHaveProperty('instructions');+ });+});++describe('voice notes', () => {+ it('replies come as voice notes only in chat apps, by the setting', () => {+ expect(voiceReplyWanted('telegram', true)).toBe(true);+ expect(voiceReplyWanted('telegram', false)).toBe(false);+ expect(voiceReplyWanted('whatsapp', false, 'always')).toBe(true);+ expect(voiceReplyWanted('telegram', true, 'off')).toBe(false);+ expect(voiceReplyWanted('web', true, 'always')).toBe(false);+ expect(voiceReplyWanted('cli', true, 'always')).toBe(false);+ });++ it('what is said: no markdown or code, links by name, long replies cut at a sentence', () => {+ expect(speakableText('**Done.** See [the docs](https://x.y) and run:\n```sh\nnpm test\n```\n- one\n- two')).toBe('Done. See the docs and run:\n (code in the message) \none\ntwo');+ const long = speakableText(`${'This is a sentence. '.repeat(200)}`, 300);+ expect(long.length).toBeLessThan(340);+ expect(long.endsWith('The rest is in the message.')).toBe(true);+ });++ const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();+ it.skipIf(!hasFfmpeg)('mp3 or wav becomes Ogg/Opus with ffmpeg', async () => {+ const dir = join(home, 'ff');+ mkdirSync(dir);+ const wav = join(dir, 'a.wav');+ execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=0.3', wav]);+ const ogg = await toOggOpus(readFileSync(wav), 'wav');+ expect(ogg && Buffer.from(ogg.subarray(0, 4)).toString('ascii')).toBe('OggS');+ });++ it('ffmpeg missing or failing: null, so the audio goes as it was', async () => {+ expect(await toOggOpus(new Uint8Array([1, 2, 3]), 'mp3')).toBeNull();+ });+});++describe('/say and /media for speech', () => {+ it('parses /say with a style', () => {+ expect(parseSayCommand('/say --style "calm and slow" Good night')).toEqual({ text: 'Good night', style: 'calm and slow' });+ expect(parseSayCommand('/tts hello')).toEqual({ text: 'hello' });+ expect(parseSayCommand('/say')).toBeNull();+ expect(parseSayCommand('/sayonara')).toBeNull();+ });++ it('routes /say to generate_speech with the exact words', () => {+ const messages: Array<{ role: string; content: unknown }> = [{ role: 'user', content: '/say Happy birthday, Sam!' }];+ expect(applyMediaIntent({ channelType: 'telegram', metadata: {} } as never, '/say Happy birthday, Sam!', messages)).toEqual({ kind: 'speech', text: 'Happy birthday, Sam!' });+ expect(String(messages[1].content)).toContain('generate_speech');+ expect(String(messages[1].content)).toContain('"Happy birthday, Sam!"');+ });++ it('/media replies, voice and speech choices', async () => {+ process.env.DEEPGRAM_API_KEY = 'dg';+ const speech = new SpeechService(() => [], noNetwork);+ const media = new MediaService({ sources: () => [], currentProvider: () => undefined });+ expect((await mediaCommand(media, 'replies always', speech)).text).toContain('on every reply');+ expect((await mediaCommand(media, 'speech 1', speech)).text).toContain('Deepgram');+ expect(loadMediaPrefs().speech?.choice).toBe('deepgram');+ expect((await mediaCommand(media, 'voice aura-2-orion-en', speech)).text).toContain('aura-2-orion-en');+ expect((await mediaCommand(media, 'replies sometimes', speech)).text).toContain('Usage');+ expect((await mediaCommand(media, 'speech auto', speech)).text).toContain('follows Settings → Voice');+ });+});diff --git a/src/media/speech.ts b/src/media/speech.tsnew file mode 100644index 00000000..c90bbade--- /dev/null+++ b/src/media/speech.ts@@ -0,0 +1,186 @@+/**+ * Speaking (ADR-042 phase 2): one choice of speech service and voice for+ * everything that speaks — the generate_speech tool, /voice, voice-note+ * replies in chat apps, and reading replies aloud in the apps.+ *+ * What speaks, in order:+ * 1. the owner's choice in Settings → AI → Media or /media speech: a+ * service Mercury calls directly (OpenAI, Gemini, Deepgram, ElevenLabs)+ * or a text-to-speech model found on a provider (LiteLLM, Mercury+ * Cloud, any OpenAI-compatible /audio/speech)+ * 2. the voice chosen in Settings → Voice, else the first service with a+ * key (what read-aloud always used)+ */+import { execFile } from 'node:child_process';+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { promisify } from 'node:util';+import { freeName } from '../artifacts/output-dir.js';+import { loadConfig } from '../utils/config.js';+import { secretValue } from '../plugins/store.js';+import { currentSpeechEngine } from '../plugins/speech-choice.js';+import { SPEAK_MAX_CHARS, SPEECH_VOICES, speechMime, synthesizeSpeech, type SpeechFormat } from '../plugins/speak.js';+import type { SpeechEngine } from '../plugins/transcribe.js';+import { parseRef, speechModels, type MediaModel, type MediaSource } from './catalog.js';+import { loadMediaPrefs, type SpeechPrefs } from './prefs.js';+import { slug } from './service.js';++const run = promisify(execFile);++export interface SpeechOption {+ /** "openai" | "gemini" | "deepgram" | "elevenlabs", or "provider::model". */+ id: string;+ label: string;+ group: string;+ /** Voices it knows by name (empty: any id the service takes, e.g. ElevenLabs voice ids). */+ voices: string[];+}++export interface SpeechTarget {+ engine: SpeechEngine;+ id: string;+ label: string;+ voice?: string;+}++const ENGINE_LABEL: Record<string, string> = { openai: 'OpenAI', gemini: 'Gemini', deepgram: 'Deepgram', elevenlabs: 'ElevenLabs' };++/** Services Mercury can call directly with keys the owner already gave. */+function directEngines(): Partial<Record<SpeechEngine['kind'], SpeechEngine>> {+ const out: Partial<Record<SpeechEngine['kind'], SpeechEngine>> = {};+ const openai = loadConfig().providers.openai;+ if (openai?.apiKey && openai.enabled !== false) out.openai = { kind: 'openai', label: 'OpenAI', apiKey: openai.apiKey, baseUrl: openai.baseUrl };+ const gemini = secretValue('GEMINI_API_KEY');+ if (gemini) out.gemini = { kind: 'gemini', label: 'Gemini', apiKey: gemini };+ const deepgram = secretValue('DEEPGRAM_API_KEY');+ if (deepgram) out.deepgram = { kind: 'deepgram', label: 'Deepgram', apiKey: deepgram };+ const eleven = secretValue('ELEVENLABS_API_KEY');+ if (eleven) out.elevenlabs = { kind: 'elevenlabs', label: 'ElevenLabs', apiKey: eleven };+ return out;+}++export class SpeechService {+ constructor(private readonly sources: () => MediaSource[], private readonly fetchImpl: typeof fetch = globalThis.fetch) {}++ prefs(): SpeechPrefs {+ return loadMediaPrefs().speech ?? {};+ }++ /** Every way Mercury can speak right now: direct services, then provider models. */+ async options(opts: { refresh?: boolean } = {}): Promise<SpeechOption[]> {+ const direct = Object.values(directEngines()).map((e) => ({ id: e.kind, label: ENGINE_LABEL[e.kind], group: 'Speech services', voices: SPEECH_VOICES[e.kind] ?? [] }));+ const models = await speechModels(this.sources(), { refresh: opts.refresh, fetchImpl: this.fetchImpl });+ // The OpenAI provider's own models are the "OpenAI" service with a model picked.+ return [+ ...direct,+ ...models.map((m: MediaModel) => ({ id: m.ref, label: m.label, group: m.group, voices: SPEECH_VOICES.openai ?? [] })),+ ];+ }++ /** What speaks now (null: nothing set up). */+ async target(): Promise<SpeechTarget | null> {+ const prefs = this.prefs();+ const voice = prefs.voice;+ if (prefs.choice) {+ const direct = directEngines()[prefs.choice as SpeechEngine['kind']];+ if (direct) return { engine: direct, id: direct.kind, label: ENGINE_LABEL[direct.kind], ...(voice ? { voice } : {}) };+ const ref = parseRef(prefs.choice);+ const src = ref ? this.sources().find((s) => s.name === ref.provider) : undefined;+ const ep = src ? await src.endpoint().catch(() => undefined) : undefined;+ if (ref && ep) {+ return {+ engine: { kind: 'openai', label: `${ref.model}`, apiKey: '', baseUrl: ep.baseUrl, headers: ep.headers, model: ref.model },+ id: prefs.choice,+ label: ref.model,+ ...(voice ? { voice } : {}),+ };+ }+ // The choice is gone (key removed, provider off): fall back below.+ }+ const engine = currentSpeechEngine('speak');+ return engine ? { engine, id: engine.kind, label: engine.label, ...(voice && !prefs.choice ? { voice } : {}) } : null;+ }++ /** Speak text; ogg is a voice note (converted with ffmpeg where the service can't make it). */+ async speak(text: string, opts: { voice?: string; instructions?: string; format?: SpeechFormat; signal?: AbortSignal } = {}): Promise<{ bytes: Uint8Array; mime: string; ext: string; label: string }> {+ const t = await this.target();+ if (!t) throw new Error('No speech service is set up: add an OpenAI key (Settings → Models), or a Gemini, Deepgram or ElevenLabs key (Settings → Voice).');+ const format = opts.format ?? 'mp3';+ const bytes = await synthesizeSpeech(text.slice(0, SPEAK_MAX_CHARS), t.engine, {+ fetch: this.fetchImpl,+ signal: opts.signal,+ voice: opts.voice ?? t.voice,+ instructions: opts.instructions,+ format,+ });+ const mime = speechMime(t.engine, format);+ if (format === 'ogg' && mime !== 'audio/ogg') {+ const converted = await toOggOpus(bytes, mime === 'audio/wav' ? 'wav' : 'mp3');+ if (converted) return { bytes: converted, mime: 'audio/ogg', ext: 'ogg', label: t.label };+ }+ return { bytes, mime, ext: mime === 'audio/ogg' ? 'ogg' : mime === 'audio/wav' ? 'wav' : 'mp3', label: t.label };+ }++ /** Speak into a file in `outDir`; named from the text. */+ async speakToFile(text: string, outDir: string, opts: { voice?: string; instructions?: string; format?: SpeechFormat; signal?: AbortSignal } = {}): Promise<{ file: string; label: string; ms: number }> {+ const started = Date.now();+ const audio = await this.speak(text, opts);+ mkdirSync(outDir, { recursive: true });+ const file = join(outDir, freeName(outDir, `${slug(text).slice(0, 40) || 'speech'}.${audio.ext}`));+ writeFileSync(file, audio.bytes);+ return { file, label: audio.label, ms: Date.now() - started };+ }+}++/** Ogg/Opus from mp3 or wav with ffmpeg; null when ffmpeg isn't there or fails. */+export async function toOggOpus(bytes: Uint8Array, from: 'mp3' | 'wav'): Promise<Uint8Array | null> {+ const dir = join(tmpdir(), `mercury-voice-${process.pid}-${Date.now()}`);+ try {+ mkdirSync(dir, { recursive: true });+ const input = join(dir, `in.${from}`);+ const output = join(dir, 'out.ogg');+ writeFileSync(input, bytes);+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', input, '-c:a', 'libopus', '-b:a', '48k', '-ac', '1', output], { timeout: 60_000 });+ const { readFileSync } = await import('node:fs');+ return new Uint8Array(readFileSync(output));+ } catch {+ return null;+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++/**+ * A reply as it should sound: no markdown, no code, links by name, and+ * short enough for a voice note (the full text was sent as a message).+ */+export function speakableText(markdown: string, max = 1500): string {+ let t = markdown+ .replace(/```[\s\S]*?```/g, ' (code in the message) ')+ .replace(/`([^`]+)`/g, '$1')+ .replace(/!\[[^\]]*\]\([^)]*\)/g, '')+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')+ .replace(/https?:\/\/\S+/g, 'a link')+ .replace(/^#{1,6}\s+/gm, '')+ .replace(/^\s*[-*+]\s+/gm, '')+ .replace(/[*_~>|]+/g, '')+ .replace(/\n{2,}/g, '\n')+ .trim();+ if (t.length > max) {+ const cut = t.slice(0, max);+ const end = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf('\n'));+ t = `${cut.slice(0, end > max * 0.6 ? end + 1 : max).trim()} The rest is in the message.`;+ }+ return t;+}++/** Should this chat-app reply also come as a voice note? */+export function voiceReplyWanted(channelType: string, sentVoiceNote: boolean, replies: SpeechPrefs['replies'] = 'mirror'): boolean {+ if (['web', 'cli', 'internal'].includes(channelType)) return false;+ return replies === 'always' || (replies === 'mirror' && sentVoiceNote);+}++let speechService: SpeechService | null = null;+export function setSpeechService(s: SpeechService | null): void { speechService = s; }+export function getSpeechService(): SpeechService | null { return speechService; }diff --git a/src/media/video.test.ts b/src/media/video.test.tsnew file mode 100644index 00000000..d221479d--- /dev/null+++ b/src/media/video.test.ts@@ -0,0 +1,280 @@+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// The real mercury.yaml must never be read: point Mercury at an empty home first.+const fixedHome = await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-video-home-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');+ process.env.MERCURY_HOME = dir;+ return dir;+});++const { listGeminiModels, listMusicModels, listVideoModels, resetMediaCatalogCache } = await import('./catalog.js');+const { generateMusicWith, generateVideoWith } = await import('./video.js');+const { generateWith } = await import('./image.js');+const { MediaService } = await import('./service.js');+const { MediaJobs } = await import('./jobs.js');+const { parseJobCommand, applyMediaIntent } = await import('./intent.js');+const { mediaCommand } = await import('../core/commands/chat-command.js');+const { loadMediaPrefs, resetMediaPrefsCache } = await import('./prefs.js');+const { mediaKeySources } = await import('./key-sources.js');+const { Agent } = await import('../core/agent.js');+const { WebChannel } = await import('../channels/web.js');++/**+ * Video and music (ADR-042 phase 3): Gemini (Omni video, Lyria music,+ * Nano Banana images) and ElevenLabs Music from saved keys, the OpenAI+ * Videos API on gateways, and background jobs posted to the chat that asked.+ */+let home: string;+beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-video-'));+ for (const f of ['media-models.json', 'media-prefs.json', 'media-jobs.json']) rmSync(join(fixedHome, f), { force: true });+ resetMediaCatalogCache();+ resetMediaPrefsCache();+});+afterEach(() => rmSync(home, { recursive: true, force: true }));++const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+const MP4 = Buffer.from('....ftypmp42 fake video');+const MP3 = Buffer.from([0xff, 0xfb, 0x90, 0x44, 9, 9]);+const gemini = mediaKeySources((k) => (k === 'GEMINI_API_KEY' ? 'g-key' : undefined))[0];+const eleven = mediaKeySources((k) => (k === 'ELEVENLABS_API_KEY' ? 'e-key' : undefined))[0];+const GEMINI_MODELS = { models: [+ { name: 'models/gemini-3.1-flash-image', supportedGenerationMethods: ['generateContent'] },+ { name: 'models/gemini-omni-1.2-flash', displayName: 'Gemini Omni 1.2 Flash', supportedGenerationMethods: ['generateContent'] },+ { name: 'models/lyria-3.5', supportedGenerationMethods: ['generateContent'] },+ { name: 'models/lyria-realtime-exp', supportedGenerationMethods: ['bidiGenerateMusic'] },+ { name: 'models/gemini-3-pro', supportedGenerationMethods: ['generateContent'] },+] };++describe('what keys and gateways offer', () => {+ it('a Gemini key: images, Omni video and Lyria music (not the live stream)', async () => {+ const fake = (async () => json(GEMINI_MODELS)) as unknown as typeof fetch;+ const models = await listGeminiModels(gemini, fake);+ expect(models?.map((m) => [m.model, m.kind, m.backend])).toEqual([+ ['gemini-3.1-flash-image', 'image', 'gemini-image'],+ ['gemini-omni-1.2-flash', 'video', 'gemini-omni'],+ ['lyria-3.5', 'music', 'gemini-lyria'],+ ]);+ expect(models?.[1].label).toBe('Gemini Omni 1.2 Flash');+ expect(models?.[1].group).toBe('Gemini');+ });++ it('ElevenLabs: its music models; gateways: video by mode, output or name', async () => {+ expect((await listMusicModels(eleven))?.map((m) => m.model)).toEqual(['music_v2_5', 'music_v2', 'music_v1']);+ const litellm = (async () => json({ data: [{ model_name: 'veo', model_info: { mode: 'video_generation' } }] })) as unknown as typeof fetch;+ const src = { name: 'litellm', baseUrl: 'http://p/v1', endpoint: async () => ({ baseUrl: 'http://p/v1', headers: {} }) };+ expect((await listVideoModels(src, litellm))?.map((m) => [m.ref, m.backend])).toEqual([['litellm::veo', 'openai-videos']]);+ const other = (async () => json({ data: [{ id: 'kling-v2' }, { id: 'gpt-4.1' }, { id: 'x', output_modalities: ['video'] }] })) as unknown as typeof fetch;+ expect((await listVideoModels({ ...src, name: 'openaiCompat' }, other))?.map((m) => m.model)).toEqual(['kling-v2', 'x']);+ });+});++const model = (id: string, kind: 'image' | 'video' | 'music', backend: string) => ({ ref: `p::${id}`, provider: 'p', model: id, kind, backend: backend as never, label: id, group: 'P', canEdit: true });+const gemEp = { baseUrl: 'https://generativelanguage.googleapis.com/v1beta', headers: { 'x-goog-api-key': 'g' } };++describe('calling them', () => {+ it('Gemini Omni: Interactions with the video format; the inline MP4 is read back', async () => {+ let url = '';+ let body: Record<string, unknown> = {};+ const fake = (async (u: string, init?: RequestInit) => {+ url = u; body = JSON.parse(String(init?.body));+ return json({ status: 'completed', steps: [{ type: 'model_output', content: [{ type: 'text', text: 'A cat surfing.' }, { type: 'video', mime_type: 'video/mp4', data: MP4.toString('base64') }] }] });+ }) as unknown as typeof fetch;+ const out = await generateVideoWith(model('gemini-omni-1.2-flash', 'video', 'gemini-omni'), gemEp, { prompt: 'a cat surfing', aspect: 'portrait', seconds: 30 }, fake);+ expect(url).toBe('https://generativelanguage.googleapis.com/v1beta/interactions');+ expect(body).toEqual({ model: 'gemini-omni-1.2-flash', input: 'a cat surfing', response_format: { type: 'video', aspect_ratio: '9:16', resolution: '720p', duration: '15s' } });+ expect(out.bytes.equals(MP4)).toBe(true);+ expect(out.note).toBe('A cat surfing.');+ });++ it('a reference image goes in with the prompt', async () => {+ const ref = join(home, 'still.png');+ writeFileSync(ref, Buffer.from([0x89, 0x50]));+ let body: { input?: unknown } = {};+ const fake = (async (_u: string, init?: RequestInit) => { body = JSON.parse(String(init?.body)); return json({ steps: [{ type: 'model_output', content: [{ type: 'video', data: MP4.toString('base64') }] }] }); }) as unknown as typeof fetch;+ await generateVideoWith(model('gemini-omni-1.2-flash', 'video', 'gemini-omni'), gemEp, { prompt: 'animate it', references: [ref] }, fake);+ expect(body.input).toEqual([{ type: 'text', text: 'animate it' }, { type: 'image', data: Buffer.from([0x89, 0x50]).toString('base64'), mime_type: 'image/png' }]);+ });++ it('OpenAI Videos API: start, poll until completed, download', async () => {+ vi.useFakeTimers();+ const calls: string[] = [];+ let polls = 0;+ const fake = (async (u: string) => {+ calls.push(u);+ if (u.endsWith('/videos')) return json({ id: 'v1', status: 'queued' });+ if (u.endsWith('/content')) return new Response(MP4, { headers: { 'content-type': 'video/mp4' } });+ polls++;+ return json({ id: 'v1', status: polls < 2 ? 'in_progress' : 'completed' });+ }) as unknown as typeof fetch;+ const run = generateVideoWith(model('veo', 'video', 'openai-videos'), { baseUrl: 'http://gw/v1', headers: {} }, { prompt: 'x' }, fake);+ await vi.advanceTimersByTimeAsync(11_000);+ const out = await run;+ vi.useRealTimers();+ expect(calls).toEqual(['http://gw/v1/videos', 'http://gw/v1/videos/v1', 'http://gw/v1/videos/v1', 'http://gw/v1/videos/v1/content']);+ expect(out.bytes.equals(MP4)).toBe(true);+ });++ it('a failed gateway job says why', async () => {+ const fake = (async (u: string) => (u.endsWith('/videos') ? json({ id: 'v1', status: 'failed', error: { message: 'policy' } }) : json({}))) as unknown as typeof fetch;+ await expect(generateVideoWith(model('veo', 'video', 'openai-videos'), { baseUrl: 'http://gw/v1', headers: {} }, { prompt: 'x' }, fake)).rejects.toThrow('The video job failed: policy');+ });++ it('Lyria: length and "instrumental" in the words, the revision header, MP3 back', async () => {+ let headers: Record<string, string> = {};+ let body: Record<string, unknown> = {};+ const fake = (async (_u: string, init?: RequestInit) => {+ headers = init?.headers as Record<string, string>; body = JSON.parse(String(init?.body));+ return json({ steps: [{ type: 'model_output', content: [{ type: 'audio', data: MP3.toString('base64') }] }] });+ }) as unknown as typeof fetch;+ const out = await generateMusicWith(model('lyria-3.5', 'music', 'gemini-lyria'), gemEp, { prompt: 'lo-fi beat', seconds: 90, instrumental: true }, fake);+ expect(headers['Api-Revision']).toBe('2026-05-20');+ expect(body).toEqual({ model: 'lyria-3.5', input: 'lo-fi beat Instrumental only, no vocals. About 90 seconds long.' });+ expect(out).toMatchObject({ mime: 'audio/mpeg' });+ expect(out.bytes.equals(MP3)).toBe(true);+ });++ it('ElevenLabs Music: length in ms, instrumental, the model', async () => {+ let url = '';+ let body: Record<string, unknown> = {};+ const fake = (async (u: string, init?: RequestInit) => { url = u; body = JSON.parse(String(init?.body)); return new Response(MP3); }) as unknown as typeof fetch;+ await generateMusicWith(model('music_v2_5', 'music', 'elevenlabs-music'), { baseUrl: 'https://api.elevenlabs.io/v1', headers: { 'xi-api-key': 'e' } }, { prompt: 'jingle', seconds: 20, instrumental: true }, fake);+ expect(url).toBe('https://api.elevenlabs.io/v1/music?output_format=mp3_44100_128');+ expect(body).toEqual({ prompt: 'jingle', model_id: 'music_v2_5', music_length_ms: 20000, force_instrumental: true });+ });++ it('Gemini images: generateContent with image output and the aspect ratio', async () => {+ let url = '';+ let body: { generationConfig?: unknown } = {};+ const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47]);+ const fake = (async (u: string, init?: RequestInit) => {+ url = u; body = JSON.parse(String(init?.body));+ return json({ candidates: [{ content: { parts: [{ inlineData: { mimeType: 'image/png', data: PNG.toString('base64') } }] } }] });+ }) as unknown as typeof fetch;+ const out = await generateWith(model('gemini-3.1-flash-image', 'image', 'gemini-image'), gemEp, { prompt: 'fox', aspect: 'landscape' }, fake);+ expect(url).toBe('https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image:generateContent');+ expect(body.generationConfig).toEqual({ responseModalities: ['TEXT', 'IMAGE'], imageConfig: { aspectRatio: '16:9' } });+ expect(out.images[0].bytes.equals(PNG)).toBe(true);+ });+});++describe('background jobs', () => {+ const chat = { channelType: 'telegram', channelId: 'telegram:1' };++ it('runs after the turn and is delivered once, done or failed', async () => {+ const delivered: Array<{ status: string; file?: string; error?: string }> = [];+ const jobs = new MediaJobs(async (j) => { delivered.push({ status: j.status, file: j.file, error: j.error }); }, join(home, 'jobs.json'));+ const ok = jobs.start('video', 'a fox', chat, async () => ({ file: '/out/fox.mp4', madeWith: 'Omni · Gemini' }));+ expect(ok.status).toBe('running');+ jobs.start('music', 'a song', chat, async () => { throw new Error('quota'); });+ await jobs.idle();+ expect(delivered).toEqual([{ status: 'done', file: '/out/fox.mp4', error: undefined }, { status: 'failed', file: undefined, error: 'quota' }]);+ expect(JSON.parse(readFileSync(join(home, 'jobs.json'), 'utf-8')).every((j: { delivered: boolean }) => j.delivered)).toBe(true);+ });++ it('a restart cuts running jobs off: their chats are told, once', async () => {+ writeFileSync(join(home, 'jobs.json'), JSON.stringify([{ id: 'a1', kind: 'video', prompt: 'x', status: 'running', chat, createdAt: 1, delivered: false }]));+ const delivered: string[] = [];+ const jobs = new MediaJobs(async (j) => { delivered.push(`${j.id}:${j.status}`); }, join(home, 'jobs.json'));+ expect(await jobs.recover()).toBe(1);+ expect(await jobs.recover()).toBe(0);+ expect(delivered).toEqual(['a1:failed']);+ });++ it('announces a started job (a placeholder appears) with its shape', async () => {+ const announced: string[] = [];+ const jobs = new MediaJobs(async () => {}, join(home, 'jobs.json'), (j) => announced.push(`${j.kind}:${j.aspect}`));+ jobs.start('video', 'x', chat, async () => ({ file: '/f.mp4', madeWith: 'm' }), { aspect: 'portrait' });+ await jobs.idle();+ expect(announced).toEqual(['video:portrait']);+ });++ it('stop aborts a chat’s running job', async () => {+ const delivered: string[] = [];+ const jobs = new MediaJobs(async (j) => { delivered.push(j.error ?? ''); }, join(home, 'jobs.json'));+ jobs.start('video', 'x', chat, (signal) => new Promise((_r, reject) => signal.addEventListener('abort', () => reject(new Error('aborted')))));+ expect(jobs.stop({ channelId: 'telegram:2' })).toBe(0);+ expect(jobs.stop({ channelId: 'telegram:1' })).toBe(1);+ await jobs.idle();+ expect(delivered).toEqual(['Stopped.']);+ });+});++describe('asking for video and music', () => {+ it('/video and /music with flags', () => {+ expect(parseJobCommand('/video --portrait --seconds 6 a cat surfing')).toEqual({ kind: 'video', prompt: 'a cat surfing', aspect: 'portrait', seconds: 6 });+ expect(parseJobCommand('/music --instrumental lo-fi beat')).toEqual({ kind: 'music', prompt: 'lo-fi beat', instrumental: true });+ expect(parseJobCommand('/song happy birthday for Sam')).toEqual({ kind: 'music', prompt: 'happy birthday for Sam' });+ expect(parseJobCommand('/video')).toBeNull();+ expect(parseJobCommand('/videos of cats')).toBeNull();+ });++ it('routes to the background tool, from a command or the Create menu', () => {+ const m1: Array<{ role: string; content: unknown }> = [{ role: 'user', content: '/music lo-fi beat' }];+ applyMediaIntent({ channelType: 'telegram', metadata: {} } as never, '/music lo-fi beat', m1);+ expect(m1[0].content).toBe('lo-fi beat');+ expect(String(m1[1].content)).toContain('Call generate_music now');+ const m2: Array<{ role: string; content: unknown }> = [{ role: 'user', content: 'a drone shot of a coast' }];+ applyMediaIntent({ channelType: 'web', metadata: { media: { kind: 'video', aspect: 'portrait' } } } as never, 'a drone shot of a coast', m2);+ expect(String(m2[1].content)).toContain('Call generate_video now with aspect "portrait"');+ });++ it('/media lists video and music, and sets their defaults', async () => {+ const fake = (async () => json(GEMINI_MODELS)) as unknown as typeof fetch;+ const media = new MediaService({ sources: () => [gemini, eleven], currentProvider: () => undefined }, fake);+ const shown = (await mediaCommand(media, '')).text;+ expect(shown).toContain('**Video** · Gemini Omni 1.2 Flash · Gemini (automatic)');+ expect(shown).toContain('**Music** · Lyria 3.5');+ expect((await mediaCommand(media, 'music 2')).text).toContain('Eleven Music v2.5');+ expect(loadMediaPrefs().music?.primary).toBe('elevenlabs::music_v2_5');+ });+});++describe('posting a finished job to its chat', () => {+ function fakeAgent(channelType: string) {+ const sent: string[] = [];+ const files: string[] = [];+ const appended: Array<{ content: string; metadata?: Record<string, unknown> }> = [];+ const ready: Array<{ text: string; artifacts: unknown[] }> = [];+ const channel = channelType === 'web'+ ? Object.assign(Object.create(WebChannel.prototype), { sendMediaReady: (text: string, artifacts: unknown[]) => ready.push({ text, artifacts }) })+ : { send: async (t: string) => { sent.push(t); }, sendFile: async (f: string) => { files.push(f); } };+ const self = { channels: { get: () => channel }, sessions: { appendMessage: (_id: string, m: { content: string; metadata?: Record<string, unknown> }) => { appended.push(m); } } };+ return { self, sent, files, appended, ready };+ }++ it('chat apps: a note, then the file', async () => {+ const file = join(home, 'fox.mp4');+ writeFileSync(file, MP4);+ const a = fakeAgent('telegram');+ await Agent.prototype.deliverMediaJob.call(a.self as never, { id: 'j', kind: 'video', prompt: 'fox', status: 'done', file, madeWith: 'Omni · Gemini', chat: { channelType: 'telegram', channelId: 'telegram:1' }, createdAt: 1, delivered: true });+ expect(a.sent).toEqual(['🎬 Your video is ready (Omni · Gemini).']);+ expect(a.files).toEqual([file]);+ });++ it('the apps: kept with the conversation as an artifact, and announced on its own', async () => {+ const file = join(home, 'song.mp3');+ writeFileSync(file, MP3);+ const a = fakeAgent('web');+ await Agent.prototype.deliverMediaJob.call(a.self as never, { id: 'k', kind: 'music', prompt: 'song', status: 'done', file, madeWith: 'Lyria 3.5 · Gemini', chat: { channelType: 'web', channelId: 'thread-1', sessionId: 'thread-1' }, createdAt: 1, delivered: true });+ expect(a.appended[0].content).toBe('🎵 Your music is ready (Lyria 3.5 · Gemini).');+ const refs = a.appended[0].metadata?.artifacts as Array<{ kind: string; name: string }>;+ expect(refs[0]).toMatchObject({ kind: 'audio', name: 'song.mp3' });+ expect(a.ready[0].artifacts).toEqual(refs);+ expect(existsSync(join(fixedHome, 'artifacts', 'index.json'))).toBe(true);+ });++ it('a failure is said plainly', async () => {+ const a = fakeAgent('telegram');+ await Agent.prototype.deliverMediaJob.call(a.self as never, { id: 'f', kind: 'video', prompt: 'x', status: 'failed', error: 'quota exceeded', chat: { channelType: 'telegram', channelId: 'telegram:1' }, createdAt: 1, delivered: true });+ expect(a.sent).toEqual(["⚠ I couldn't make the video: quota exceeded"]);+ expect(a.files).toEqual([]);+ });+});diff --git a/src/media/video.ts b/src/media/video.tsnew file mode 100644index 00000000..bb011736--- /dev/null+++ b/src/media/video.ts@@ -0,0 +1,215 @@+/**+ * Calling a video or music model (ADR-042 phase 3). These take from+ * seconds to minutes, so they run as background jobs (jobs.ts); the calls+ * here just wait for the result.+ *+ * Video+ * - Gemini Omni (gemini-omni-*): POST /v1beta/interactions with+ * response_format {type: "video", aspect_ratio, resolution, duration};+ * the MP4 comes back inline in steps[type=model_output].content[type=video].+ * - OpenAI Videos API shape (/videos, poll /videos/{id}, /videos/{id}/content):+ * what gateways such as LiteLLM serve (Sora itself was retired in 2026).+ * Music+ * - Gemini Lyria (lyria-*): the same Interactions call; MP3 inline.+ * - ElevenLabs Music: POST /v1/music → the audio file.+ */+import { readFileSync } from 'node:fs';+import type { MediaEndpoint } from '../providers/base.js';+import type { MediaModel } from './catalog.js';+import { mimeOf } from '../artifacts/classify.js';+import { ImageGenerationError } from './image.js';++export interface VideoRequest {+ prompt: string;+ aspect?: 'landscape' | 'portrait';+ /** 3–15 seconds (Gemini Omni); gateways round to what their model takes. */+ seconds?: number;+ resolution?: '360p' | '720p' | '1080p';+ /** A still to animate or keep characters consistent with. */+ references?: string[];+ signal?: AbortSignal;+}++export interface MusicRequest {+ prompt: string;+ seconds?: number;+ instrumental?: boolean;+ signal?: AbortSignal;+}++export interface MediaFile {+ bytes: Buffer;+ mime: string;+ note?: string;+}++const VIDEO_TIMEOUT_MS = 15 * 60_000;+const MUSIC_TIMEOUT_MS = 10 * 60_000;+const POLL_MS = 5000;++function withTimeout(signal: AbortSignal | undefined, ms: number): { signal: AbortSignal; done: () => void } {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(new Error('timed out')), ms);+ const onAbort = () => ctrl.abort(signal?.reason);+ signal?.addEventListener('abort', onAbort, { once: true });+ return { signal: ctrl.signal, done: () => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); } };+}++async function failure(res: Response): Promise<ImageGenerationError> {+ const text = await res.text().catch(() => '');+ let message = text.slice(0, 400);+ try {+ const j = JSON.parse(text) as { error?: { message?: string } | string; detail?: unknown; message?: string };+ const detail = Array.isArray(j.detail) ? (j.detail[0] as { msg?: string })?.msg : typeof j.detail === 'string' ? j.detail : (j.detail as { message?: string } | undefined)?.message;+ message = (typeof j.error === 'string' ? j.error : j.error?.message) ?? detail ?? j.message ?? message;+ } catch { /* not JSON */ }+ return new ImageGenerationError(`${res.status}: ${message || res.statusText}`, res.status);+}++const clamp = (n: number, lo: number, hi: number) => Math.min(Math.max(Math.round(n), lo), hi);++interface InteractionContent { type?: string; data?: string; uri?: string; mime_type?: string; text?: string }++/** The first output of a kind in an Interactions response, and any text with it. */+async function interactionOutput(body: unknown, kind: 'video' | 'audio', ep: MediaEndpoint, fetchImpl: typeof fetch, signal: AbortSignal): Promise<MediaFile> {+ const steps = (body as { steps?: Array<{ type?: string; content?: InteractionContent[] }> }).steps ?? [];+ let note = '';+ for (const step of steps) {+ if (step.type !== 'model_output') continue;+ for (const c of step.content ?? []) {+ if (c.type === 'text' && c.text) note += c.text;+ if (c.type !== kind) continue;+ const mime = c.mime_type || (kind === 'video' ? 'video/mp4' : 'audio/mpeg');+ if (c.data) return { bytes: Buffer.from(c.data, 'base64'), mime, ...(note ? { note } : {}) };+ if (c.uri) {+ const res = await fetchImpl(c.uri, { headers: ep.headers, signal });+ if (!res.ok) throw await failure(res);+ return { bytes: Buffer.from(await res.arrayBuffer()), mime, ...(note ? { note } : {}) };+ }+ }+ }+ throw new ImageGenerationError(note ? `The model answered in words instead: ${note.slice(0, 300)}` : `The model returned no ${kind}`);+}++async function geminiOmni(m: MediaModel, ep: MediaEndpoint, req: VideoRequest, fetchImpl: typeof fetch): Promise<MediaFile> {+ const t = withTimeout(req.signal, VIDEO_TIMEOUT_MS);+ try {+ const refs = req.references?.slice(0, 6) ?? [];+ const input = refs.length+ ? [{ type: 'text', text: req.prompt }, ...refs.map((f) => ({ type: 'image', data: readFileSync(f).toString('base64'), mime_type: mimeOf(f) || 'image/png' }))]+ : req.prompt;+ const res = await fetchImpl(`${ep.baseUrl}/interactions`, {+ method: 'POST',+ headers: { ...ep.headers, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: m.model,+ input,+ response_format: {+ type: 'video',+ aspect_ratio: req.aspect === 'portrait' ? '9:16' : '16:9',+ resolution: req.resolution ?? '720p',+ duration: `${clamp(req.seconds ?? 8, 3, 15)}s`,+ },+ }),+ signal: t.signal,+ });+ if (!res.ok) throw await failure(res);+ return await interactionOutput(await res.json(), 'video', ep, fetchImpl, t.signal);+ } finally {+ t.done();+ }+}++async function openAIVideos(m: MediaModel, ep: MediaEndpoint, req: VideoRequest, fetchImpl: typeof fetch): Promise<MediaFile> {+ const t = withTimeout(req.signal, VIDEO_TIMEOUT_MS);+ try {+ const res = await fetchImpl(`${ep.baseUrl}/videos`, {+ method: 'POST',+ headers: { ...ep.headers, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: m.model,+ prompt: req.prompt,+ size: req.aspect === 'portrait' ? '720x1280' : '1280x720',+ seconds: String(clamp(req.seconds ?? 8, 2, 20)),+ }),+ signal: t.signal,+ });+ if (!res.ok) throw await failure(res);+ let job = await res.json() as { id?: string; status?: string; error?: { message?: string } };+ const jobId = job.id;+ if (!jobId) throw new ImageGenerationError('The server started no video job');+ while (job.status !== 'completed') {+ if (job.status === 'failed' || job.status === 'expired' || job.status === 'cancelled') {+ throw new ImageGenerationError(`The video job ${job.status}${job.error?.message ? `: ${job.error.message}` : ''}`);+ }+ await new Promise((r) => setTimeout(r, POLL_MS));+ t.signal.throwIfAborted();+ const poll = await fetchImpl(`${ep.baseUrl}/videos/${encodeURIComponent(jobId)}`, { headers: ep.headers, signal: t.signal });+ if (!poll.ok) throw await failure(poll);+ job = { ...(await poll.json() as typeof job), id: jobId };+ }+ const content = await fetchImpl(`${ep.baseUrl}/videos/${encodeURIComponent(jobId)}/content`, { headers: ep.headers, signal: t.signal });+ if (!content.ok) throw await failure(content);+ return { bytes: Buffer.from(await content.arrayBuffer()), mime: content.headers.get('content-type')?.split(';')[0] || 'video/mp4' };+ } finally {+ t.done();+ }+}++export async function generateVideoWith(m: MediaModel, ep: MediaEndpoint, req: VideoRequest, fetchImpl: typeof fetch = globalThis.fetch): Promise<MediaFile> {+ if (m.backend === 'gemini-omni') return geminiOmni(m, ep, req, fetchImpl);+ if (m.backend === 'openai-videos') return openAIVideos(m, ep, req, fetchImpl);+ throw new ImageGenerationError(`${m.label} doesn't make videos`);+}++async function geminiLyria(m: MediaModel, ep: MediaEndpoint, req: MusicRequest, fetchImpl: typeof fetch): Promise<MediaFile> {+ const t = withTimeout(req.signal, MUSIC_TIMEOUT_MS);+ try {+ // Lyria takes length and "instrumental" as words in the prompt; clip models are always 30 s.+ const clip = /clip/.test(m.model);+ const prompt = [+ req.prompt.trim(),+ req.instrumental ? 'Instrumental only, no vocals.' : '',+ !clip && req.seconds ? `About ${clamp(req.seconds, 10, 300)} seconds long.` : '',+ ].filter(Boolean).join(' ');+ const res = await fetchImpl(`${ep.baseUrl}/interactions`, {+ method: 'POST',+ headers: { ...ep.headers, 'Content-Type': 'application/json', 'Api-Revision': '2026-05-20' },+ body: JSON.stringify({ model: m.model, input: prompt }),+ signal: t.signal,+ });+ if (!res.ok) throw await failure(res);+ return await interactionOutput(await res.json(), 'audio', ep, fetchImpl, t.signal);+ } finally {+ t.done();+ }+}++async function elevenLabsMusic(m: MediaModel, ep: MediaEndpoint, req: MusicRequest, fetchImpl: typeof fetch): Promise<MediaFile> {+ const t = withTimeout(req.signal, MUSIC_TIMEOUT_MS);+ try {+ const res = await fetchImpl(`${ep.baseUrl}/music?output_format=mp3_44100_128`, {+ method: 'POST',+ headers: { ...ep.headers, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ prompt: req.prompt,+ model_id: m.model,+ ...(req.seconds ? { music_length_ms: clamp(req.seconds, 3, 600) * 1000 } : {}),+ ...(req.instrumental ? { force_instrumental: true } : {}),+ }),+ signal: t.signal,+ });+ if (!res.ok) throw await failure(res);+ const bytes = Buffer.from(await res.arrayBuffer());+ if (!bytes.length) throw new ImageGenerationError('ElevenLabs sent no audio');+ return { bytes, mime: 'audio/mpeg' };+ } finally {+ t.done();+ }+}++export async function generateMusicWith(m: MediaModel, ep: MediaEndpoint, req: MusicRequest, fetchImpl: typeof fetch = globalThis.fetch): Promise<MediaFile> {+ if (m.backend === 'gemini-lyria') return geminiLyria(m, ep, req, fetchImpl);+ if (m.backend === 'elevenlabs-music') return elevenLabsMusic(m, ep, req, fetchImpl);+ throw new ImageGenerationError(`${m.label} doesn't make music`);+}diff --git a/src/plugins/speak.ts b/src/plugins/speak.tsindex 0592f7d2..d545ad88 100644--- a/src/plugins/speak.ts+++ b/src/plugins/speak.ts@@ -21,8 +21,24 @@ const GEMINI_VOICE = 'Kore';/** Speaking models, newest first; the next is tried when one isn't offered or is busy. */const GEMINI_SPEAK_MODELS = ['gemini-3.8-flash-tts', 'gemini-2.5-flash-preview-tts'];-/** The audio type synthesizeSpeech returns for an engine. */-export function speechMime(engine: SpeechEngine): string {+/** Voices each service offers by name (ElevenLabs uses voice ids; Deepgram, Aura model names). */+export const SPEECH_VOICES: Partial<Record<SpeechEngine['kind'], string[]>> = {+ openai: ['alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'nova', 'onyx', 'sage', 'shimmer', 'verse', 'marin', 'cedar'],+ gemini: ['Kore', 'Puck', 'Charon', 'Fenrir', 'Aoede', 'Leda', 'Orus', 'Zephyr'],+ deepgram: ['aura-2-thalia-en', 'aura-2-andromeda-en', 'aura-2-apollo-en', 'aura-2-arcas-en', 'aura-2-helena-en', 'aura-2-orion-en'],+};++/**+ * mp3 plays everywhere; "ogg" is Ogg/Opus, what Telegram and WhatsApp play+ * as a voice note. OpenAI and Deepgram make it themselves; Gemini and+ * ElevenLabs output is converted with ffmpeg when it is installed (else it+ * stays as it was, and goes as an audio file).+ */+export type SpeechFormat = 'mp3' | 'ogg';++/** The audio type synthesizeSpeech returns for an engine (and format). */+export function speechMime(engine: SpeechEngine, format: SpeechFormat = 'mp3'): string {+ if (format === 'ogg' && (engine.kind === 'openai' || engine.kind === 'deepgram')) return 'audio/ogg';return engine.kind === 'gemini' ? 'audio/wav' : 'audio/mpeg';}@@ -31,6 +47,11 @@ type Fetch = typeof fetch;export interface SpeakOptions {fetch?: Fetch;signal?: AbortSignal;+ /** A voice the service knows (SPEECH_VOICES; an ElevenLabs voice id). */+ voice?: string;+ /** How to say it ("calm and warm", "excited"): OpenAI gpt-4o-mini-tts and Gemini follow it. */+ instructions?: string;+ format?: SpeechFormat;}/** Speak `text` with `engine`; resolves with audio bytes of type speechMime(engine). */@@ -39,9 +60,12 @@ export async function synthesizeSpeech(text: string, engine: SpeechEngine, opts:if (!input) throw new Error('nothing to say');const f = opts.fetch ?? fetch;const signal = opts.signal;+ const ogg = opts.format === 'ogg';if (engine.kind === 'deepgram') {- const res = await f(`https://api.deepgram.com/v1/speak?model=${DEEPGRAM_MODEL}&encoding=mp3`, {+ const model = opts.voice && /^aura-/i.test(opts.voice) ? opts.voice : DEEPGRAM_MODEL;+ const encoding = ogg ? 'encoding=opus&container=ogg' : 'encoding=mp3';+ const res = await f(`https://api.deepgram.com/v1/speak?model=${encodeURIComponent(model)}&${encoding}`, {method: 'POST',headers: { Authorization: `Token ${engine.apiKey}`, 'Content-Type': 'application/json' },body: JSON.stringify({ text: input.slice(0, DEEPGRAM_MAX_CHARS) }),@@ -57,8 +81,9 @@ export async function synthesizeSpeech(text: string, engine: SpeechEngine, opts:method: 'POST',headers: { 'x-goog-api-key': engine.apiKey, 'Content-Type': 'application/json' },body: JSON.stringify({- contents: [{ parts: [{ text: input.slice(0, SPEAK_MAX_CHARS) }] }],- generationConfig: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: GEMINI_VOICE } } } },+ // Gemini takes the style as words in front of the text.+ contents: [{ parts: [{ text: (opts.instructions ? `Say this ${opts.instructions.replace(/[.:]+$/, '')}: ` : '') + input.slice(0, SPEAK_MAX_CHARS) }] }],+ generationConfig: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: opts.voice || GEMINI_VOICE } } } },}),signal,});@@ -75,7 +100,7 @@ export async function synthesizeSpeech(text: string, engine: SpeechEngine, opts:}if (engine.kind === 'elevenlabs') {- const res = await f(`https://api.elevenlabs.io/v1/text-to-speech/${ELEVENLABS_VOICE}?output_format=mp3_44100_128`, {+ const res = await f(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(opts.voice || ELEVENLABS_VOICE)}?output_format=mp3_44100_128`, {method: 'POST',headers: { 'xi-api-key': engine.apiKey, 'Content-Type': 'application/json' },body: JSON.stringify({ text: input.slice(0, SPEAK_MAX_CHARS), model_id: ELEVENLABS_MODEL }),@@ -87,14 +112,24 @@ export async function synthesizeSpeech(text: string, engine: SpeechEngine, opts:const base = (engine.baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');const say = (model: string) => f(`${base}/audio/speech`, {method: 'POST',- headers: { Authorization: `Bearer ${engine.apiKey}`, 'Content-Type': 'application/json' },- body: JSON.stringify({ model, voice: OPENAI_VOICE, input: input.slice(0, SPEAK_MAX_CHARS), response_format: 'mp3' }),+ headers: { ...(engine.headers ?? { Authorization: `Bearer ${engine.apiKey}` }), 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model,+ voice: opts.voice || OPENAI_VOICE,+ input: input.slice(0, SPEAK_MAX_CHARS),+ // "opus" is Ogg/Opus: a voice note as it is.+ response_format: ogg ? 'opus' : 'mp3',+ // Only the instructable models take a style; tts-1 rejects the field.+ ...(opts.instructions && !/^tts-1/i.test(model) ? { instructions: opts.instructions } : {}),+ }),signal,});+ // A chosen model is used as is; otherwise the newer one, then the classic one+ // on an OpenAI-compatible endpoint that doesn't have it.+ if (engine.model) return audioOf(await say(engine.model), engine.label);let res = await say('gpt-4o-mini-tts');- // An OpenAI-compatible endpoint without the newer model: try the classic one.if (res.status === 400 || res.status === 404) res = await say('tts-1');- return audioOf(res, 'OpenAI');+ return audioOf(res, engine.label || 'OpenAI');}/**diff --git a/src/plugins/transcribe.ts b/src/plugins/transcribe.tsindex 2c277ac4..85ba9a3e 100644--- a/src/plugins/transcribe.ts+++ b/src/plugins/transcribe.ts@@ -17,7 +17,7 @@ export interface TranscribeCreds {}export type SpeechEngine =- | { kind: 'openai'; label: string; apiKey: string; baseUrl?: string }+ | { kind: 'openai'; label: string; apiKey: string; baseUrl?: string; headers?: Record<string, string>; model?: string }| { kind: 'deepgram'; label: string; apiKey: string }| { kind: 'elevenlabs'; label: string; apiKey: string }| { kind: 'gemini'; label: string; apiKey: string };diff --git a/src/plugins/types.ts b/src/plugins/types.tsindex 88bca3b2..d2c7d353 100644--- a/src/plugins/types.ts+++ b/src/plugins/types.ts@@ -36,7 +36,7 @@ export const RESERVED_PLUGIN_IDS: ReadonlySet<string> = new Set(['mcp']);* TUI's SLASH_COMMANDS by src/plugins/commands.test.ts.*/export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([- 'agents', 'bg', 'bot', 'bots', 'budget', 'call', 'calls', 'chat', 'cloud', 'code', 'effort', 'halt', 'help', 'log', 'memory', 'menu', 'models', 'model',+ 'agents', 'bg', 'bot', 'bots', 'budget', 'call', 'calls', 'chat', 'cloud', 'code', 'effort', 'halt', 'image', 'imagine', 'img', 'media', 'say', 'tts', 'video', 'music', 'song', 'help', 'log', 'memory', 'menu', 'models', 'model','permissions', 'plugin', 'plugins', 'progress', 'research', 'reset', 'server', 'saver', 'session', 'sessions', 'skills', 'spotify','status', 'stop', 'stream', 'tools', 'update', 'view', 'whatsnew', 'ws', 'start', 'skip', 'new', 'compact', 'clear','approve', 'deny', 'yes', 'no', 'cancel', 'pair', 'unpair', 'telegram', 'discord', 'slack', 'signal', 'web', 'exit', 'quit',diff --git a/src/providers/base.ts b/src/providers/base.tsindex da46b9da..5b4bfa0f 100644--- a/src/providers/base.ts+++ b/src/providers/base.ts@@ -1,5 +1,12 @@import type { ProviderConfig } from '../utils/config.js';+/** An OpenAI-style HTTP endpoint and its auth, for calls beyond chat (image generation…). */+export interface MediaEndpoint {+ /** Ends in /v1 (or the server's equivalent): "<baseUrl>/images/generations". */+ baseUrl: string;+ headers: Record<string, string>;+}+export interface LLMResponse {text: string;inputTokens: number;@@ -32,6 +39,11 @@ export abstract class BaseProvider {return this.config.model;}+ /** The configured endpoint (empty for providers without one). */+ getBaseUrl(): string {+ return this.config.baseUrl ?? '';+ }+/*** What the owner declared about this endpoint's capability, or undefined when* nothing was declared — in which case the name-based guess applies.@@ -52,4 +64,13 @@ export abstract class BaseProvider {supportsToolResultImages(): boolean {return false;}++ /**+ * Where this provider's OpenAI-style media endpoints live (images, later+ * speech and video), with auth; undefined when it has none Mercury can+ * call (src/media).+ */+ async mediaEndpoint(): Promise<MediaEndpoint | undefined> {+ return undefined;+ }}\ No newline at end of filediff --git a/src/providers/mercury-cloud.ts b/src/providers/mercury-cloud.tsindex 0aa68a81..2b480105 100644--- a/src/providers/mercury-cloud.ts+++ b/src/providers/mercury-cloud.ts@@ -1,6 +1,6 @@import { createOpenAI } from '@ai-sdk/openai';import { generateText, streamText } from 'ai';-import { BaseProvider } from './base.js';+import { BaseProvider, type MediaEndpoint } from './base.js';import type { ProviderConfig } from '../utils/config.js';import type { LLMResponse, LLMStreamChunk } from './base.js';import { logger } from '../utils/logger.js';@@ -168,6 +168,17 @@ export class MercuryCloudProvider extends BaseProvider {}}+ async mediaEndpoint(): Promise<MediaEndpoint | undefined> {+ await this.ensureFreshToken().catch(() => {});+ const baseUrl = this.config.baseUrl || '';+ const jwt = this.usesAccessKey ? this.config.apiKey : this.tokenStore?.getJwt() ?? this.config.apiKey;+ if (!baseUrl || !jwt) return undefined;+ return {+ baseUrl: baseUrl.endsWith('/v1') ? baseUrl : `${baseUrl}/v1`,+ headers: { Authorization: `Bearer ${jwt}`, ...(this.cloudHeaders() ?? {}) },+ };+ }+async getModelInstanceAsync(): Promise<any> {await this.ensureFreshToken();return this.modelInstance;diff --git a/src/providers/openai-compat.ts b/src/providers/openai-compat.tsindex 2319859b..6c24c43f 100644--- a/src/providers/openai-compat.ts+++ b/src/providers/openai-compat.ts@@ -1,6 +1,6 @@import { createOpenAI } from '@ai-sdk/openai';import { generateText, streamText } from 'ai';-import { BaseProvider } from './base.js';+import { BaseProvider, type MediaEndpoint } from './base.js';import type { ProviderConfig } from '../utils/config.js';import type { LLMResponse, LLMStreamChunk } from './base.js';import { logger } from '../utils/logger.js';@@ -88,6 +88,16 @@ export class OpenAICompatProvider extends BaseProvider {: this.client(config.model);}+ async mediaEndpoint(): Promise<MediaEndpoint | undefined> {+ if (!this.config.baseUrl) return undefined;+ const basic = basicAuthHeaders(this.config);+ const attribution = aimlapiHeaders(this.config.baseUrl) ?? {};+ return {+ baseUrl: this.config.baseUrl.replace(/\/+$/, ''),+ headers: { ...attribution, ...(basic ?? (this.config.apiKey ? { Authorization: `Bearer ${this.config.apiKey}` } : {})) },+ };+ }+private formatApiError(err: unknown): Error {if (err instanceof Error) {const msg = err.message || '';diff --git a/src/utils/manual.ts b/src/utils/manual.tsindex de2f2885..0acfb964 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -98,6 +98,19 @@ export const CHAT_COMMAND_HELP: ReadonlyArray<readonly [string, string]> = [['/permissions', 'Change permission mode (Ask Me / Allow All)'],['/models', 'List configured providers and their models'],['/models use <provider>', 'Switch the default model (saved across restarts)'],+ ['/image <prompt>', 'Make an image with an image model (add --landscape or --portrait)'],+ ['/media', 'Show the image model in use and the ones your providers offer'],+ ['/media image <number|auto>', 'Choose the default image model (or let Mercury pick)'],+ ['/media refresh', 'Ask your providers again which image models they have'],+ ['/say <text>', 'Say it out loud: a voice note in chat apps, audio in the apps (add --style "calm")'],+ ['/video <shot>', 'Make a short video (3–15 s; --portrait, --seconds 6); it arrives here when ready'],+ ['/music <style>', 'Make a song or instrumental (--instrumental, --seconds 60); it arrives here when ready'],+ ['/media video <number|auto>', 'Choose the video model'],+ ['/media music <number|auto>', 'Choose the music model'],+ ['/media jobs', 'Videos and songs being made, and the last few made'],+ ['/media speech <number|auto>', 'Choose what speaks (OpenAI, Gemini, ElevenLabs, Deepgram, or a provider model)'],+ ['/media voice <name|default>', 'Choose the voice (e.g. nova, Kore)'],+ ['/media replies <off|mirror|always>', 'When chat-app replies also come as a voice note (mirror: when you send one)'],['/effort', 'Show the thinking effort in this chat and the levels the model takes'],['/effort <auto|low|medium|high|xhigh|max>', 'Set the thinking effort for this chat only'],['/effort default', "Go back to the model's default effort in this chat"],@@ -400,6 +413,10 @@ export function getTelegramHelp(): string {lines.push('/update ignore — Silence the offered update notice');lines.push('/permissions — Switch Ask Me / Allow All mode');lines.push('/models — List providers or switch AI model (saved across restarts)');+ lines.push('/image <prompt> — Make an image with an image model');+ lines.push('/media — Image model in use; /media image <n> to change it');+ lines.push('/say <text> — Say it out loud (a voice note in chat apps)');+ lines.push('/video <shot>, /music <style> — Make a video or song; it arrives when ready');lines.push('/effort — Show or set how hard the current model thinks');lines.push('/cloud models — List Mercury Cloud models and switch');lines.push('/stream — Toggle text streaming on/off');@@ -519,6 +536,10 @@ export function getDiscordHelp(): string {lines.push('/update ignore \u2014 Silence the offered update notice');lines.push('/permissions \u2014 Switch Ask Me / Allow All mode');lines.push('/models \u2014 List providers or switch AI model (saved across restarts)');+ lines.push('/image <prompt> \u2014 Make an image with an image model');+ lines.push('/media \u2014 Image model in use; /media image <n> to change it');+ lines.push('/say <text> \u2014 Say it out loud (a voice note in chat apps)');+ lines.push('/video <shot>, /music <style> \u2014 Make a video or song; it arrives when ready');lines.push('/effort \u2014 Show or set how hard the current model thinks');lines.push('/cloud models \u2014 List Mercury Cloud models and switch');lines.push('/stop \u2014 Stop the current task and its agents now');diff --git a/src/utils/model-prefs.test.ts b/src/utils/model-prefs.test.tsindex f66f4b12..4efca649 100644--- a/src/utils/model-prefs.test.ts+++ b/src/utils/model-prefs.test.ts@@ -28,6 +28,10 @@ describe('humanizeModelName', () => {['hf.co/mradermacher/qwen3.5-9b-nsfw-captioning-v5-GGUF:Q8_0', 'Qwen 3.5 9B NSFW Captioning V5 (Q8_0)'],['mistral-small-24b-huihui-ablit-q4ks:latest', 'Mistral Small 24B Huihui Abliterated (Q4KS)'],['codex-auto-review', 'Codex Auto Review'],+ ['claude-haiku-4-5-20251001', 'Claude Haiku 4.5'],+ ['claude-opus-5-5', 'Claude Opus 5.5'],+ ['claude-sonnet-4-20250514', 'Claude Sonnet 4'],+ ['llama-3-1-8b-instruct', 'Llama 3.1 8B Instruct'],['hf.co/BennyDaBall/Qwopus3.8-27B-Flash-NVFP4:NVFP4', 'Qwopus 3.8 27B Flash (NVFP4)'],])('%s → %s', (raw, expected) => {expect(humanizeModelName(raw)).toBe(expected);diff --git a/src/utils/model-prefs.ts b/src/utils/model-prefs.tsindex b2828d27..9c90431a 100644--- a/src/utils/model-prefs.ts+++ b/src/utils/model-prefs.ts@@ -435,7 +435,15 @@ export function humanizeModelName(model: string): string {const extras: string[] = [];// Hyphens separate words; underscores belong to quant tags like Q4_K_M.- const parts = name.split(/[-\s]+/).filter(Boolean);+ // A dated snapshot ("…-20251001") reads as the model; a version split into+ // numbers ("haiku-4-5", "llama-3-1-8b") reads as one: 4.5, 3.1.+ const raw = name.split(/[-\s]+/).filter(Boolean).filter((p, i, all) => !(i > 0 && /^(19|20)\d{6}$/.test(p) && all.length > 1));+ const parts: string[] = [];+ for (const p of raw) {+ const prev = parts[parts.length - 1];+ if (/^\d{1,2}$/.test(p) && prev && /^\d{1,2}$/.test(prev) && parts.length >= 2 && !/^\d/.test(parts[parts.length - 2])) parts[parts.length - 1] = `${prev}.${p}`;+ else parts.push(p);+ }for (let i = 0; i < parts.length; i++) {const part = parts[i];// Keep GPT-style "GPT-6" / "GPT-5.6" joined.diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex fa10e1f3..6bd1d964 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -60,7 +60,10 @@ export const API_FEATURES: readonly string[] = Object.freeze(['budget.split', // GET /api/budget daily.split + daily.cachedWeight, PUT { cachedWeight }; /api/usage split + counted breakdowns — #296'chat.usage', // message.usage on assistant replies; text_done { usage } — what each reply cost'chat.effort', // POST /api/chat/effort, GET /api/chat/models?sessionId= current.effort — per-chat effort (#188)- 'chat.trace', // live step ids/durations, progress/phase events, message.trace on replies (ADR-041)+ 'media.image', // GET /api/media/models, PUT /api/media/default; POST /api/chat/send { media: { kind: "image", aspect? } } (ADR-042)+ 'media.jobs', // GET /api/media/models video, music; PUT /api/media/default { kind: video|music }; SSE 'media_ready' { text, artifacts }; send { media: { kind: video|music } } (ADR-042 phase 3)+ 'media.speech', // GET /api/media/models speech { options, current, choice, voice, replies }, PUT /api/media/speech (ADR-042 phase 2)+ 'chat.trace', // live step ids/durations, progress/phase events, message.trace on replies (ADR-041); GET /api/chat/threads/:id/live (a running reply so far)'chat.research', // SSE 'research' / 'research_plan' / 'research_plan_resolved' / 'notice'; GET /api/chat/threads/:id/research, POST …/research/finish, …/research/off, POST /api/chat/research/plan/:id; message.research; step_done { failed, reason }]);diff --git a/src/web/api/chat-live-route.test.ts b/src/web/api/chat-live-route.test.tsnew file mode 100644index 00000000..c7523d3e--- /dev/null+++ b/src/web/api/chat-live-route.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it, vi } from 'vitest';++await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-live-route-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), [+ 'identity:', ' owner: Test', 'providers:', ' default: mercuryCloud', ' mercuryCloud:', ' name: mercuryCloud', ' apiKey: sk-mc-test', ' baseUrl: https://cloud.test', ' model: mercury-pro', ' enabled: true', '',+ ].join('\n'));+ process.env.MERCURY_HOME = dir;+});++const { default: chat, setTurnControls, setWebChannel, setCurrentProviderCallback } = await import('./chat.js');+const { WebChannel } = await import('../../channels/web.js');+const { TurnTrace } = await import('../../core/turn-trace.js');+const { setMediaService } = await import('../../media/runtime.js');+const { MediaService } = await import('../../media/service.js');++/**+ * Coming back to a chat mid-reply shows it as far as it got; the model+ * picker lists Mercury Cloud's models for the account's tier and says when+ * the Cloud sign-in has expired.+ */+describe('a reply still being worked on', () => {+ it('its thinking and steps so far, what it is doing, and the text written so far', async () => {+ const web = new WebChannel('Mercury');+ (web as unknown as { broadcast: () => boolean }).broadcast = () => true;+ setWebChannel(web);+ let now = 1000;+ const trace = new TurnTrace(() => now);+ trace.reasoning('Planning.');+ trace.toolStarted('c1', 'Running npm test');+ setTurnControls({+ running: () => [], waiting: () => [], limit: () => ({ limit: 4, configured: 0, auto: 4 }), setLimit: () => {},+ live: (id) => (id === 'thread-1' ? { startedAt: 900, activity: '⚙️ Running npm test', trace: trace.peek(900) } : undefined),+ });+ async function* chunks() { yield 'Half '; yield 'an answer'; }+ await web.stream(chunks(), 'thread-1');++ const body = await (await chat.request('http://127.0.0.1/api/chat/threads/thread-1/live')).json() as Record<string, any>;+ expect(body.running).toBe(true);+ expect(body.text).toBe('Half an answer');+ expect(body.trace.items.map((i: { kind: string }) => i.kind)).toEqual(['reasoning', 'tool']);+ // Nothing is ended by looking: the tool still runs, the thinking block is closed only by the tool start.+ expect(body.trace.items[1]).toMatchObject({ id: 'c1', status: 'running' });++ expect(await (await chat.request('http://127.0.0.1/api/chat/threads/thread-2/live')).json()).toEqual({ running: false });+ // The reply arrived: no longer live text.+ await web.send('Half an answer.', 'thread-1');+ expect(web.liveTextFor('thread-1')).toBe('');+ now++;+ });++ it('a later round of the same turn writes on after the earlier text; a cleared turn starts fresh', async () => {+ const web = new WebChannel('Mercury');+ (web as unknown as { broadcast: () => boolean }).broadcast = () => true;+ async function* a() { yield 'First.'; }+ async function* b() { yield ' Second.'; }+ await web.stream(a(), 't');+ await web.stream(b(), 't');+ expect(web.liveTextFor('t')).toBe('First. Second.');+ web.clearLiveText('t');+ expect(web.liveTextFor('t')).toBe('');+ });+});++describe('Mercury Cloud in the model picker', () => {+ function withCloud(respond: () => Response) {+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => respond());+ setMediaService(new MediaService({+ sources: () => [{ name: 'mercuryCloud', baseUrl: 'https://cloud.test', endpoint: async () => ({ baseUrl: 'https://cloud.test/v1', headers: { Authorization: 'Bearer t' } }) }],+ currentProvider: () => 'mercuryCloud',+ }));+ setCurrentProviderCallback(() => ({ name: 'mercuryCloud', model: 'mercury-pro' }));+ return fetchSpy;+ }++ it("lists the models this account's tier may use, with Cloud's names", async () => {+ const spy = withCloud(() => new Response(JSON.stringify({ data: [+ { id: 'mercury-pro', label: 'Mercury Pro', available: true },+ { id: 'mercury-flash', label: 'Mercury Flash', available: true },+ { id: 'mercury-opus', label: 'Mercury Opus', available: false },+ { id: 'mercury-tts', label: 'Voice', available: true },+ ] }), { headers: { 'content-type': 'application/json' } }));+ const body = await (await chat.request('http://127.0.0.1/api/chat/models')).json() as { providers: Array<{ name: string; model: string; label: string }>; notices: string[] };+ const cloud = body.providers.filter((p) => p.name === 'mercuryCloud');+ expect(cloud.map((p) => p.model)).toEqual(['mercury-pro', 'mercury-flash']);+ expect(cloud.map((p) => p.label)).toEqual(['Mercury Pro', 'Mercury Flash']);+ expect(body.notices).toEqual([]);+ spy.mockRestore();+ });+});diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex f6c86da9..adff7579 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -20,6 +20,8 @@ import type { SessionRepository } from '../../sessions/index.js';import { SessionTitleError } from '../../sessions/repository.js';import { loadPermissionMode, savePermissionMode } from '../../capabilities/permission-mode-store.js';import { discoverReasoningCaps } from '../../providers/reasoning-discovery.js';+import { mediaService } from '../../media/runtime.js';+import { isChatModelId } from '../../utils/provider-models.js';import {getModelPref, setModelPref, humanizeModelName, modelGroupLabel,reasoningLevelsFor, effectiveReasoning, isReasoningLevel, isValidModelRef, type ReasoningLevel,@@ -134,6 +136,8 @@ export interface TurnControls {limit: () => { limit: number; configured: number; auto: number };/** Set the configured limit (0 = automatic); applies at once and persists. */setLimit: (configured: number) => void;+ /** The reply a chat is working on now, as far as it got (agent.liveTurn). */+ live?: (id: string) => { startedAt: number; activity: string; trace: unknown } | undefined;}let turnControls: TurnControls | null = null;export function setTurnControls(controls: TurnControls | null): void {@@ -328,6 +332,8 @@ chat.post('/api/chat/send', async (c) => {programming?: unknown;/** Folder the coding turn works in (an existing directory). */cwd?: unknown;+ /** The desktop's Image switch: { kind: "image", aspect? } (ADR-042). */+ media?: unknown;}>();const content = body.content?.trim() ?? '';const upload = storeInlineAttachments(body.attachments);@@ -362,7 +368,11 @@ chat.post('/api/chat/send', async (c) => {}codeCwd = resolvedCwd;}- webChannel.emitMessageInThread(text, session.id, session.id, undefined, undefined, undefined, upload.attachments, { ...(programming ? { programming, cwd: codeCwd } : {}), thisComputer: isThisComputer(c) });+ const mediaRaw = body.media as { kind?: unknown; aspect?: unknown } | undefined;+ const media = mediaRaw?.kind === 'image' || mediaRaw?.kind === 'video' || mediaRaw?.kind === 'music'+ ? { kind: mediaRaw.kind as 'image' | 'video' | 'music', ...(mediaRaw.aspect === 'square' || mediaRaw.aspect === 'landscape' || mediaRaw.aspect === 'portrait' ? { aspect: mediaRaw.aspect } : {}) }+ : undefined;+ webChannel.emitMessageInThread(text, session.id, session.id, undefined, undefined, undefined, upload.attachments, { ...(programming ? { programming, cwd: codeCwd } : {}), thisComputer: isThisComputer(c), ...(media ? { media } : {}) });return c.json({sent: true,sessionId: session.id,@@ -533,19 +543,59 @@ async function listChatGPTModels(): Promise<string[]> {}}+/**+ * Mercury Cloud's chat models this account's tier may use (its /v1/models+ * marks each `available`), with Cloud's own names. Cached for five minutes.+ */+let cloudModelCache: { at: number; models: Array<{ id: string; label?: string }> } | null = null;+const CLOUD_MODEL_TTL_MS = 5 * 60 * 1000;+const cloudLabels = new Map<string, string>();+/** Why the last Mercury Cloud lookup failed, for the picker to say. */+let cloudProblem: string | null = null;++async function listMercuryCloudModels(): Promise<string[]> {+ if (cloudModelCache && Date.now() - cloudModelCache.at < CLOUD_MODEL_TTL_MS) return cloudModelCache.models.map((m) => m.id);+ if (recentlyFailed('mercuryCloud')) return cloudModelCache?.models.map((m) => m.id) ?? [];+ try {+ // The provider's own endpoint and auth (a fresh JWT or the access key).+ const ep = await mediaService()?.endpointFor('mercuryCloud');+ if (!ep) throw new Error('Mercury Cloud is not connected');+ const res = await fetch(`${ep.baseUrl}/models`, { headers: ep.headers, signal: AbortSignal.timeout(5000) });+ if (res.status === 401 || res.status === 403) throw new Error('Mercury Cloud sign-in expired: run `mercury cloud login` (or sign in again in Settings → Cloud) to see your models.');+ if (!res.ok) throw new Error(`Mercury Cloud didn't answer (HTTP ${res.status}).`);+ const data = (await res.json()) as { data?: Array<{ id?: string; label?: string; available?: boolean; output_modalities?: unknown }> };+ const all = (data.data ?? []).filter((m): m is { id: string; label?: string; available?: boolean; output_modalities?: unknown } => typeof m.id === 'string' && m.id.length > 0);+ // The tier decides: only models marked available (older deployments without the flag: all of them).+ const tiered = all.some((m) => typeof m.available === 'boolean') ? all.filter((m) => m.available === true) : all;+ const chat = tiered.filter((m) => isChatModelId(m.id) && (!Array.isArray(m.output_modalities) || m.output_modalities.includes('text')));+ for (const m of chat) if (m.label) cloudLabels.set(m.id, m.label);+ cloudModelCache = { at: Date.now(), models: chat.map((m) => ({ id: m.id, ...(m.label ? { label: m.label } : {}) })) };+ failedLookups.delete('mercuryCloud');+ cloudProblem = null;+ return cloudModelCache.models.map((m) => m.id);+ } catch (err) {+ cloudProblem = err instanceof Error ? err.message : String(err);+ failedLookups.set('mercuryCloud', Date.now());+ return cloudModelCache?.models.map((m) => m.id) ?? [];+ }+}+/** Providers that serve many models list each one; others list their configured model. */async function listProviderModels(p: ProviderConfig): Promise<string[]> {if (p.name === 'ollamaLocal') return listOllamaModels(p);if (p.name === 'chatgptWeb') return [...(await listChatGPTModels())];+ if (p.name === 'mercuryCloud') return listMercuryCloudModels();return [];}/** What the picker needs to show a model in plain language. */function describeModel(provider: string, model: string) {const pref = getModelPref(provider, model);+ // Mercury Cloud names its models itself ("Mercury Pro").+ const auto = (provider === 'mercuryCloud' ? cloudLabels.get(model) : undefined) ?? humanizeModelName(model);return {- label: pref.label ?? humanizeModelName(model),- autoLabel: humanizeModelName(model),+ label: pref.label ?? auto,+ autoLabel: auto,customLabel: pref.label ?? null,group: modelGroupLabel(provider, model),reasoning: effectiveReasoning(provider, model) ?? 'auto',@@ -553,6 +603,18 @@ function describeModel(provider: string, model: string) {};}+/**+ * The reply this chat is working on right now: its thinking and steps so+ * far, the text written so far, and what it is doing. A screen that left+ * the chat mid-turn shows this on return, then follows the live events.+ */+chat.get('/api/chat/threads/:id/live', (c) => {+ const id = c.req.param('id');+ const live = turnControls?.live?.(id);+ if (!live) return c.json({ running: false });+ return c.json({ running: true, startedAt: live.startedAt, activity: live.activity, trace: live.trace, text: webChannel?.liveTextFor(id) ?? '' });+});+chat.get('/api/chat/models', async (c) => {const config = loadConfig();const active = getActiveProviders(config);@@ -581,6 +643,8 @@ chat.get('/api/chat/models', async (c) => {const chatKey = sessionId && isValidModelRef(sessionId) ? sessionId : undefined;const effort = effortFor(current.name, current.model, chatKey);return c.json({+ // Lookups that failed, said plainly (an expired Mercury Cloud sign-in).+ notices: active.some((p) => p.name === 'mercuryCloud') && cloudProblem ? [cloudProblem] : [],current: {...current,...describeModel(current.name, current.model),diff --git a/src/web/api/media-route.test.ts b/src/web/api/media-route.test.tsnew file mode 100644index 00000000..c0460f56--- /dev/null+++ b/src/web/api/media-route.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++await (async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ process.env.MERCURY_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-media-route-'));+})();++const { default: media } = await import('./media.js');+const { setMediaService } = await import('../../media/runtime.js');+const { MediaService } = await import('../../media/service.js');+const { loadMediaPrefs, resetMediaPrefsCache } = await import('../../media/prefs.js');++describe('/api/media', () => {+ it('lists image models with the automatic pick, and sets the default', async () => {+ const fake = (async () => new Response(JSON.stringify({ data: [{ id: 'gpt-image-1' }] }), { headers: { 'content-type': 'application/json' } })) as unknown as typeof fetch;+ setMediaService(new MediaService({ sources: () => [{ name: 'openai', baseUrl: 'http://o/v1', endpoint: async () => ({ baseUrl: 'http://o/v1', headers: {} }) }], currentProvider: () => 'openai' }, fake));+ const listed = await (await media.request('http://127.0.0.1/api/media/models')).json() as { image: { models: Array<{ ref: string }>; auto: { ref: string } | null; default: unknown } };+ expect(listed.image.models.map((m) => m.ref)).toEqual(['openai::gpt-image-1']);+ expect(listed.image.auto?.ref).toBe('openai::gpt-image-1');+ expect(listed.image.default).toBeNull();++ const put = (body: unknown) => media.request('http://127.0.0.1/api/media/default', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });+ expect((await put({ kind: 'image', ref: 'openai::gpt-image-1' })).status).toBe(200);+ resetMediaPrefsCache();+ expect(loadMediaPrefs().image?.primary).toBe('openai::gpt-image-1');+ expect((await put({ kind: 'image', ref: 'not a ref' })).status).toBe(400);+ expect((await put({ kind: 'speech', ref: null })).status).toBe(400);+ setMediaService(null);+ });++ it('changes speech prefs, refusing bad values', async () => {+ const put = (body: unknown) => media.request('http://127.0.0.1/api/media/speech', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });+ const ok = await put({ choice: 'openai', replies: 'always' });+ expect(ok.status).toBe(200);+ expect((await ok.json() as { speech: unknown }).speech).toEqual({ choice: 'openai', replies: 'always' });+ expect((await put({ voice: 'nova' })).status).toBe(200);+ resetMediaPrefsCache();+ expect(loadMediaPrefs().speech).toEqual({ choice: 'openai', replies: 'always', voice: 'nova' });+ expect((await put({ replies: 'sometimes' })).status).toBe(400);+ expect((await put({ choice: 'nonsense' })).status).toBe(400);+ });+});diff --git a/src/web/api/media.ts b/src/web/api/media.tsnew file mode 100644index 00000000..c1af5b1d--- /dev/null+++ b/src/web/api/media.ts@@ -0,0 +1,88 @@+import { Hono } from 'hono';+import { mediaService } from '../../media/runtime.js';+import { setMediaDefault, setSpeechPrefs } from '../../media/prefs.js';+import { getSpeechService } from '../../media/speech.js';+import { mediaJobs } from '../../media/jobs.js';++/**+ * Media models for the apps (ADR-042).+ * GET /api/media/models[?refresh=1] image models on the configured providers,+ * the default and the automatic pick+ * PUT /api/media/default { kind: "image", ref: "provider::model" | null }+ * PUT /api/media/speech { choice?, voice?, replies? } (null clears; phase 2)+ */+const media = new Hono();++media.get('/api/media/models', async (c) => {+ const service = mediaService();+ if (!service) return c.json({ image: { models: [], default: null, auto: null }, speech: null });+ const refresh = c.req.query('refresh') === '1';+ const speechService = getSpeechService();+ const [setup, speech, video, music] = await Promise.all([+ service.imageSetup({ refresh }),+ speechService ? Promise.all([speechService.options({ refresh }), speechService.target()]) : Promise.resolve(null),+ service.setup('video', { refresh }),+ service.setup('music', { refresh }),+ ]);+ const kindJson = (k: typeof video) => ({+ models: k.models.map(({ ref, provider, model, label, group, canEdit }) => ({ ref, provider, model, label, group, canEdit })),+ default: k.default ?? null,+ auto: k.auto ? { ref: k.auto.ref, label: k.auto.label, group: k.auto.group } : null,+ });+ const prefs = speechService?.prefs() ?? {};+ return c.json({+ video: kindJson(video),+ music: kindJson(music),+ speech: speech ? {+ options: speech[0],+ current: speech[1] ? { id: speech[1].id, label: speech[1].label, voice: speech[1].voice ?? null } : null,+ choice: prefs.choice ?? null,+ voice: prefs.voice ?? null,+ replies: prefs.replies ?? 'mirror',+ } : null,+ image: {+ models: setup.models.map(({ ref, provider, model, label, group, canEdit }) => ({ ref, provider, model, label, group, canEdit })),+ default: setup.default ?? null,+ auto: setup.auto ? { ref: setup.auto.ref, label: setup.auto.label, group: setup.auto.group } : null,+ },+ });+});++media.put('/api/media/default', async (c) => {+ const body = await c.req.json<{ kind?: unknown; ref?: unknown }>().catch(() => null);+ if (!body || (body.kind !== 'image' && body.kind !== 'video' && body.kind !== 'music')) return c.json({ error: 'kind must be "image", "video" or "music"' }, 400);+ if (body.ref !== null && typeof body.ref !== 'string') return c.json({ error: 'ref must be "provider::model" or null' }, 400);+ try {+ setMediaDefault(body.kind, body.ref);+ } catch (err) {+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 400);+ }+ return c.json({ ok: true });+});++media.put('/api/media/speech', async (c) => {+ const body = await c.req.json<{ choice?: unknown; voice?: unknown; replies?: unknown }>().catch(() => null);+ if (!body) return c.json({ error: 'JSON body required' }, 400);+ const str = (v: unknown) => (v === null || typeof v === 'string' ? v : undefined);+ try {+ const next = setSpeechPrefs({+ ...(body.choice !== undefined ? { choice: str(body.choice) ?? null } : {}),+ ...(body.voice !== undefined ? { voice: str(body.voice) ?? null } : {}),+ ...(body.replies !== undefined ? { replies: (str(body.replies) ?? null) as 'off' | 'mirror' | 'always' | null } : {}),+ });+ return c.json({ ok: true, speech: next });+ } catch (err) {+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 400);+ }+});++/** Videos and songs this chat is still making (placeholders on a reopened chat). */+media.get('/api/media/jobs', (c) => {+ const id = c.req.query('sessionId');+ const list = mediaJobs()?.list(id ? { channelId: id } : undefined, 20) ?? [];+ return c.json({+ jobs: list.filter((j) => j.status === 'running').map((j) => ({ jobId: j.id, kind: j.kind, prompt: j.prompt.slice(0, 200), startedAt: j.createdAt, ...(j.aspect ? { aspect: j.aspect } : {}) })),+ });+});++export default media;diff --git a/src/web/api/speak.ts b/src/web/api/speak.tsindex 1ce72a2c..6f94fb09 100644--- a/src/web/api/speak.ts+++ b/src/web/api/speak.ts@@ -1,6 +1,7 @@import { Hono } from 'hono';import { currentSpeechEngine, NO_SPEECH_SERVICE } from '../../plugins/speech-choice.js';import { SPEAK_MAX_CHARS, speechMime, synthesizeSpeech } from '../../plugins/speak.js';+import { getSpeechService } from '../../media/speech.js';/*** Read aloud for every client: text in, speech out.@@ -19,19 +20,30 @@ let doFetch: Fetch | undefined;/** Test seam. */export function setSpeakFetch(f: Fetch | undefined): void { doFetch = f; }-function engine() {- return currentSpeechEngine('speak');+/**+ * What reads aloud: the speech choice in Settings → AI → Media (with its+ * voice) when the runtime has one, else the voice in Settings → Voice.+ */+async function target(): Promise<{ engine: NonNullable<ReturnType<typeof currentSpeechEngine>>; voice?: string } | null> {+ const service = getSpeechService();+ if (service) {+ const t = await service.target();+ return t ? { engine: t.engine, ...(t.voice ? { voice: t.voice } : {}) } : null;+ }+ const engine = currentSpeechEngine('speak');+ return engine ? { engine } : null;}const speak = new Hono();-speak.get('/api/speak', (c) => {- const e = engine();- return c.json({ available: !!e, engine: e?.label ?? null, maxChars: SPEAK_MAX_CHARS });+speak.get('/api/speak', async (c) => {+ const t = await target();+ return c.json({ available: !!t, engine: t?.engine.label ?? null, maxChars: SPEAK_MAX_CHARS });});speak.post('/api/speak', async (c) => {- const e = engine();+ const t = await target();+ const e = t?.engine;if (!e) {return c.json({ error: `Reading aloud needs ${NO_SPEECH_SERVICE}`, needs: 'speech' }, 412);}@@ -40,7 +52,7 @@ speak.post('/api/speak', async (c) => {if (!text) return c.json({ error: 'Nothing to read.' }, 400);if (text.length > SPEAK_MAX_CHARS) return c.json({ error: `Send at most ${SPEAK_MAX_CHARS} characters at a time.`, maxChars: SPEAK_MAX_CHARS }, 413);try {- const audio = await synthesizeSpeech(text, e, { fetch: doFetch, signal: c.req.raw.signal });+ const audio = await synthesizeSpeech(text, e, { fetch: doFetch, signal: c.req.raw.signal, ...(t?.voice ? { voice: t.voice } : {}) });return new Response(audio, { headers: { 'Content-Type': speechMime(e), 'Cache-Control': 'no-store', 'X-Speech-Engine': e.label } });} catch (err) {const message = err instanceof Error ? err.message : String(err);diff --git a/src/web/server.ts b/src/web/server.tsindex d21c6877..d8c6fddb 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -1,4 +1,5 @@import { Hono } from 'hono';+import mediaRoutes from './api/media.js';import { isBunVirtualPath } from '../utils/bun-path.js';import { createAdaptorServer } from '@hono/node-server';import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';@@ -119,6 +120,7 @@ app.route('/', providerRoutes);app.route('/', cloudRoutes);app.route('/', transcribeRoutes);app.route('/', speakRoutes);+app.route('/', mediaRoutes);app.route('/', budgetRoutes);app.route('/', channelRoutes);app.route('/', artifactRoutes);diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdxindex 8eb7ac30..a029e437 100644--- a/website/docs/cli-commands/in-chat-commands.mdx+++ b/website/docs/cli-commands/in-chat-commands.mdx@@ -16,6 +16,19 @@ Type these during a conversation with Mercury. Most work in both CLI and Telegra| `/permissions` | Change permission mode (Ask Me / Allow All) || `/models` | List configured models/providers for this session || `/models use <provider>` | Switch the current session model/provider |+| `/image <prompt>` | Make an image with an image model; add `--landscape` or `--portrait`, or `--model provider::model`. Send a photo with it to edit that photo |+| `/media` | Show the image model in use and every image model your providers offer |+| `/media image <number\|provider::model\|auto>` | Choose the default image model, or let Mercury pick |+| `/media refresh` | Ask your providers again which image models they have |+| `/say <text>` | Say it out loud: a voice note in Telegram and WhatsApp, audio in the apps; add `--style "calm"` |+| `/media speech <number\|auto>` | Choose what speaks: OpenAI, Gemini, Deepgram, ElevenLabs, or a text-to-speech model on your providers (`auto` follows Settings → Voice) |+| `/media voice <name\|default>` | Choose the voice (OpenAI: `nova`, `coral`…; Gemini: `Kore`, `Puck`…; an ElevenLabs voice id) |+| `/media replies <off\|mirror\|always>` | When chat-app replies also come as a voice note; `mirror` (default) answers a voice note with one |+| `/video <shot>` | Make a short video (3–15 s; `--portrait`, `--seconds 6`). It runs in the background and arrives in the chat when ready |+| `/music <style>` | Make a song or instrumental (`--instrumental`, `--seconds 60`); arrives when ready (`/song` works too) |+| `/media video <number\|auto>` | Choose the video model (Gemini Omni, or a gateway's video model) |+| `/media music <number\|auto>` | Choose the music model (Gemini Lyria, ElevenLabs Music) |+| `/media jobs` | Videos and songs being made, and the last few made || `/effort` | Show the thinking effort in this chat, where it comes from (this chat or the model's default) and the levels the model takes || `/effort <level>` | Set the effort for this chat only: `auto`, `low`, `medium`, `high`, and `off`/`xhigh`/`max` where the model takes them || `/effort default` | Clear this chat's effort and use the model's default again |