"""Provider-neutral raster generation; authentication remains in the daemon. Every call is explicit and may consume image quota. Never retry a failed or interrupted generation automatically. Files are published without replacement. """ from __future__ import annotations import asyncio import base64 import binascii import os from pathlib import Path import re import stat import tempfile from typing import cast import uuid from albedo_api import Host, PythonApi, Record from albedo_capture import image_size from albedo_plugins import hook import albedo_trace _INPUT_BYTES = 5 * 1024 * 1024 _OUTPUT_BYTES = 5 * 1024 * 1024 _OUTPUT_ENCODED = 4 * ((_OUTPUT_BYTES + 2) // 3) _MAX_EDGE = 16_384 _MAX_PIXELS = 40_000_000 _MAX_SEQUENCE = 9_223_372_036_854_775_807 _REFERENCE = re.compile(r"transcript:([1-9][0-9]{0,18}):([0-9]{1,19})\Z") def _inspect(data: bytes, maximum: int) -> tuple[str, int, int]: if len(data) > maximum: raise ValueError(f"image exceeds {maximum // (1024 * 1024)} MiB") found = image_size(data) if found is None: raise ValueError("image must be a complete PNG, JPEG, or WebP") mime, width, height = found if max(width, height) > _MAX_EDGE or width * height > _MAX_PIXELS: raise ValueError("image exceeds 16384px edge or 40 million pixels") return mime, width, height def _path(value: str | os.PathLike[str]) -> str: path = os.fspath(value) if not isinstance(path, str): raise TypeError("image paths must be text") if len(path) > 32_768 or len(path.encode("utf-8")) > 32_768: raise ValueError("image path exceeds 32768 UTF-8 bytes") return path def _reference_path(value: str | os.PathLike[str]) -> str: path = _path(value) if path.startswith("transcript:"): match = _REFERENCE.fullmatch(path) if match is None or any(int(part) > _MAX_SEQUENCE for part in match.groups()): raise ValueError("invalid transcript reference; use imagegen.references()") return path def _check_generate( prompt: str, references: list[str | os.PathLike[str]] | None, transparent_background: bool, output: str | os.PathLike[str] | None, provider: str | None, ) -> None: if provider is not None and ( not isinstance(provider, str) or not provider.strip() or len(provider.encode("utf-8")) > 128 ): raise ValueError("provider must be nonempty text of at most 128 UTF-8 bytes") if not isinstance(prompt, str): raise ValueError("prompt must be nonempty text") if len(prompt) > 32_768 or len(prompt.encode("utf-8")) > 32_768: raise ValueError("prompt exceeds 32768 UTF-8 bytes") if not prompt.strip(): raise ValueError("prompt must be nonempty text") if type(transparent_background) is not bool: raise TypeError("transparent_background must be a bool") if references is not None and not isinstance(references, list): raise TypeError("references must be a list of paths or transcript references") if references is not None and len(references) > 5: raise ValueError("at most five reference images") for value in references or []: _reference_path(value) if output is not None: _path(output) def _check_page(after: int, limit: int) -> None: if type(after) is not int or not 0 <= after <= _MAX_SEQUENCE: raise ValueError( "after must be a nonnegative signed-64-bit transcript sequence" ) if type(limit) is not int or not 1 <= limit <= 100: raise ValueError("limit must be 1..100 transcript rows") def _reference(value: str | os.PathLike[str]) -> str | dict[str, str]: path = _reference_path(value) if path.startswith("transcript:"): return path path = os.path.abspath(os.path.expanduser(path)) # O_NONBLOCK prevents a named pipe supplied as a path from hanging the kernel. descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)) with os.fdopen(descriptor, "rb") as source: info = os.fstat(source.fileno()) if not stat.S_ISREG(info.st_mode): raise ValueError("reference must be a regular image file") if info.st_size > _INPUT_BYTES: raise ValueError("reference exceeds 5 MiB") data = source.read(_INPUT_BYTES + 1) mime, _, _ = _inspect(data, _INPUT_BYTES) return {"mime_type": mime, "data": base64.b64encode(data).decode("ascii")} def _destination(output: str | os.PathLike[str] | None) -> Path: path = ( Path.cwd() / "output" / "imagegen" / f"generated-{uuid.uuid4().hex}.png" if output is None else Path(output).expanduser().absolute() ) if path.suffix.lower() != ".png": raise ValueError("output must name a .png file") if os.path.lexists(path): raise FileExistsError(f"will not overwrite {path}; choose a new output path") path.parent.mkdir(parents=True, exist_ok=True) return path class Imagegen: def __init__(self, host: Host) -> None: self._host = host @hook.reported("imagegen.providers", {}) async def providers(self) -> list[Record]: """List only the drivers active in this session's loaded extensions.""" providers = cast(list[dict], await self._host("imagegen.providers", {})) return [Record(provider) for provider in providers] async def references(self, after: int = 0, limit: int = 50) -> Record: """List explicit image references in a bounded page of this session's rows.""" _check_page(after, limit) return await self._references(after, limit) @hook.reported("imagegen.references", {"after": "after", "limit": "limit"}) async def _references(self, after: int, limit: int) -> Record: _check_page(after, limit) page = cast( dict, await self._host("imagegen.references", {"after": after, "limit": limit}), ) return Record( images=[Record(image) for image in page["images"]], next_after=page["next_after"], has_more=page["has_more"], ) async def generate( self, prompt: str, *, references: list[str | os.PathLike[str]] | None = None, transparent_background: bool = False, output: str | os.PathLike[str] | None = None, provider: str | None = None, ) -> Record: """Generate one image; references are up to five paths or transcript IDs.""" # Bound all reported arguments before hooks can send a host frame. The # implementation validates again because hooks may rewrite arguments. _check_generate(prompt, references, transparent_background, output, provider) return await self._generate( prompt, references=references, transparent_background=transparent_background, output=output, provider=provider, ) @hook.reported( "imagegen.generate", { "prompt": "prompt", "references": "references", "output": "output", "transparent_background": "transparent_background", "provider": "provider", }, ) async def _generate( self, prompt: str, *, references: list[str | os.PathLike[str]] | None = None, transparent_background: bool = False, output: str | os.PathLike[str] | None = None, provider: str | None = None, ) -> Record: """Generate or edit one image, saving it before returning its metadata. References are local files or imagegen.references() identifiers, at most five, in the order the prompt names them. Inspect with show_image(r.path). """ _check_generate(prompt, references, transparent_background, output, provider) encoded = [_reference(value) for value in references or []] # The kernel link accepts 8 MiB frames. Bound local inline input as a # group before encoding the host frame; transcript refs resolve daemon-side. inline_bytes = sum( (len(value["data"]) // 4) * 3 - (len(value["data"]) - len(value["data"].rstrip("="))) for value in encoded if isinstance(value, dict) ) if inline_bytes > _INPUT_BYTES: raise ValueError("local reference images exceed the combined 5 MiB limit") destination = _destination(output) # Probe writability before consuming quota. The temp file also retains a # successful image if final publication fails (e.g. a competing writer). descriptor, temporary = tempfile.mkstemp( prefix=".imagegen-", suffix=".png", dir=destination.parent ) retained = False data: bytes | None = None call_id = uuid.uuid4().hex try: with os.fdopen(descriptor, "wb") as target: await self._host("imagegen.begin", {"call_id": call_id}) reply = cast( dict, await albedo_trace.noted( "imagegen", prompt, self._host( "imagegen.generate", { "prompt": prompt, "references": encoded, "transparent_background": transparent_background, "call_id": call_id, "provider": provider, }, ), ), ) try: payload = reply["data"] if not isinstance(payload, str) or len(payload) > _OUTPUT_ENCODED: raise ValueError("image response exceeds 5 MiB") decoded = base64.b64decode(payload, validate=True) mime, width, height = _inspect(decoded, _OUTPUT_BYTES) if mime != "image/png" or reply.get("mime_type") != mime: raise ValueError("image service did not return PNG") data = decoded except (KeyError, TypeError, ValueError, binascii.Error) as error: raise ValueError( f"invalid image response: {error}; generation may have used quota, not retried" ) from None if target.write(data) != len(data): raise OSError("incomplete image write") target.flush() os.fsync(target.fileno()) # Same-directory hard link publishes a complete file atomically and # never replaces a destination, even if it appeared during generation. os.link(temporary, destination) os.unlink(temporary) retained = False return Record( path=str(destination), mime_type=mime, width=width, height=height, bytes=len(data), request_id=reply.get("request_id"), generation_id=reply.get("generation_id"), ) except asyncio.CancelledError: # Host workers outlive a Python cell unless explicitly cancelled. # A cancelled accepted request has an unknown outcome; never replay. try: await asyncio.wait_for( self._host("imagegen.cancel", {"call_id": call_id}), timeout=5 ) except (Exception, asyncio.CancelledError): pass # Preserve the original cancellation even if the host is gone. print( "Image generation cancelled; upstream outcome may be unknown. " "Do not automatically retry." ) raise except OSError as error: # Closing can finish a buffered write even when write/flush failed. # Compare with the validated response before retaining any output. if data is not None: try: with open(temporary, "rb") as source: retained = source.read(_OUTPUT_BYTES + 1) == data except OSError: retained = False if retained: raise OSError( f"complete generated image retained at {temporary}; could not finish saving " f"{destination}: {error}. File durability may be unconfirmed. " "Do not generate again; inspect or move the retained file instead." ) from error raise OSError( f"image could not be saved: {error}. No complete file was retained; " "generation may have used quota. Do not automatically retry." ) from error finally: if not retained: try: os.unlink(temporary) except FileNotFoundError: pass def setup(api: PythonApi) -> dict[str, object]: return {"imagegen": Imagegen(api.host), "ImagegenError": api.HostError}