Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(mcp): add provider-backed image generation

rahmanef63c5bf5a99ad49
diff --git a/.env.example b/.env.example
index c866fe36..3908bac8 100644
--- a/.env.example
+++ b/.env.example
@@ -55,6 +55,13 @@ OS_SESSION_SECRET=
# Bring your own Anthropic key. Can also be set in the OS via Settings → AI
# (stored in ~/.mso/config.json). If unset, the assistant returns 501.
# ANTHROPIC_API_KEY=
+# Official OpenAI Images API key. It may instead be saved through Settings → AI
+# under provider OpenAI; the 0600 host credential store wins over this env fallback.
+# OPENAI_API_KEY=
+# Image-generation sandbox configuration. Provider masters are always saved as
+# lossless PNG plus a provenance JSON sidecar; repository promotion is a separate step.
+# OS_IMAGE_MODEL=gpt-image-2
+# OS_IMAGE_OUTPUT_ROOT=~/generated-images
#
# Provider-run tools the Codex backend may use, comma/space separated. Default:
# `image_generation`. Set an explicit empty value to disable every built-in, or set
diff --git a/README.md b/README.md
index 1dd71277..93b89666 100644
--- a/README.md
+++ b/README.md
@@ -64,7 +64,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
**Extend** — Alfa AI, modular slices, and custom apps.
- **Use BYOK AI** — Alfa uses credentials stored on your server, not committed to the repo.
-- **Drive the box from ChatGPT, Claude.ai or Cursor** — an optional MCP server (OAuth 2.1 + PKCE) exposes files, system health and, if you grant it, a shell. Off unless you set `OS_MCP_ENABLED=1`, scoped read/write/exec per token, revocable from Settings. See [docs/MCP.md](./docs/MCP.md).
+- **Drive the box from ChatGPT, Claude.ai or Cursor** — an optional MCP server (OAuth 2.1 + PKCE) exposes files, system health, provider-backed image generation with durable provenance, and, if you grant it, a shell. Off unless you set `OS_MCP_ENABLED=1`, scoped read/write/exec per token, revocable from Settings. See [docs/MCP.md](./docs/MCP.md).
- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index e68f67a7..cd2f58a6 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,6 +4,12 @@
Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;
this is the *what*, and it is what Settings → About shows as “What's new”.
+## 2026-08-20
+
+**Added**
+
+- `mcp` add provider-backed image generation
+
## 2026-08-19
**Added**
diff --git a/docs/MCP.md b/docs/MCP.md
index 67bc9d0b..6ae11c75 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -59,14 +59,14 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe
| Scope | Tools |
|---|---|
-| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `skills_search` `screen_capture` `browser_status` |
+| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `skills_search` `image_generation_status` `screen_capture` `browser_status` |
| `write` | + `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` |
-| `exec` | + `exec_run` `browser_power` |
+| `exec` | + `image_generate` `exec_run` `browser_power` |
Alfa — the in-app assistant — has the same host capabilities under dot.case names,
and `lib/mcp/parity.test.ts` fails if one surface gains a tool the other lacks
without a written reason. `skills_search` maps to Alfa's `skills.search`.
-`screen_capture`, `workflow_start`, `workflow_cancel` and `workflow_finish` are explicitly MCP-only:
+`screen_capture`, `image_generation_status`, `image_generate`, `workflow_start`, `workflow_cancel` and `workflow_finish` are explicitly MCP-only:
the external connector needs visual proof and an actor-scoped task boundary, while
Alfa already runs inside the rendered shell and owns an in-app run boundary. The
two catalogs stay separate on purpose (different transport and guard) but may not
@@ -93,7 +93,7 @@ The catalog has a stable server version plus a schema-derived toolset signature.
Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.
-Current catalog: **22 tools**. `workflow_cancel` is the only new public name in this release.
+Current catalog: **24 tools**. `image_generation_status` and `image_generate` are the new public names in this release.
## Safe text inspection and overwrite
@@ -188,6 +188,27 @@ is limited to five downloads, sends `Cache-Control: no-store`, and is deleted af
expiry/exhaustion. This provides visual progress without turning a read token into a
general browser or public-file-hosting primitive.
+## Provider-backed image generation
+
+`image_generation_status` is read-only and reports whether an OpenAI API key is
+available without returning it. `image_generate` is exec-scope because it spends
+provider credits, sends the prompt off-box, and writes binary bytes. Each call is
+exactly one official OpenAI Images API request and produces:
+
+- a lossless PNG master under `OS_IMAGE_OUTPUT_ROOT` (default `~/generated-images`);
+- a prompt SHA-256 and byte SHA-256;
+- actual provider model and `x-request-id` as the generation run identifier;
+- width, height and alpha status parsed from the returned PNG;
+- a 0600 provenance JSON sidecar that does not contain the raw prompt;
+- a temporary authenticated preview when the image is at most 10 MiB.
+
+Configure provider OpenAI in Settings → AI or set `OPENAI_API_KEY`. A ChatGPT
+subscription/OAuth login is separate from API billing and is not silently reused.
+Transparent requests automatically use `gpt-image-1.5` unless another compatible
+model is explicitly selected; `gpt-image-2` is refused for transparent output.
+Repository candidates are never written automatically—the generated PNG remains a
+sandbox master until a project-specific validator/post-process promotes it.
+
## What this does and does not protect
Every tool goes through `lib/host`, so the MCP surface inherits the bounds that
@@ -301,7 +322,7 @@ also carries the **per-operation** limit its route already applies, on the SAME
bucket key — MCP and the browser share one allowance rather than getting one each.
`exec_run` 60/min, fs writes 120/min, fs copy/delete 60/min, `apps_power` and
`browser_power` 12/min per app. MCP-native expensive/stateful operations are
-stricter: `screen_capture` 10/min and workflow-memory writes 30/min.
+stricter: `screen_capture` 10/min, `image_generate` 5/min, and workflow-memory writes 30/min.
## Layout
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 514ec688..8c270577 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -8,6 +8,19 @@ Running log of what shipped each phase. Newest at top.
> Read those phases as history. **This file is the source of truth for what exists** —
> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.
+## 2026-08-20 — provider-backed MCP image generation (DONE)
+
+MCP now exposes `image_generation_status` (read) and `image_generate` (exec).
+Generation uses the official OpenAI Images API rather than the prior procedural
+icon scripts or the internal unofficial Codex backend. One billed call creates one
+lossless PNG sandbox master plus a prompt-free 0600 provenance sidecar containing
+provider/model/request id, prompt and byte hashes, dimensions, alpha status and
+eligibility findings. The raw prompt is excluded from activity, audit and learned
+workflow memory. The output root is write-jailed (`OS_IMAGE_OUTPUT_ROOT`, default
+`~/generated-images`), generated filenames are unique, temporary previews remain
+authenticated/expiring, and image calls are limited to 5/min. The MCP server/toolset
+advance to `1.4.0` / `2026.08.20.1`, with **24 tools**.
+
## 2026-08-20 — image generation and full-access defaults (DONE)
Fresh MSO installs now expose Codex provider-side `image_generation` when
diff --git a/lib/host/audit.ts b/lib/host/audit.ts
index ce6aaf7c..0811bad4 100644
--- a/lib/host/audit.ts
+++ b/lib/host/audit.ts
@@ -26,6 +26,7 @@ export type AuditAction =
| "sys.update"
| "managed-app.action"
| "camoufox.power"
+ | "image.generate"
| "workflow.start"
| "workflow.cancel"
| "workflow.finish"
diff --git a/lib/image-generation/openai.test.ts b/lib/image-generation/openai.test.ts
new file mode 100644
index 00000000..9510900d
--- /dev/null
+++ b/lib/image-generation/openai.test.ts
@@ -0,0 +1,137 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+const state = vi.hoisted(() => ({ key: "sk-test" }));
+vi.mock("@/lib/config/store", () => ({
+ hostCredentialStore: () => ({ getKey: async () => state.key }),
+}));
+
+const {
+ generateOpenAiImage,
+ imageGenerationStatus,
+ shouldReturnDirectImage,
+} = await import("./openai");
+
+let root = "";
+const realFetch = globalThis.fetch;
+
+function fakePng(width = 1, height = 1, colorType = 6): Buffer {
+ const out = Buffer.alloc(33);
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(out, 0);
+ out.writeUInt32BE(13, 8);
+ out.write("IHDR", 12, "ascii");
+ out.writeUInt32BE(width, 16);
+ out.writeUInt32BE(height, 20);
+ out[24] = 8;
+ out[25] = colorType;
+ return out;
+}
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-image-generation-"));
+ process.env.OS_FS_WRITE_ROOTS = root;
+ process.env.OS_IMAGE_OUTPUT_ROOT = path.join(root, "images");
+ process.env.OS_IMAGE_MODEL = "gpt-image-2";
+ state.key = "sk-test";
+});
+
+afterEach(async () => {
+ globalThis.fetch = realFetch;
+ delete process.env.OS_FS_WRITE_ROOTS;
+ delete process.env.OS_IMAGE_OUTPUT_ROOT;
+ delete process.env.OS_IMAGE_MODEL;
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+describe("OpenAI image generation bridge", () => {
+ it("reports readiness without exposing the key", async () => {
+ const status = await imageGenerationStatus();
+ expect(status).toMatchObject({ ready: true, provider: "openai", credential: "configured" });
+ expect(JSON.stringify(status)).not.toContain("sk-test");
+ });
+
+ it("persists one PNG master and prompt-free provenance with provider request id", async () => {
+ const png = fakePng();
+ let sent: Record<string, unknown> | undefined;
+ globalThis.fetch = vi.fn(async (_url, init) => {
+ sent = JSON.parse(String(init?.body));
+ return new Response(JSON.stringify({
+ created: 1_787_161_600,
+ data: [{ b64_json: png.toString("base64") }],
+ usage: { total_tokens: 123 },
+ }), { status: 200, headers: { "content-type": "application/json", "x-request-id": "req_test_123" } });
+ });
+
+ const result = await generateOpenAiImage({
+ prompt: "private studio prompt",
+ project: "antinrml-game",
+ filenameStem: "zone-house-empty",
+ size: "auto",
+ quality: "high",
+ background: "opaque",
+ });
+
+ expect(sent).toMatchObject({ model: "gpt-image-2", output_format: "png", n: 1 });
+ expect(result.summary).toMatchObject({
+ provider: "openai",
+ generationRunId: "req_test_123",
+ width: 1,
+ height: 1,
+ lossless: true,
+ candidateEligible: true,
+ });
+ expect(await fs.readFile(result.summary.masterPath)).toEqual(png);
+ const provenance = await fs.readFile(result.summary.provenancePath, "utf8");
+ expect(provenance).toContain('"promptSha256"');
+ expect(provenance).toContain('"generationRunId": "req_test_123"');
+ expect(provenance).not.toContain("private studio prompt");
+ });
+
+ it("uses gpt-image-1.5 automatically for transparent output", async () => {
+ const png = fakePng();
+ let sent: Record<string, unknown> | undefined;
+ globalThis.fetch = vi.fn(async (_url, init) => {
+ sent = JSON.parse(String(init?.body));
+ return new Response(JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }), {
+ status: 200,
+ headers: { "x-request-id": "req_transparent" },
+ });
+ });
+ await generateOpenAiImage({ prompt: "one prop", size: "auto", background: "transparent" });
+ expect(sent).toMatchObject({ model: "gpt-image-1.5", background: "transparent" });
+ });
+
+ it("refuses an explicit transparent gpt-image-2 request before spending", async () => {
+ globalThis.fetch = vi.fn();
+ await expect(generateOpenAiImage({
+ prompt: "one prop",
+ model: "gpt-image-2",
+ background: "transparent",
+ })).rejects.toThrow(/does not support transparent/);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ it("fails clearly when the OpenAI API key is absent", async () => {
+ state.key = "";
+ await expect(generateOpenAiImage({ prompt: "x" })).rejects.toThrow(/not configured/);
+ });
+
+ it("keeps an output sandbox-only when provider request id is missing", async () => {
+ const png = fakePng();
+ globalThis.fetch = vi.fn(async () => new Response(
+ JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }),
+ { status: 200 },
+ ));
+ const result = await generateOpenAiImage({ prompt: "x", size: "auto" });
+ expect(result.summary.generationRunId).toBeNull();
+ expect(result.summary.candidateEligible).toBe(false);
+ expect(result.summary.findings).toContain("provider request id missing");
+ });
+
+ it("bounds direct image responses", () => {
+ expect(shouldReturnDirectImage(1)).toBe(true);
+ expect(shouldReturnDirectImage(9 * 1024 * 1024)).toBe(false);
+ });
+});
diff --git a/lib/image-generation/openai.ts b/lib/image-generation/openai.ts
new file mode 100644
index 00000000..2c2df190
--- /dev/null
+++ b/lib/image-generation/openai.ts
@@ -0,0 +1,402 @@
+import { createHash, randomUUID } from "crypto";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+import { hostCredentialStore } from "@/lib/config/store";
+import { createTempShare, tempShareUrl } from "@/lib/host/temp-share";
+import { isUnderRoot, resolveWriteRoots, safeWritePath } from "@/lib/host/paths";
+
+const OPENAI_IMAGES_ENDPOINT = "https://api.openai.com/v1/images/generations";
+const DEFAULT_MODEL = "gpt-image-2" as const;
+const TRANSPARENT_MODEL = "gpt-image-1.5" as const;
+const DEFAULT_OUTPUT_ROOT = path.join(os.homedir(), "generated-images");
+const MAX_PROMPT_CHARS = 32_000;
+const MAX_PROVIDER_BYTES = 64 * 1024 * 1024;
+const TEMP_SHARE_MAX_BYTES = 10 * 1024 * 1024;
+const DIRECT_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
+
+export const OPENAI_IMAGE_MODELS = [
+ "gpt-image-2",
+ "gpt-image-1.5",
+ "gpt-image-1",
+ "gpt-image-1-mini",
+] as const;
+export type OpenAiImageModel = (typeof OPENAI_IMAGE_MODELS)[number];
+
+export const OPENAI_IMAGE_SIZES = ["auto", "1024x1024", "1024x1536", "1536x1024"] as const;
+export type OpenAiImageSize = (typeof OPENAI_IMAGE_SIZES)[number];
+
+export const OPENAI_IMAGE_QUALITIES = ["auto", "low", "medium", "high"] as const;
+export type OpenAiImageQuality = (typeof OPENAI_IMAGE_QUALITIES)[number];
+
+export const OPENAI_IMAGE_BACKGROUNDS = ["auto", "opaque", "transparent"] as const;
+export type OpenAiImageBackground = (typeof OPENAI_IMAGE_BACKGROUNDS)[number];
+
+export interface GenerateOpenAiImageInput {
+ prompt: string;
+ project?: string;
+ filenameStem?: string;
+ model?: OpenAiImageModel;
+ size?: OpenAiImageSize;
+ quality?: OpenAiImageQuality;
+ background?: OpenAiImageBackground;
+}
+
+export interface GeneratedImageSummary {
+ generationMethod: "image-generation";
+ provider: "openai";
+ model: OpenAiImageModel;
+ generationRunId: string | null;
+ generationRunIdKind: "provider-request-id" | null;
+ localRunId: string;
+ promptSha256: string;
+ masterPath: string;
+ provenancePath: string;
+ width: number;
+ height: number;
+ format: "png";
+ mimeType: "image/png";
+ lossless: true;
+ alphaStatus: "present" | "absent";
+ bytes: number;
+ sha256: string;
+ candidateEligible: boolean;
+ findings: string[];
+ previewUrl: string | null;
+ downloadUrl: string | null;
+ createdAt: string;
+}
+
+export interface GeneratedImageResult {
+ summary: GeneratedImageSummary;
+ data: Buffer;
+}
+
+function configuredOutputRoot(): string {
+ const raw = process.env.OS_IMAGE_OUTPUT_ROOT?.trim();
+ if (!raw) return DEFAULT_OUTPUT_ROOT;
+ if (raw === "~") return os.homedir();
+ if (raw.startsWith("~/")) return path.join(os.homedir(), raw.slice(2));
+ return path.resolve(raw);
+}
+
+function configuredModel(): OpenAiImageModel {
+ const raw = process.env.OS_IMAGE_MODEL?.trim();
+ return isOneOf(raw, OPENAI_IMAGE_MODELS) ? raw : DEFAULT_MODEL;
+}
+
+function isOneOf<T extends readonly string[]>(value: unknown, values: T): value is T[number] {
+ return typeof value === "string" && (values as readonly string[]).includes(value);
+}
+
+function assertOneOf<T extends readonly string[]>(
+ value: unknown,
+ values: T,
+ field: string,
+ fallback: T[number],
+): T[number] {
+ if (value == null || value === "") return fallback;
+ if (!isOneOf(value, values)) throw new Error(`${field} must be one of: ${values.join(", ")}`);
+ return value;
+}
+
+function cleanSegment(value: string | undefined, fallback: string, max: number): string {
+ const normalized = (value ?? fallback)
+ .normalize("NFKD")
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
+ .replace(/^[._-]+|[._-]+$/g, "")
+ .slice(0, max);
+ return normalized || fallback;
+}
+
+function sha256(data: Uint8Array | string): string {
+ return createHash("sha256").update(data).digest("hex");
+}
+
+function redactProviderError(raw: string, prompt: string): string {
+ let message = raw;
+ try {
+ const parsed = JSON.parse(raw) as { error?: { message?: string; code?: string; type?: string } };
+ message = parsed.error?.message ?? parsed.error?.code ?? parsed.error?.type ?? raw;
+ } catch {
+ // Keep the raw provider text when it was not JSON.
+ }
+ if (prompt) message = message.split(prompt).join("[prompt]");
+ return message
+ .replace(/\b(?:sk|pk)_[a-z0-9_-]{8,}\b/gi, "[redacted]")
+ .replace(/\b(?:sk-proj|sk-live)-[a-z0-9_-]{8,}\b/gi, "[redacted]")
+ .slice(0, 500);
+}
+
+function parsePngMetadata(data: Buffer): { width: number; height: number; hasAlpha: boolean } {
+ const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+ if (data.length < 33 || !data.subarray(0, 8).equals(signature)) {
+ throw new Error("OpenAI returned bytes that are not a PNG image");
+ }
+ if (data.subarray(12, 16).toString("ascii") !== "IHDR") {
+ throw new Error("OpenAI PNG is missing the IHDR header");
+ }
+ const width = data.readUInt32BE(16);
+ const height = data.readUInt32BE(20);
+ const colorType = data[25] ?? 0;
+ let hasTransparencyChunk = false;
+ let offset = 8;
+ while (offset + 12 <= data.length) {
+ const length = data.readUInt32BE(offset);
+ const type = data.subarray(offset + 4, offset + 8).toString("ascii");
+ const next = offset + 12 + length;
+ if (next > data.length) break;
+ if (type === "tRNS") hasTransparencyChunk = true;
+ if (type === "IEND") break;
+ offset = next;
+ }
+ return { width, height, hasAlpha: colorType === 4 || colorType === 6 || hasTransparencyChunk };
+}
+
+function expectedDimensions(size: OpenAiImageSize): { width: number; height: number } | null {
+ if (size === "auto") return null;
+ const [width, height] = size.split("x").map(Number);
+ return { width, height };
+}
+
+async function ensureOutputRoot(): Promise<string> {
+ const lexical = await safeWritePath(configuredOutputRoot(), false);
+ await fs.mkdir(lexical, { recursive: true, mode: 0o700 });
+ const real = await fs.realpath(lexical);
+ const roots = await resolveWriteRoots();
+ if (!roots.some((root) => isUnderRoot(real, root))) {
+ throw new Error("OS_IMAGE_OUTPUT_ROOT resolves outside writable roots");
+ }
+ await fs.chmod(real, 0o700).catch(() => undefined);
+ return real;
+}
+
+async function makeJobDirectory(root: string, project: string, day: string): Promise<string> {
+ const dir = path.join(root, project, day);
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ const real = await fs.realpath(dir);
+ if (!isUnderRoot(real, root)) throw new Error("Image output directory escaped its sandbox root");
+ await fs.chmod(real, 0o700).catch(() => undefined);
+ return real;
+}
+
+async function writeExclusive(file: string, data: Buffer | string): Promise<void> {
+ await fs.writeFile(file, data, { flag: "wx", mode: 0o600 });
+}
+
+function selectedModel(explicit: OpenAiImageModel | undefined, background: OpenAiImageBackground): OpenAiImageModel {
+ const base = explicit ?? configuredModel();
+ if (!isOneOf(base, OPENAI_IMAGE_MODELS)) throw new Error(`Unsupported OpenAI image model: ${base}`);
+ if (background === "transparent" && base === "gpt-image-2") {
+ if (explicit) throw new Error("gpt-image-2 does not support transparent backgrounds; use gpt-image-1.5 or gpt-image-1");
+ return TRANSPARENT_MODEL;
+ }
+ return base;
+}
+
+export async function imageGenerationStatus(): Promise<Record<string, unknown>> {
+ const key = await hostCredentialStore().getKey(undefined, "openai");
+ return {
+ ready: Boolean(key),
+ provider: "openai",
+ endpoint: OPENAI_IMAGES_ENDPOINT,
+ defaultModel: configuredModel(),
+ transparentModel: TRANSPARENT_MODEL,
+ outputRoot: configuredOutputRoot(),
+ outputFormat: "png",
+ losslessMaster: true,
+ supportedModels: [...OPENAI_IMAGE_MODELS],
+ supportedSizes: [...OPENAI_IMAGE_SIZES],
+ supportedQualities: [...OPENAI_IMAGE_QUALITIES],
+ supportedBackgrounds: [...OPENAI_IMAGE_BACKGROUNDS],
+ credential: key ? "configured" : "missing",
+ setup: key
+ ? "ready"
+ : "Add an OpenAI API key in MSO Settings → AI (provider OpenAI) or set OPENAI_API_KEY. ChatGPT OAuth/Plus is not an OpenAI API key.",
+ };
+}
+
+export async function generateOpenAiImage(input: GenerateOpenAiImageInput): Promise<GeneratedImageResult> {
+ const prompt = input.prompt?.trim() ?? "";
+ if (!prompt) throw new Error("prompt must be a non-empty string");
+ if (prompt.length > MAX_PROMPT_CHARS) throw new Error(`prompt exceeds ${MAX_PROMPT_CHARS} characters`);
+
+ const key = await hostCredentialStore().getKey(undefined, "openai");
+ if (!key) {
+ throw new Error(
+ "OpenAI image generation is not configured. Add an OpenAI API key in MSO Settings → AI (provider OpenAI) or set OPENAI_API_KEY. ChatGPT OAuth/Plus is separate from API billing.",
+ );
+ }
+
+ const size = assertOneOf(input.size, OPENAI_IMAGE_SIZES, "size", "1024x1024");
+ const quality = assertOneOf(input.quality, OPENAI_IMAGE_QUALITIES, "quality", "high");
+ const background = assertOneOf(input.background, OPENAI_IMAGE_BACKGROUNDS, "background", "auto");
+ const model = selectedModel(input.model, background);
+ const localRunId = randomUUID();
+ const promptSha256 = sha256(prompt);
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 300_000);
+ timeout.unref?.();
+ let response: Response;
+ try {
+ response = await fetch(OPENAI_IMAGES_ENDPOINT, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${key}`,
+ "content-type": "application/json",
+ "x-client-request-id": localRunId,
+ },
+ body: JSON.stringify({
+ model,
+ prompt,
+ n: 1,
+ size,
+ quality,
+ background,
+ output_format: "png",
+ }),
+ signal: controller.signal,
+ });
+ } catch (error) {
+ if ((error as Error).name === "AbortError") throw new Error("OpenAI image generation timed out after 300 seconds");
+ throw error;
+ } finally {
+ clearTimeout(timeout);
+ }
+
+ const raw = await response.text();
+ if (!response.ok) throw new Error(`OpenAI Images API HTTP ${response.status}: ${redactProviderError(raw, prompt)}`);
+
+ let payload: {
+ created?: number;
+ data?: Array<{ b64_json?: string }>;
+ usage?: unknown;
+ };
+ try {
+ payload = JSON.parse(raw) as typeof payload;
+ } catch {
+ throw new Error("OpenAI Images API returned invalid JSON");
+ }
+ const encoded = payload.data?.[0]?.b64_json;
+ if (!encoded) throw new Error("OpenAI Images API returned no base64 image bytes");
+ const data = Buffer.from(encoded, "base64");
+ if (!data.length || data.length > MAX_PROVIDER_BYTES) {
+ throw new Error(`OpenAI image bytes must be between 1 and ${MAX_PROVIDER_BYTES} bytes`);
+ }
+
+ const png = parsePngMetadata(data);
+ const expected = expectedDimensions(size);
+ const findings: string[] = [];
+ const requestId = response.headers.get("x-request-id") ?? response.headers.get("openai-request-id");
+ if (!requestId) findings.push("provider request id missing");
+ if (expected && (expected.width !== png.width || expected.height !== png.height)) {
+ findings.push(`provider returned ${png.width}x${png.height}, expected ${expected.width}x${expected.height}`);
+ }
+ if (background === "transparent" && !png.hasAlpha) findings.push("transparent background requested but PNG has no alpha channel");
+
+ const root = await ensureOutputRoot();
+ const project = cleanSegment(input.project, "general", 48);
+ const stem = cleanSegment(input.filenameStem, "generated-image", 64);
+ const createdAt = new Date().toISOString();
+ const day = createdAt.slice(0, 10);
+ const stamp = createdAt.replace(/[:.]/g, "-");
+ const jobDir = await makeJobDirectory(root, project, day);
+ const base = `${stamp}-${localRunId.slice(0, 8)}-${stem}`;
+ const masterPath = path.join(jobDir, `${base}.png`);
+ const provenancePath = path.join(jobDir, `${base}.provenance.json`);
+ const bytesSha256 = sha256(data);
+ const candidateEligible = findings.length === 0;
+
+ const provenance = {
+ schemaVersion: 1,
+ generationMethod: "image-generation",
+ provider: "openai",
+ model,
+ generationRunId: requestId,
+ generationRunIdKind: requestId ? "provider-request-id" : null,
+ localRunId,
+ promptSha256,
+ referenceInputs: [],
+ request: { size, quality, background, outputFormat: "png", n: 1 },
+ providerCreatedAt: payload.created ? new Date(payload.created * 1000).toISOString() : null,
+ usage: payload.usage ?? null,
+ generatedMaster: {
+ sandboxOnly: true,
+ path: masterPath,
+ width: png.width,
+ height: png.height,
+ format: "png",
+ mimeType: "image/png",
+ lossless: true,
+ alphaStatus: png.hasAlpha ? "present" : "absent",
+ bytes: data.length,
+ sha256: bytesSha256,
+ },
+ convertedFromLegacyAsset: false,
+ rasterizedFromSvg: false,
+ tracedExistingArtwork: false,
+ candidateEligible,
+ findings,
+ createdAt,
+ };
+
+ try {
+ await writeExclusive(masterPath, data);
+ await writeExclusive(provenancePath, JSON.stringify(provenance, null, 2) + "\n");
+ } catch (error) {
+ await fs.rm(masterPath, { force: true }).catch(() => undefined);
+ await fs.rm(provenancePath, { force: true }).catch(() => undefined);
+ throw error;
+ }
+
+ let previewUrl: string | null = null;
+ let downloadUrl: string | null = null;
+ if (data.length <= TEMP_SHARE_MAX_BYTES) {
+ try {
+ const share = await createTempShare({
+ data,
+ filename: path.basename(masterPath),
+ mimeType: "image/png",
+ ttlMs: 30 * 60_000,
+ maxDownloads: 5,
+ });
+ previewUrl = tempShareUrl(share.id);
+ downloadUrl = tempShareUrl(share.id, true);
+ } catch {
+ // The durable sandbox path remains the source of truth when preview creation fails.
+ }
+ }
+
+ return {
+ data,
+ summary: {
+ generationMethod: "image-generation",
+ provider: "openai",
+ model,
+ generationRunId: requestId,
+ generationRunIdKind: requestId ? "provider-request-id" : null,
+ localRunId,
+ promptSha256,
+ masterPath,
+ provenancePath,
+ width: png.width,
+ height: png.height,
+ format: "png",
+ mimeType: "image/png",
+ lossless: true,
+ alphaStatus: png.hasAlpha ? "present" : "absent",
+ bytes: data.length,
+ sha256: bytesSha256,
+ candidateEligible,
+ findings,
+ previewUrl,
+ downloadUrl,
+ createdAt,
+ },
+ };
+}
+
+export function shouldReturnDirectImage(bytes: number): boolean {
+ return bytes > 0 && bytes <= DIRECT_IMAGE_MAX_BYTES;
+}
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index edae9164..9ea51751 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -44,7 +44,7 @@ describe("protocol", () => {
it("publishes server and toolset metadata so action drift is visible", async () => {
const r = await dispatch({ id: 1, method: "initialize" }, "exec");
const result = r.result as { serverInfo: { version: string }; _meta: { toolset: { toolCount: number; hash: string } } };
- expect(result.serverInfo.version).toBe("1.3.0");
+ expect(result.serverInfo.version).toBe("1.4.0");
expect(result._meta.toolset.toolCount).toBe(TOOLS.length);
expect(result._meta.toolset.hash).toMatch(/^[a-f0-9]{16}$/);
});
@@ -77,6 +77,7 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("fs_list");
expect(n).toContain("sys_stats");
expect(n).toContain("skills_search");
+ expect(n).toContain("image_generation_status");
expect(n).not.toContain("workflow_start");
expect(n).not.toContain("fs_write");
expect(n).not.toContain("exec_run");
@@ -91,6 +92,7 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("workflow_finish");
expect(n).not.toContain("exec_run");
expect(n).not.toContain("browser_power");
+ expect(n).not.toContain("image_generate");
});
it("shows an exec token the whole catalog", async () => {
@@ -217,7 +219,7 @@ describe("catalog hygiene", () => {
});
it("the irreversible tools carry destructiveHint so clients keep prompting", () => {
- for (const name of ["fs_delete", "exec_run", "browser_power"]) {
+ for (const name of ["fs_delete", "exec_run", "browser_power", "image_generate"]) {
expect(TOOLS.find((t) => t.name === name)?.annotations?.destructiveHint, name).toBe(true);
}
});
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 0f3b248d..e60dd673 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -36,6 +36,8 @@ const ALFA_ONLY: Record<string, string> = {
const MCP_ONLY: Record<string, string> = {
"screen.capture": "external MCP clients need visual proof of the rendered OS; in-shell Alfa already runs inside that browser UI",
+ "image.generation.status": "provider readiness is exposed to external asset agents; Alfa currently has no image-generation output renderer",
+ "image.generate": "the external asset agent needs provider bytes, durable sandbox paths and provenance; Alfa currently cannot render or persist provider image output",
"workflow.start": "the external connector needs an actor-scoped task boundary; Alfa already owns an in-app conversation/run boundary",
"workflow.cancel": "same actor-scoped boundary; external runs need explicit recovery from an interrupted task",
"workflow.finish": "same actor-scoped learning loop; Alfa recipes can use the session route later without weakening MCP scope semantics",
@@ -99,6 +101,7 @@ describe("MCP rate limits mirror the routes", () => {
// MCP clients and is expensive enough to deserve a much smaller bucket.
"screen.capture": 10,
"workflow.memory": 30,
+ "image.generate": 5,
};
for (const t of TOOLS) {
if (!t.limit) continue;
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index 7e120ae3..f350d1e6 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -2,6 +2,7 @@ import { listDir, readFile, searchFs, usage, stats, processes, captureMsoScreen,
import { camoufoxStatus } from "@/lib/camoufox/service";
import { listManagedApps, getManagedAppLogs } from "@/lib/managed-apps/manager";
import { searchSkillMemory } from "@/lib/skills/search";
+import { imageGenerationStatus } from "@/lib/image-generation/openai";
import { isManagedAppId } from "@/lib/managed-apps/catalog";
import { type McpTool, str, opt, S, PATH_P, READ_ONLY, mcpDirect } from "./tool-kit";
@@ -126,6 +127,16 @@ export const READ_TOOLS: McpTool[] = [
});
},
},
+ {
+ name: "image_generation_status",
+ description:
+ "Check whether the official OpenAI Images API is configured, which model/output root will be used, and which sizes/background modes are available. " +
+ "This never generates an image, spends credits, or exposes the API key.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S({}),
+ run: () => imageGenerationStatus(),
+ },
{
name: "screen_capture",
description:
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index e9e7d78e..df1a57dc 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -3,7 +3,19 @@ import { setCamoufoxEnabled } from "@/lib/camoufox/service";
import { performManagedAppAction } from "@/lib/managed-apps/manager";
import { isManagedAppId } from "@/lib/managed-apps/catalog";
import { MANAGED_APP_ACTIONS, type ManagedAppAction } from "@/lib/managed-apps/types";
-import { type McpTool, str, opt, S, PATH_P } from "./tool-kit";
+import { type McpTool, str, opt, S, PATH_P, mcpDirect } from "./tool-kit";
+import {
+ generateOpenAiImage,
+ OPENAI_IMAGE_BACKGROUNDS,
+ OPENAI_IMAGE_MODELS,
+ OPENAI_IMAGE_QUALITIES,
+ OPENAI_IMAGE_SIZES,
+ shouldReturnDirectImage,
+ type OpenAiImageBackground,
+ type OpenAiImageModel,
+ type OpenAiImageQuality,
+ type OpenAiImageSize,
+} from "@/lib/image-generation/openai";
import { READ_TOOLS } from "./tools-read";
import { LEARNING_TOOLS } from "./tools-learning";
@@ -103,6 +115,43 @@ const MUTATE_TOOLS: McpTool[] = [
return performManagedAppAction(id, action as ManagedAppAction).then((app) => ({ app }));
},
},
+ {
+ name: "image_generate",
+ limit: { key: "image.generate", max: 5, windowMs: 60_000 },
+ audit: { action: "image.generate" as const, targetArg: "project" },
+ description:
+ "Generate exactly one genuinely new raster image through the official OpenAI Images API. " +
+ "The provider response is saved as a lossless PNG sandbox master under OS_IMAGE_OUTPUT_ROOT and accompanied by prompt SHA-256, byte SHA-256, dimensions, alpha status, provider/model/request id, and a provenance sidecar. " +
+ "This is a billed external operation and requires an OpenAI API key configured in MSO Settings → AI or OPENAI_API_KEY.",
+ scope: "exec",
+ annotations: { destructiveHint: true, openWorldHint: true },
+ inputSchema: S({
+ prompt: { type: "string", description: "Complete image-generation prompt. It is sent to OpenAI but never stored in MCP activity or workflow memory." },
+ project: { type: "string", description: "Safe project slug used only to organize the sandbox output directory. Default general." },
+ filename_stem: { type: "string", description: "Safe filename stem. A timestamp and random run id are always added." },
+ model: { type: "string", enum: [...OPENAI_IMAGE_MODELS], description: "OpenAI image model. Default OS_IMAGE_MODEL or gpt-image-2. Transparent requests default to gpt-image-1.5." },
+ size: { type: "string", enum: [...OPENAI_IMAGE_SIZES], description: "Requested output size. Default 1024x1024." },
+ quality: { type: "string", enum: [...OPENAI_IMAGE_QUALITIES], description: "Provider quality. Default high." },
+ background: { type: "string", enum: [...OPENAI_IMAGE_BACKGROUNDS], description: "auto, opaque, or transparent. gpt-image-2 does not support transparent output." },
+ }, ["prompt"]),
+ run: async (a) => {
+ const result = await generateOpenAiImage({
+ prompt: str(a, "prompt"),
+ project: opt(a, "project"),
+ filenameStem: opt(a, "filename_stem"),
+ model: opt(a, "model") as OpenAiImageModel | undefined,
+ size: opt(a, "size") as OpenAiImageSize | undefined,
+ quality: opt(a, "quality") as OpenAiImageQuality | undefined,
+ background: opt(a, "background") as OpenAiImageBackground | undefined,
+ });
+ const content: Array<{ type: "image"; data: string; mimeType: string } | { type: "text"; text: string }> = [];
+ if (shouldReturnDirectImage(result.data.byteLength)) {
+ content.push({ type: "image", data: result.data.toString("base64"), mimeType: "image/png" });
+ }
+ content.push({ type: "text", text: JSON.stringify(result.summary, null, 2) });
+ return mcpDirect(content);
+ },
+ },
{
name: "exec_run",
limit: { key: "exec", max: 60, windowMs: 60_000 },
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 6e2e0c6a..5956b5da 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -2,9 +2,9 @@ import { createHash } from "crypto";
import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
-export const MCP_SERVER_VERSION = "1.3.0";
-export const MCP_TOOLSET_VERSION = "2026.08.19.2";
-export const MCP_TOOLSET_CHANGED_AT = "2026-08-19T14:54:00.000Z";
+export const MCP_SERVER_VERSION = "1.4.0";
+export const MCP_TOOLSET_VERSION = "2026.08.20.1";
+export const MCP_TOOLSET_CHANGED_AT = "2026-08-19T20:41:23Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/skills/memory.ts b/lib/skills/memory.ts
index 6d611f9f..a6185fee 100644
--- a/lib/skills/memory.ts
+++ b/lib/skills/memory.ts
@@ -207,6 +207,7 @@ const SAFE_TOOL_ARGS: Record<string, readonly string[]> = {
fs_usage: ["path"],
apps_logs: ["id"],
screen_capture: ["shell", "width", "height"],
+ image_generate: ["project", "filename_stem", "model", "size", "quality", "background"],
fs_write: ["path"], // content is intentionally impossible to persist
fs_mkdir: ["path"],
fs_move: ["from", "to"],
@@ -245,7 +246,7 @@ function enrichBestSteps(best: WorkflowStep[], current: WorkflowStep[]): Workflo
const MAX_RECIPE_STEPS = 24;
const IMPORTANT_RECIPE_TOOLS = new Set([
"fs_write", "fs_mkdir", "fs_move", "fs_copy", "fs_delete",
- "apps_power", "browser_power", "exec_run", "screen_capture",
+ "apps_power", "browser_power", "exec_run", "screen_capture", "image_generate",
]);
/** Keep the recipe replayable without teaching the next run to repeat every