The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): pet — pass 1 (dead ROWS/COLUMNS, module-level PIL imports, helper collapse, docstring compaction)
Tekniumb4c386642fd3
diff --git a/agent/pet/__init__.py b/agent/pet/__init__.pyindex b045598d2eb..66e07528f36 100644--- a/agent/pet/__init__.py+++ b/agent/pet/__init__.py@@ -1,31 +1,14 @@"""Petdex pet engine — shared core for the CLI, TUI, and desktop surfaces.Petdex (https://github.com/crafter-station/petdex) is a public gallery of-animated sprite "pets" for coding agents. Each pet is a ``pet.json`` plus a-``spritesheet.{webp,png}`` of 192×208 px cells. Current Codex/petdex sheets use-an 8-column × 9-row atlas; older Hermes/petdex sheets used an 8-row atlas.-Hermes infers the row taxonomy from the sheet and maps agent activity onto-idle/run/review/failed/wave/jump.--This package is the **single source of truth** for the feature so the base-CLI (Python) and TUI (Ink, via ``tui_gateway``) never duplicate the hard-parts:--- :mod:`agent.pet.constants` — frame geometry + the :class:`PetState` enum.-- :mod:`agent.pet.state` — map agent activity → a :class:`PetState`.-- :mod:`agent.pet.manifest` — fetch the public petdex manifest.-- :mod:`agent.pet.store` — install / list / resolve pets on disk- (profile-aware via ``get_hermes_home()``).-- :mod:`agent.pet.render` — decode a spritesheet and encode frames for a- terminal (kitty / iTerm2 / sixel graphics- protocols, with a Unicode half-block- fallback).--Rendering in the Electron desktop is necessarily TypeScript (canvas), but it-reuses the same on-disk store and the same state semantics.--The whole feature is a *display* concern: it adds no model tool, mutates no-system prompt or toolset, and therefore has zero effect on prompt caching.+animated sprite "pets": a ``pet.json`` plus a ``spritesheet.{webp,png}`` of+192×208 px cells (8-col × 9-row Codex atlas, or the older 8-row atlas). This+package is the single source of truth for the feature so the CLI (Python) and+TUI (Ink, via ``tui_gateway``) never duplicate the hard parts: ``constants``+(geometry + :class:`PetState`), ``state`` (activity → state), ``manifest``,+``store`` (on-disk pets), ``render`` (kitty / iTerm2 / sixel / half-blocks).+A pure display concern: no model tool, no prompt/toolset mutation, so zero+effect on prompt caching."""from agent.pet.constants import (diff --git a/agent/pet/constants.py b/agent/pet/constants.pyindex 5a3fafb291f..66892b96c56 100644--- a/agent/pet/constants.py+++ b/agent/pet/constants.py@@ -1,43 +1,39 @@"""Pet sprite geometry + animation-state taxonomy.-These values are the common petdex/Codex pet geometry. The real ``pet.json``-usually only carries ``id``/``displayName``/``description``/``spritesheetPath``;-row taxonomy is inferred from the atlas shape so Hermes can render both legacy-8-row sheets and current 9-row Codex sheets.+Common petdex/Codex pet geometry. ``pet.json`` usually only carries+``id``/``displayName``/``description``/``spritesheetPath``; row taxonomy is+inferred from the atlas shape so Hermes renders both legacy 8-row sheets and+current 9-row Codex sheets."""from __future__ import annotationsfrom enum import Enum-# Frame geometry (pixels). Current Codex/petdex spritesheets are 8 columns x 9-# rows (1536x1872), while older Hermes/petdex sheets used 9 columns x 8 rows-# (1728x1664). Renderers derive both row taxonomy and real column count from the-# concrete sheet, so either shape works.+# Frame geometry (pixels). Current Codex/petdex sheets are 8 columns x 9 rows+# (1536x1872); older Hermes/petdex sheets were 9 columns x 8 rows (1728x1664).+# Renderers derive row taxonomy and real column count from the concrete sheet.FRAME_W = 192FRAME_H = 208-# Frames consumed per animation state (the petdex web app uses CSS-# ``steps(6)``). A sheet may physically contain more columns; we only step-# through the first ``FRAMES_PER_STATE``.+# Frames consumed per animation state (the petdex web app uses CSS ``steps(6)``).+# A sheet may physically contain more columns; we only step through the first N.FRAMES_PER_STATE = 6# Full-loop duration for one state, milliseconds (petdex default).LOOP_MS = 1100-# Default on-screen scale relative to native frame size. ``display.pet.scale``-# is the single master scalar: the desktop canvas multiplies its native pixels-# by it and every terminal surface derives its half-block/kitty column width-# from it (see :func:`cols_for_scale`), so one number shrinks all three-# interfaces together. (petdex's own clients render at 0.7; we default smaller-# so the kitty/GUI mascot stays a glanceable corner sprite. The half-block-# fallback can't shrink as far — see ``UNICODE_MIN_COLS`` — and clamps to its-# legibility floor instead.)+# Default on-screen scale relative to native frame size. ``display.pet.scale`` is+# the single master scalar: the desktop canvas multiplies native pixels by it and+# every terminal surface derives its half-block/kitty column width from it+# (:func:`cols_for_scale`), so one number shrinks all three interfaces together.+# petdex's own clients render at 0.7; we default smaller so the mascot stays a+# glanceable corner sprite. The half-block fallback can't shrink as far and+# clamps to ``UNICODE_MIN_COLS`` instead.DEFAULT_SCALE = 0.33-# User-settable scale bounds (``/pet scale``, desktop slider). Floor keeps the-# pet clickable/visible; ceiling stops a fat-fingered value from filling the-# screen. The unicode fallback additionally clamps to ``UNICODE_MIN_COLS``.+# User-settable scale bounds (``/pet scale``, desktop slider). Floor keeps the+# pet clickable/visible; ceiling stops a fat-fingered value from filling the screen.MIN_SCALE = 0.1MAX_SCALE = 3.0@@ -46,17 +42,17 @@ def clamp_scale(scale: float) -> float:"""Clamp *scale* to ``[MIN_SCALE, MAX_SCALE]`` (the single validation point)."""return max(MIN_SCALE, min(MAX_SCALE, scale))-# Terminal cells one native frame spans at ``scale == 1.0``. A cell is ~8px-# wide, a frame is ``FRAME_W`` (192) px → 24 cells. This mirrors the kitty-# graphics placement (``scaled_px // 8``) so at full scale every renderer agrees.++# Terminal cells one native frame spans at ``scale == 1.0``: a cell is ~8px wide,+# a frame 192px → 24 cells. Mirrors the kitty placement (``scaled_px // 8``) so at+# full scale every renderer agrees.BASE_UNICODE_COLS = FRAME_W // 8-# Legibility floor for the half-block fallback. A half-block cell samples the+# Legibility floor for the half-block fallback. A half-block cell samples the# sprite at only 1 horizontal + 2 vertical taps, so below this width a 192×208-# pet collapses into an unreadable blob *regardless* of scale. kitty/GUI draw-# true pixels and have no such floor — that's why the same ``scale: 0.33`` is-# crisp there but mush in half-blocks. ``scale`` shrinks the unicode pet down-# TO this floor (and grows it above), instead of past it into noise.+# pet collapses into an unreadable blob regardless of scale (kitty/GUI draw true+# pixels and have no such floor). ``scale`` shrinks the unicode pet down TO this+# floor, not past it into noise.UNICODE_MIN_COLS = 16@@ -64,8 +60,7 @@ def cols_for_scale(scale: float) -> int:"""Half-block width implied by *scale*, clamped to the legibility floor.Above the floor it tracks the kitty cell box (``scaled_px // 8``) so the two- renderers converge at larger sizes; below it the floor keeps the sprite- readable rather than letting it devolve into a blob.+ renderers converge at larger sizes."""return max(UNICODE_MIN_COLS, round(BASE_UNICODE_COLS * (scale or DEFAULT_SCALE)))@@ -78,9 +73,9 @@ def resolve_cols(scale: float, unicode_cols: int = 0) -> int:class PetState(str, Enum):"""Animation state a pet can be shown in.- These are Hermes' activity state names. They are not always identical to the- source atlas row names: Codex-format pets use rows like ``jumping`` /- ``running`` while the UI keeps the shorter ``jump`` / ``run`` names.+ Hermes' activity state names; not always identical to the source atlas row+ names (Codex pets use ``jumping``/``running`` rows while the UI keeps the+ shorter ``jump``/``run``)."""IDLE = "idle"@@ -92,48 +87,21 @@ class PetState(str, Enum):WAITING = "waiting"-# Legacy Hermes/petdex row order (top -> bottom) used by the older 8-row,-# 9-column atlas shape.-LEGACY_STATE_ROWS: list[str] = [- PetState.IDLE.value,- PetState.WAVE.value,- PetState.RUN.value,- PetState.FAILED.value,- PetState.REVIEW.value,- PetState.JUMP.value,- "extra1",- "extra2",-]--# Current Petdex row order (top -> bottom) used by 1536x1872 atlases:-# 8 columns x 9 rows of 192x208 cells.-CODEX_STATE_ROWS: list[str] = [- PetState.IDLE.value,- "running-right",- "running-left",- "waving",- "jumping",- PetState.FAILED.value,- PetState.WAITING.value,- "running",- PetState.REVIEW.value,-]--# Default/fallback for callers without a sheet. Prefer the current 9-row Codex-# format because generated pets and the public Codex pet contract use it.+# Legacy Hermes/petdex row order (top -> bottom) for the older 8-row, 9-column atlas.+LEGACY_STATE_ROWS: list[str] = ["idle", "wave", "run", "failed", "review", "jump", "extra1", "extra2"]++# Current Petdex row order (top -> bottom) for 1536x1872 atlases (8 cols x 9 rows).+CODEX_STATE_ROWS: list[str] = ["idle", "running-right", "running-left", "waving", "jumping", "failed", "waiting", "running", "review"]++# Default/fallback for callers without a sheet: generated pets and the public+# Codex pet contract use the 9-row format.STATE_ROWS: list[str] = CODEX_STATE_ROWS# Canonical Hermes activity names -> accepted row-name aliases in descending-# preference. This keeps our internal state names stable (`wave`/`jump`/`run`)-# while matching Petdex's current `waving`/`jumping`/`running` taxonomy.+# preference, so internal names stay stable while matching Petdex's taxonomy.+_CODEX_NAMES = {"wave": "waving", "jump": "jumping", "run": "running"}STATE_ALIASES: dict[str, tuple[str, ...]] = {- PetState.IDLE.value: (PetState.IDLE.value,),- PetState.WAVE.value: (PetState.WAVE.value, "waving"),- PetState.JUMP.value: (PetState.JUMP.value, "jumping"),- PetState.RUN.value: (PetState.RUN.value, "running"),- PetState.FAILED.value: (PetState.FAILED.value,),- PetState.REVIEW.value: (PetState.REVIEW.value,),- PetState.WAITING.value: (PetState.WAITING.value,),+ s.value: (s.value, _CODEX_NAMES[s.value]) if s.value in _CODEX_NAMES else (s.value,) for s in PetState}@@ -155,9 +123,4 @@ def state_rows_for_grid(row_count: int | None) -> list[str]:def state_row_index(state: "PetState | str", row_count: int | None = None) -> int:"""Return the spritesheet row index for *state* (clamped, never raises)."""rows = state_rows_for_grid(row_count)- for name in state_aliases_for(state):- try:- return rows.index(name)- except ValueError:- continue- return 0 # fall back to the idle row+ return next((rows.index(name) for name in state_aliases_for(state) if name in rows), 0) # 0 = idle rowdiff --git a/agent/pet/generate/__init__.py b/agent/pet/generate/__init__.pyindex b75a03cd985..b20f6afb5f1 100644--- a/agent/pet/generate/__init__.py+++ b/agent/pet/generate/__init__.py@@ -1,29 +1,14 @@"""Pet generation — base-draft → hatch pipeline.-Public surface used by the gateway RPCs, the CLI ``hermes pets generate``-command, and tests:--- :func:`generate_base_drafts` / :func:`hatch_pet` — the two-step flow.-- :class:`HatchResult`, :class:`GenerationError`.-- :mod:`atlas` — deterministic frame extraction + atlas composition/validation.--Image generation is delegated to the active reference-capable-:class:`~agent.image_gen_provider.ImageGenProvider` (OpenAI gpt-image-2 or Krea);-atlas assembly is fully deterministic so it's testable without any API calls.+Public surface for the gateway RPCs, ``hermes pets generate``, and tests:+:func:`generate_base_drafts` / :func:`hatch_pet`, :class:`HatchResult`,+:class:`GenerationError`, and :mod:`atlas` (deterministic frame extraction ++atlas composition/validation, testable without any API calls)."""from __future__ import annotationsfrom agent.pet.generate.imagegen import GenerationError-from agent.pet.generate.orchestrate import (- HatchResult,- generate_base_drafts,- hatch_pet,-)+from agent.pet.generate.orchestrate import HatchResult, generate_base_drafts, hatch_pet-__all__ = [- "GenerationError",- "HatchResult",- "generate_base_drafts",- "hatch_pet",-]+__all__ = ["GenerationError", "HatchResult", "generate_base_drafts", "hatch_pet"]diff --git a/agent/pet/generate/atlas.py b/agent/pet/generate/atlas.pyindex 7049bd6cd09..d1de0e0889c 100644--- a/agent/pet/generate/atlas.py+++ b/agent/pet/generate/atlas.py@@ -1,22 +1,22 @@"""Deterministic spritesheet assembly — generated row strips → Hermes atlas.Image models draw a row of poses well but can't do exact grid geometry, so the-model never owns the layout: it emits one loose horizontal strip per state and-these ops slice it into centered transparent ``192x208`` cells packed into the-petdex/Codex atlas (8 columns x 9 rows, ``1536x1872``) that-:mod:`agent.pet.render` reads via :data:`agent.pet.constants.CODEX_STATE_ROWS`.-``running`` is the in-place *working* state; ``running-right``/``-left`` are the-directional walk cycles. Segmentation/fit/residue logic is adapted from-OpenAI's ``hatch-pet`` skill (openai/skills, Apache-2.0).+model never owns the layout: it emits one loose strip per state and these ops+slice it into centered transparent 192x208 cells packed into the petdex/Codex+atlas (8 cols x 9 rows, 1536x1872; see ``constants.CODEX_STATE_ROWS``).+Segmentation/fit/residue logic adapted from OpenAI's ``hatch-pet`` skill (Apache-2.0)."""from __future__ import annotationsimport loggingimport math-from collections import deque+from collections import Counter, deque+from itertools import groupbyfrom pathlib import Path+from PIL import Image, ImageChops, ImageFilter+from agent.pet.constants import FRAME_H, FRAME_Wlogger = logging.getLogger(__name__)@@ -27,32 +27,25 @@ CELL_HEIGHT = FRAME_H# (state, row index, frame count). Order/row indices MUST match# ``constants.CODEX_STATE_ROWS``; frame counts mirror the petdex ``hatch-pet``# spec. Rows shorter than 8 leave their tail transparent (renderer trims it).+# ``running`` is the in-place *working* state; ``running-right``/``-left`` walk.ROW_SPECS: list[tuple[str, int, int]] = [- ("idle", 0, 6),- ("running-right", 1, 8),- ("running-left", 2, 8),- ("waving", 3, 4),- ("jumping", 4, 5),- ("failed", 5, 8),- ("waiting", 6, 6),- ("running", 7, 6),- ("review", 8, 6),+ ("idle", 0, 6), ("running-right", 1, 8), ("running-left", 2, 8), ("waving", 3, 4), ("jumping", 4, 5),+ ("failed", 5, 8), ("waiting", 6, 6), ("running", 7, 6), ("review", 8, 6),]-ROWS = len(ROW_SPECS)-COLUMNS = max(count for _, _, count in ROW_SPECS)-ATLAS_WIDTH = COLUMNS * CELL_WIDTH-ATLAS_HEIGHT = ROWS * CELL_HEIGHT+ATLAS_WIDTH = max(count for _, _, count in ROW_SPECS) * CELL_WIDTH+ATLAS_HEIGHT = len(ROW_SPECS) * CELL_HEIGHT_ALPHA_FLOOR = 16 # alpha at/below which a pixel is "background"_CELL_PAD = 10 # padding kept around a fitted sprite-# Small margin for the normalized pass so cells fill like real petdex pets-# (~5px from the edges); the width clamp, not the pad, prevents clipping.+# Normalized cells fill like real petdex pets (~5px from the edges); the width+# clamp, not the pad, prevents clipping._NORMALIZE_PAD = 14-# Side-lobe cutoff: adjacent-pose bleed shows as a small separated lobe; keep-# sizeable lobes so a legitimate wide pose isn't punished.+# Adjacent-pose bleed shows as a small separated lobe; keep sizeable lobes so a+# legitimate wide pose isn't punished._SIDE_LOBE_RATIO = 0.18_NEIGHBOURS = ((1, 0), (-1, 0), (0, 1), (0, -1))+_NEAREST = Image.Resampling.NEAREST # interpolating resamples blur hard pixel-art edgesdef _median(values) -> int:@@ -61,8 +54,6 @@ def _median(values) -> int:def _blank(size=(CELL_WIDTH, CELL_HEIGHT)):- from PIL import Image-return Image.new("RGBA", size, (0, 0, 0, 0))@@ -80,24 +71,12 @@ def _clear_region(image, box: tuple[int, int, int, int]) -> None:def _load_rgba(image):"""Open a path (or take an image) as RGBA."""- from PIL import Image-if isinstance(image, (str, Path)):with Image.open(image) as opened:return opened.convert("RGBA")return image.convert("RGBA")-def _border_coords(w: int, h: int):- """Every border pixel: top/bottom rows column-wise, then left/right columns."""- for x in range(w):- for y in (0, h - 1):- yield x, y- for y in range(h):- for x in (0, w - 1):- yield x, y--def _flood(w: int, h: int, visited: bytearray, seeds, accept) -> list[tuple[int, int]]:"""4-connected BFS from *seeds* over pixels passing *accept*; returns the visited pixels."""queue = deque(seeds)@@ -107,19 +86,18 @@ def _flood(w: int, h: int, visited: bytearray, seeds, accept) -> list[tuple[int,pixels.append((x, y))for dx, dy in _NEIGHBOURS:nx, ny = x + dx, y + dy- if 0 <= nx < w and 0 <= ny < h:- idx = ny * w + nx- if not visited[idx]:- visited[idx] = 1- if accept(nx, ny):- queue.append((nx, ny))+ if 0 <= nx < w and 0 <= ny < h and not visited[ny * w + nx]:+ visited[ny * w + nx] = 1+ if accept(nx, ny):+ queue.append((nx, ny))return pixelsdef _border_flood(w: int, h: int, visited: bytearray, accept) -> list[tuple[int, int]]:"""Flood from every border pixel passing *accept* (edge-connected region only)."""+ border = [(x, y) for x in range(w) for y in (0, h - 1)] + [(x, y) for y in range(h) for x in (0, w - 1)]seeds: list[tuple[int, int]] = []- for x, y in _border_coords(w, h):+ for x, y in border:if not visited[y * w + x] and accept(x, y):visited[y * w + x] = 1seeds.append((x, y))@@ -137,28 +115,18 @@ def _unvisited_components(w: int, h: int, visited: bytearray, accept):yield _flood(w, h, visited, [(x, y)], accept)-# ───────────────────────── background removal ─────────────────────────--def _has_transparency(image) -> bool:- """True if the strip already carries a real alpha background."""- if image.getchannel("A").getextrema()[0] > _ALPHA_FLOOR:- return False- transparent = sum(image.getchannel("A").histogram()[: _ALPHA_FLOOR + 1])- return transparent > image.width * image.height * 0.05+ """True if the strip already carries a real alpha background (>5% of pixels at/below the floor)."""+ alpha = image.getchannel("A")+ return alpha.getextrema()[0] <= _ALPHA_FLOOR and sum(alpha.histogram()[: _ALPHA_FLOOR + 1]) > image.width * image.height * 0.05def _dominant_corner_color(image) -> tuple[int, int, int]:"""Most common opaque color among the four corners."""- from collections import Counter-w, h = image.width, image.heightpx = image.load()- counter: Counter = Counter()- for x, y in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)):- r, g, b, a = px[x, y]- if a > _ALPHA_FLOOR:- counter[(r, g, b)] += 1+ corners = [px[x, y] for x, y in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1))]+ counter = Counter(tuple(c[:3]) for c in corners if c[3] > _ALPHA_FLOOR)return counter.most_common(1)[0][0] if counter else (0, 255, 0)@@ -168,17 +136,8 @@ def _near_key_mask(image, key: tuple[int, int, int], tol: int = 48):Tight on purpose: marks only near-pure backdrop so trapped chroma pocketsseed the flood while chroma-tinted character pixels stay outside it."""- from PIL import ImageChops-- r, g, b, _a = image.split()- kr, kg, kb = key- return ImageChops.darker(- ImageChops.darker(- r.point(lambda v: 255 if abs(v - kr) <= tol else 0),- g.point(lambda v: 255 if abs(v - kg) <= tol else 0),- ),- b.point(lambda v: 255 if abs(v - kb) <= tol else 0),- )+ r, g, b = (ch.point(lambda v, k=k: 255 if abs(v - k) <= tol else 0) for ch, k in zip(image.split()[:3], key))+ return ImageChops.darker(ImageChops.darker(r, g), b)def _remove_masked(rgba, mask):@@ -187,8 +146,6 @@ def _remove_masked(rgba, mask):The erosion drops the antialiased key/sprite blend ring (too far from the key tomatch); the sprite's own thick outline keeps the silhouette intact."""- from PIL import Image, ImageFilter-out = Image.composite(_blank(rgba.size), rgba, mask)out.putalpha(out.getchannel("A").filter(ImageFilter.MinFilter(3)))return out@@ -198,33 +155,29 @@ def remove_background(image, *, chroma_key: tuple[int, int, int] | None = None,"""Return *image* (RGBA) with its flat background keyed out to transparent.Already-transparent strips are left alone (holes repaired). Otherwise key out- *chroma_key* (or the dominant corner color) via a border flood-fill: a global+ *chroma_key* (or the dominant corner color) from the border inward: a globalcolor match punched holes wherever an interior highlight matched the backdrop."""- from PIL import Image, ImageChops-rgba = image.convert("RGBA")if _has_transparency(rgba):return _repair_internal_alpha_holes(rgba)-key = chroma_key or _dominant_corner_color(rgba)- w, h = rgba.width, rgba.height- px = rgba.load()-- def _is_bg(x: int, y: int) -> bool:- r, g, b, a = px[x, y]- return a > _ALPHA_FLOOR and math.sqrt((r - key[0]) ** 2 + (g - key[1]) ** 2 + (b - key[2]) ** 2) <= threshold-# Fast path for saturated chroma keys (our prompts use hot magenta): C-level# channel ops clear border backdrop and enclosed pockets alike, no Python flood.if max(key) - min(key) >= 120:opaque = rgba.getchannel("A").point(lambda a: 255 if a > _ALPHA_FLOOR else 0)return _remove_masked(rgba, ImageChops.darker(_near_key_mask(rgba, key), opaque))+ w, h = rgba.size+ px = rgba.load()++ def _is_bg(x: int, y: int) -> bool:+ r, g, b, a = px[x, y]+ return a > _ALPHA_FLOOR and math.sqrt((r - key[0]) ** 2 + (g - key[1]) ** 2 + (b - key[2]) ** 2) <= threshold+# Border-only flood on purpose: a desaturated near-white/gray key must never- # seed from the character's interior (that is the hole-punching case).- # Mark removals in a flat mask and composite once in C — per-pixel writes- # were ~3M PixelAccess calls and stalled the gateway.+ # seed from the character's interior (that is the hole-punching case). Mark+ # removals in a flat mask and composite once in C — per-pixel writes stalled the gateway.remove = bytearray(w * h)for x, y in _border_flood(w, h, bytearray(w * h), _is_bg):remove[y * w + x] = 1@@ -235,8 +188,7 @@ def _repair_internal_alpha_holes(image):"""Fill transparent islands fully enclosed by opaque sprite pixels.Some providers return "transparent" PNGs with swiss-cheese alpha inside the- character. Edge-connected transparent components stay background; enclosed- ones are filled with the average color of their opaque neighbours.+ character; enclosed holes get the average color of their opaque neighbours."""rgba = image.convert("RGBA")w, h = rgba.size@@ -247,108 +199,68 @@ def _repair_internal_alpha_holes(image):return px[x, y][3] <= _ALPHA_FLOOR_border_flood(w, h, visited, _is_transparent) # edge-connected transparency = background-- def _fill_color(hole: list[tuple[int, int]]) -> tuple[int, int, int, int]:- samples: list[tuple[int, int, int]] = []- seen = set(hole)- for x, y in hole:- for dx, dy in _NEIGHBOURS:- nx, ny = x + dx, y + dy- if 0 <= nx < w and 0 <= ny < h and (nx, ny) not in seen:- r, g, b, a = px[nx, ny]- if a > _ALPHA_FLOOR:- samples.append((r, g, b))- if not samples:- return (0, 0, 0, 255)- r, g, b = (round(sum(c[i] for c in samples) / len(samples)) for i in range(3))- return (r, g, b, 255)-for hole in _unvisited_components(w, h, visited, _is_transparent):- color = _fill_color(hole)+ seen = set(hole)+ samples = [+ px[nx, ny][:3]+ for x, y in hole+ for dx, dy in _NEIGHBOURS+ if 0 <= (nx := x + dx) < w and 0 <= (ny := y + dy) < h and (nx, ny) not in seen and px[nx, ny][3] > _ALPHA_FLOOR+ ]+ color = (*(round(sum(c[i] for c in samples) / len(samples)) for i in range(3)), 255) if samples else (0, 0, 0, 255)for hx, hy in hole:px[hx, hy] = colorreturn rgba-# ───────────────────────── frame extraction ─────────────────────────--def _fit_to_cell(image):"""Crop to content, scale to fit a padded cell, and center on transparent."""- from PIL import Image-image = _drop_side_bleed(image)- bbox = image.getbbox()- if bbox is None:+ if (bbox := image.getbbox()) is None:return _blank()-sprite = image.crop(bbox)scale = min((CELL_WIDTH - _CELL_PAD) / sprite.width, (CELL_HEIGHT - _CELL_PAD) / sprite.height, 1.0)if scale != 1.0:- # NEAREST: interpolating resamples blur the hard pixel-art edges.- sprite = sprite.resize(- (max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale))),- Image.Resampling.NEAREST,- )+ sprite = sprite.resize((max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale))), _NEAREST)return _place(sprite, (CELL_WIDTH, CELL_HEIGHT), ((CELL_WIDTH - sprite.width) // 2, (CELL_HEIGHT - sprite.height) // 2))def _drop_side_bleed(image):"""Remove tiny separated left/right lobes (neighbour-pose slivers) before fitting.- Component extraction may already have grouped a near sliver with the subject;- a horizontal alpha projection still reveals it as a low-mass side lobe. Only- those are dropped so wide poses and real limbs survive.+ Component extraction may have grouped a near sliver with the subject; the+ column profile still shows it as a low-mass lobe. Only those go, so wide poses survive."""rgba = image.convert("RGBA")w, h = rgba.sizeruns = _content_runs(_column_profile(rgba))- if len(runs) < 2:- return rgba- keep_mass = max(m for _run, m in runs) * _SIDE_LOBE_RATIO- keep = [run for run, m in runs if m >= keep_mass]- if len(keep) == len(runs):+ keep = [run for run, m in runs if m >= max(m for _run, m in runs) * _SIDE_LOBE_RATIO] if runs else []+ if len(runs) < 2 or len(keep) == len(runs):return rgba-rgba = rgba.copy()prev = 0- for left, right in keep:+ for left, right in [*keep, (w, w)]: # (w, w) sentinel clears the trailing gapif left > prev:_clear_region(rgba, (prev, 0, left, h))prev = right- if prev < w:- _clear_region(rgba, (prev, 0, w, h))return rgba-def _erase_long_axis_lines(image):- """Remove thin slot-spanning guide/floor/divider lines.+def _thin_groups(indices: list[int]) -> list[tuple[int, int]]:+ """``(start, end)`` for each run of consecutive *indices* at most 4 long."""+ runs = ([i for _, i in g] for _k, g in groupby(enumerate(indices), key=lambda p: p[1] - p[0]))+ return [(run[0], run[-1] + 1) for run in runs if len(run) <= 4]- Models sometimes draw literal floors or panel dividers; they survive keying- and connect otherwise clean poses. Only *thin* near-full-span rows/columns go.- """++def _erase_long_axis_lines(image):+ """Remove thin slot-spanning guide/floor/divider lines (they survive keying and bridge clean poses)."""rgba = image.convert("RGBA").copy()w, h = rgba.sizealpha = rgba.getchannel("A")-- def _thin_groups(indices: list[int]) -> list[tuple[int, int]]:- groups: list[tuple[int, int]] = []- start = prev = -2- for idx in [*indices, -2]: # -2 sentinel flushes the last run- if start >= 0 and idx == prev + 1:- prev = idx- continue- if start >= 0 and prev - start + 1 <= 4:- groups.append((start, prev + 1))- start = prev = idx- return groups-- wide_rows = [y for y in range(h) if sum(1 for x in range(w) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= w * 0.85]- tall_cols = [x for x in range(w) if sum(1 for y in range(h) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= h * 0.85]-- for top, bottom in _thin_groups(wide_rows):+ opaque = [[alpha.getpixel((x, y)) > _ALPHA_FLOOR for x in range(w)] for y in range(h)]+ for top, bottom in _thin_groups([y for y in range(h) if sum(opaque[y]) >= w * 0.85]):_clear_region(rgba, (0, top, w, bottom))- for left, right in _thin_groups(tall_cols):+ for left, right in _thin_groups([x for x in range(w) if sum(row[x] for row in opaque) >= h * 0.85]):_clear_region(rgba, (left, 0, right, h))return rgba@@ -356,20 +268,15 @@ def _erase_long_axis_lines(image):def _component_boxes(image) -> list[tuple[tuple[int, int, int, int], int]]:"""Connected opaque components as ``[(bbox, mass)]``."""rgba = image.convert("RGBA")- bbox = rgba.getbbox()- if bbox is None:+ if (bbox := rgba.getbbox()) is None:return []l0, t0, r0, b0 = bboxw, h = r0 - l0, b0 - t0alpha = rgba.getchannel("A").load()+ components = _unvisited_components(w, h, bytearray(w * h), lambda x, y: alpha[l0 + x, t0 + y] > _ALPHA_FLOOR)out: list[tuple[tuple[int, int, int, int], int]] = []-- def _opaque(x: int, y: int) -> bool:- return alpha[l0 + x, t0 + y] > _ALPHA_FLOOR-- for pixels in _unvisited_components(w, h, bytearray(w * h), _opaque):- xs = [x for x, _ in pixels]- ys = [y for _, y in pixels]+ for pixels in components:+ xs, ys = zip(*pixels)out.append(((l0 + min(xs), t0 + min(ys), l0 + max(xs) + 1, t0 + max(ys) + 1), len(pixels)))return out@@ -380,26 +287,21 @@ def _isolate_slot_subject(image):comps = _component_boxes(rgba)if not comps:return rgba-main_box, main_mass = max(comps, key=lambda item: item[1])- ml, mt, mr, mb = main_box+ ml, _mt, mr, _mb = main_boxmw = max(1, mr - ml)- keep: list[tuple[int, int, int, int]] = []- for box, mass in comps:- if box == main_box:- keep.append(box)- continue++ def _keep(box, mass) -> bool:+ # Keep attached-looking accessories (halos); drop sparkles/tears/noise.left, _top, right, _bottom = boxoverlap = max(0, min(right, mr) - max(left, ml))- center_x = (left + right) / 2- near_main = (ml - mw * 0.25) <= center_x <= (mr + mw * 0.25)- # Keep attached-looking accessories (halos); drop sparkles/tears/noise.- if mass >= max(24, main_mass * 0.035) and (overlap >= mw * 0.3 or near_main):- keep.append(box)+ near_main = (ml - mw * 0.25) <= (left + right) / 2 <= (mr + mw * 0.25)+ return box == main_box or (mass >= max(24, main_mass * 0.035) and (overlap >= mw * 0.3 or near_main))out = _blank(rgba.size)- for box in keep:- out.alpha_composite(rgba.crop(box), (box[0], box[1]))+ for box, mass in comps:+ if _keep(box, mass):+ out.alpha_composite(rgba.crop(box), (box[0], box[1]))return out@@ -407,8 +309,7 @@ def _has_margin(size: tuple[int, int], box: tuple[int, int, int, int], fx: float"""True when *box* leaves empty room on all four edges of an image of *size* (≥4px, ≤12/16px)."""w, h = sizeleft, top, right, bottom = box- min_x = max(4, min(12, round(w * fx)))- min_y = max(4, min(16, round(h * fy)))+ min_x, min_y = max(4, min(12, round(w * fx))), max(4, min(16, round(h * fy)))return left >= min_x and top >= min_y and w - right >= min_x and h - bottom >= min_y@@ -416,19 +317,18 @@ def _group_component_rows(boxes: list[tuple[int, int, int, int]]) -> list[list[t"""Group component boxes into visual rows, then sort left→right."""if not boxes:return []+ cy = lambda b: (b[1] + b[3]) / 2 # noqa: E731row_tol = max(12, _median(max(1, b[3] - b[1]) for b in boxes) * 0.55)rows: list[list[tuple[int, int, int, int]]] = []centers: list[float] = []- for box in sorted(boxes, key=lambda b: (b[1] + b[3]) / 2):- cy = (box[1] + box[3]) / 2- for i, center in enumerate(centers):- if abs(cy - center) <= row_tol:- rows[i].append(box)- centers[i] = sum((b[1] + b[3]) / 2 for b in rows[i]) / len(rows[i])- break- else:+ for box in sorted(boxes, key=cy):+ i = next((i for i, center in enumerate(centers) if abs(cy(box) - center) <= row_tol), None)+ if i is None:rows.append([box])- centers.append(cy)+ centers.append(cy(box))+ else:+ rows[i].append(box)+ centers[i] = sum(cy(b) for b in rows[i]) / len(rows[i])ordered = [row for _center, row in sorted(zip(centers, rows, strict=False), key=lambda item: item[0])]for row in ordered:row.sort(key=lambda b: (b[0] + b[2]) / 2)@@ -456,10 +356,8 @@ def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[iif used[j]:continuebl, bt, br, bb = boxes[j]- v_overlap = max(0, min(ab, bb) - max(at, bt))- min_h = max(1, min(ab - at, bb - bt))- gap = max(0, max(al, bl) - min(ar, br))- min_w = max(1, min(ar - al, br - bl))+ v_overlap, min_h = max(0, min(ab, bb) - max(at, bt)), max(1, min(ab - at, bb - bt))+ gap, min_w = max(0, max(al, bl) - min(ar, br)), max(1, min(ar - al, br - bl))if v_overlap >= min_h * 0.45 and gap <= max(14, min_w * 0.22):al, at, ar, ab = min(al, bl), min(at, bt), max(ar, br), max(ab, bb)used[j] = True@@ -470,72 +368,40 @@ def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[idef _component_crops(strip, frame_count: int, *, require_padding: bool = False) -> list | None:- """Extract frame subjects as connected non-background objects.-- Robust path for models that emit a 2D grid instead of one row: count real- subject components, discard tiny effects, sort in reading order, return- exactly *frame_count* frames (or ``None`` when the contract can't be met).- """+ """Frames as connected subjects in reading order (robust to 2D grids); ``None`` when *frame_count* can't be met."""def attempt(source) -> list | None:subjects = _significant_subject_boxes(source, min_mass=64)if len(subjects) < frame_count:return None-rows = _group_component_rows(subjects)- ordered = [box for row in rows for box in row][:frame_count]- if len(ordered) < frame_count:- return None-+ ordered = [box for row in rows for box in row][:frame_count] # rows hold every subject, so exactly frame_countif require_padding and not all(_has_margin(source.size, box, 0.01, 0.015) for box in ordered):return None-multirow = len(rows) > 1frames = []for left, top, right, bottom in ordered:- pad_x = max(8, round((right - left) * 0.08))- pad_y = max(8, round((bottom - top) * 0.08))- if multirow:- crop_box = (- max(0, left - pad_x),- max(0, top - pad_y),- min(source.width, right + pad_x),- min(source.height, bottom + pad_y),- )- elif frame_count == 1:- crop_box = (0, 0, source.width, source.height)- else:- # Keep full height for true one-row strips so vertical motion survives.- crop_box = (max(0, left - pad_x), 0, min(source.width, right + pad_x), source.height)+ pad_x, pad_y = max(8, round((right - left) * 0.08)), max(8, round((bottom - top) * 0.08))+ # One-row strips keep full height so vertical motion survives; grids pad the box.+ cl, cr = (0, source.width) if frame_count == 1 else (max(0, left - pad_x), min(source.width, right + pad_x))+ ct, cb = (max(0, top - pad_y), min(source.height, bottom + pad_y)) if multirow else (0, source.height)# No second component filter here: capes/tails can be legitimate# disconnected lobes inside the chosen subject box.- frames.append(- _place(- source.crop((left, top, right, bottom)),- (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]),- (left - crop_box[0], top - crop_box[1]),- )- )+ frames.append(_place(source.crop((left, top, right, bottom)), (cr - cl, cb - ct), (left - cl, top - ct)))return framesreturn attempt(strip) or attempt(_erase_long_axis_lines(strip))def _sever_expected_gutters(strip, frame_count: int):- """Cut narrow transparent bands at expected frame boundaries before labeling.-- Shared shadows/smears/1px bridges connect neighbouring poses into one blob;- losing a few boundary pixels beats exporting merged frames.- """+ """Cut narrow transparent bands at expected frame boundaries (shared shadows/1px bridges merge poses)."""if frame_count <= 1:return strip-out = strip.copy()alpha = out.getchannel("A") # zero alpha only; RGB is left untouchedslot = out.width / frame_counthalf = max(3, min(18, round(slot * 0.06)))- for i in range(1, frame_count):- x = round(i * slot)+ for x in (round(i * slot) for i in range(1, frame_count)):alpha.paste(0, (max(0, x - half), 0, min(out.width, x + half + 1), out.height))out.putalpha(alpha)return out@@ -546,19 +412,11 @@ def _clean_slot(image):def _slot_crops(strip, frame_count: int, *, require_padding: bool = False) -> list | None:- """Slice *strip* into *frame_count* uniform, independently cleaned columns.-- Equal-width columns keep every frame in one shared coordinate frame so- :func:`normalize_cells` preserves the row's real motion without sliding.- """+ """Slice *strip* into *frame_count* equal, independently cleaned columns (one shared coordinate frame)."""w, h = strip.size- frames = []- for i in range(frame_count):- slot = _clean_slot(strip.crop((round(i * w / frame_count), 0, round((i + 1) * w / frame_count), h)))- bbox = slot.getbbox()- if require_padding and (bbox is None or not _has_margin(slot.size, bbox, 0.025, 0.02)):- return None- frames.append(slot)+ frames = [_clean_slot(strip.crop((round(i * w / frame_count), 0, round((i + 1) * w / frame_count), h))) for i in range(frame_count)]+ if require_padding and any((b := f.getbbox()) is None or not _has_margin(f.size, b, 0.025, 0.02) for f in frames):+ return Nonereturn frames@@ -579,20 +437,13 @@ def _content_runs(profile: list[int], *, threshold: int = 2) -> list[tuple[tupledef _frame_x_ranges(strip, frame_count: int) -> list[tuple[int, int]] | None:"""Per-frame ``(left, right)`` column ranges from the row's empty gutters.- spans == frames → one per frame; spans > frames → merge across the smallest- gaps (a detached halo sits a tiny gap from its body, the inter-pose gutter is- the big gap that survives); spans < frames → ``None`` (poses touching).- Ranges span X only; the caller crops full height so tall ears/halos survive.+ Extra spans merge across the smallest gaps (a detached halo sits closer to its+ body than to the next pose); fewer spans than frames → ``None`` (poses touching)."""runs = _content_runs(_column_profile(strip))- if not runs:- return None-- floor = max(m for _run, m in runs) * 0.02- groups = [[l, r] for (l, r), m in runs if m >= floor]+ groups = [[l, r] for (l, r), m in runs if m >= max(m for _run, m in runs) * 0.02] if runs else []if len(groups) < frame_count:return None-while len(groups) > frame_count:gi = min(range(len(groups) - 1), key=lambda i: groups[i + 1][0] - groups[i][1])groups[gi][1] = groups[gi + 1][1]@@ -615,26 +466,18 @@ def _is_multi_pose_outlier(width: int, height: int, med_w: int, med_h: int) -> bdef _validate_extracted_frames(frames: list, frame_count: int) -> None:- """Reject rows where one "frame" is really multiple poses.-- A collapsed strip of tiny repeated poses would make normalization shrink the- whole pet to postage-stamp size; catching it here lets hatch regenerate.- """+ """Reject rows where one "frame" is really multiple poses (normalization would shrink the whole pet)."""if len(frames) != frame_count:raise ValueError(f"expected {frame_count} frames, got {len(frames)}")-boxes = []for i, frame in enumerate(frames):- bbox = frame.getbbox()- if bbox is None:+ if (bbox := frame.getbbox()) is None:raise ValueError(f"frame {i} is empty")if len(_significant_subject_boxes(frame)) >= 3:raise ValueError(f"frame {i} contains multiple separated subjects")boxes.append(bbox)-if frame_count <= 1:return-med_w = max(1, _median(b[2] - b[0] for b in boxes))med_h = max(1, _median(b[3] - b[1] for b in boxes))for i, (left, top, right, bottom) in enumerate(boxes):@@ -643,211 +486,140 @@ def _validate_extracted_frames(frames: list, frame_count: int) -> None:def extract_strip_frames(- strip,- frame_count: int,- *,- chroma_key: tuple[int, int, int] | None = None,- method: str = "auto",- fit: bool = True,+ strip, frame_count: int, *, chroma_key: tuple[int, int, int] | None = None, method: str = "auto", fit: bool = True) -> list:"""Turn one generated row strip into *frame_count* frames.- Keys out the background, then treats the frame count as source of truth:- isolate padded subjects (component pass, then equal slots). When that fails,- ``components`` raises and ``auto`` falls back to lenient salvage (gutters →- severed gutters → raw slots). *fit* centers each frame into a 192x208 cell;- hatching passes ``fit=False`` so :func:`normalize_cells` can register the- whole pet with one shared scale + baseline.+ Keys out the background, then isolates padded subjects (components, then equal+ slots). When that fails ``components`` raises while ``auto`` salvages leniently.+ *fit* centers each frame into a cell; hatching passes ``fit=False`` so+ :func:`normalize_cells` can register the whole pet with one shared scale."""strip = remove_background(_load_rgba(strip), chroma_key=chroma_key)-- frames = _component_crops(strip, frame_count, require_padding=True)+ frames = _component_crops(strip, frame_count, require_padding=True) or _slot_crops(strip, frame_count, require_padding=True)+ if frames is None and method == "components":+ raise ValueError(f"could not segment {frame_count} padded sprites from strip")if frames is None:- frames = _slot_crops(strip, frame_count, require_padding=True)- if frames is None:- if method == "components":- raise ValueError(f"could not segment {frame_count} padded sprites from strip")frames = _component_crops(strip, frame_count, require_padding=False)if frames is None:- source = strip- ranges = _frame_x_ranges(source, frame_count)- if ranges is None:- source = _sever_expected_gutters(strip, frame_count)- ranges = _frame_x_ranges(source, frame_count)-- if ranges is None:- frames = _slot_crops(source, frame_count, require_padding=False) or []- else:- h = source.height- pad = max(2, min(16, round((source.width / max(1, frame_count)) * 0.04)))- frames = [- _clean_slot(source.crop((max(0, left - pad), 0, min(source.width, right + pad), h)))- for left, right in ranges- ]+ frames = _salvage_frames(strip, frame_count)_validate_extracted_frames(frames, frame_count)return [_fit_to_cell(f) for f in frames] if fit else frames+def _salvage_frames(strip, frame_count: int) -> list:+ """Lenient last resort: gutter ranges (severing expected gutters if needed), else raw slots."""+ source = strip+ ranges = _frame_x_ranges(source, frame_count)+ if ranges is None:+ source = _sever_expected_gutters(strip, frame_count)+ ranges = _frame_x_ranges(source, frame_count)+ if ranges is None:+ return _slot_crops(source, frame_count, require_padding=False) or []+ w, h = source.size+ pad = max(2, min(16, round((w / max(1, frame_count)) * 0.04)))+ return [_clean_slot(source.crop((max(0, left - pad), 0, min(w, right + pad), h))) for left, right in ranges]++def _column_profile(image) -> list[int]:"""Per-column alpha mass — collapse to a 1px-tall strip (fast in C)."""- from PIL import Image-return list(image.getchannel("A").resize((image.width, 1), Image.BILINEAR).getdata())def _best_shift(ref: list[int], prof: list[int], window: int) -> int:- """Integer dx that best aligns *prof* onto *ref* (1-D cross-correlation).-- The body dominates the column profile, so the peak locks onto the body and a- flipping arm/cape barely moves the match (~9px drift → ~1px).- """+ """Integer dx that best aligns *prof* onto *ref* (1-D cross-correlation; the body dominates, limbs barely move it)."""n = len(ref)def score(d: int) -> int:return sum(ref[x] * prof[x - d] for x in range(max(0, d), min(n, n + d)))- return max(range(-window, window + 1), key=score) # ties → smallest dx, as before+ return max(range(-window, window + 1), key=score) # ties → smallest dxdef normalize_cells(frames_by_state: dict[str, list], *, pad: int = _NORMALIZE_PAD) -> dict[str, list]:"""Register every frame into a 192x208 cell — the deterministic anti-jitter math.- Per-frame crop→scale→center jitters (bbox shifts with a limb, per-frame scale- pulses). Instead: cross-correlate each frame's column profile against the- state's median profile to lock the body, union-crop through one shared state- window, then scale every state by a single global factor keyed to its median- pose height so the character is the same size in every row.+ Per-frame crop→scale→center jitters. Instead: align each frame's column profile+ to the state's median (locks the body), union-crop through one shared window,+ then scale all states by one global factor keyed to median pose height."""- from PIL import Image-out: dict[str, list] = {}- prepared: dict[str, tuple[list, tuple[int, int, int, int], tuple[int, int]]] = {}- target_w = CELL_WIDTH - pad- target_h = CELL_HEIGHT - pad-+ prepared: dict[str, tuple[list, tuple[int, int, int, int], int]] = {}+ target_w, target_h = CELL_WIDTH - pad, CELL_HEIGHT - padfor state, frames in frames_by_state.items():rgba = [f.convert("RGBA") for f in frames]if not any(f.getbbox() for f in rgba):out[state] = [_blank() for _ in frames]continue-# Pad every frame to a common canvas so column profiles are comparable.- w0 = max(f.width for f in rgba)- h0 = max(f.height for f in rgba)+ w0, h0 = max(f.width for f in rgba), max(f.height for f in rgba)canvas = [f if f.size == (w0, h0) else _place(f, (w0, h0)) for f in rgba]-profiles = [_column_profile(f) for f in canvas]ref = [_median(p[x] for p in profiles) for x in range(w0)]window = max(8, w0 // 5)- margin = windowaligned = [- _place(f, (w0 + 2 * margin, h0), (margin + _best_shift(ref, prof, window), 0))- for f, prof in zip(canvas, profiles)+ _place(f, (w0 + 2 * window, h0), (window + _best_shift(ref, prof, window), 0)) for f, prof in zip(canvas, profiles)]-boxes = [b for b in (a.getbbox() for a in aligned) if b]- prepared[state] = (- aligned,- (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)),- (_median(b[2] - b[0] for b in boxes), _median(b[3] - b[1] for b in boxes)),- )-+ union = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))+ prepared[state] = (aligned, union, _median(b[3] - b[1] for b in boxes))if not prepared:return out# K is the one global cap keeping the tallest/widest motion envelope (a# jump's lift) inside the cell; a still row's union ≈ pose so it fills fully.K = target_h- for _aligned, (left, top, right, bottom), (_pose_w, pose_h) in prepared.values():- uw, uh = right - left, bottom - top- K = min(K, target_h * pose_h / max(1, uh), target_w * pose_h / max(1, uw))-- for state, (aligned, (left, top, right, bottom), (_pose_w, pose_h)) in prepared.items():- uw, uh = right - left, bottom - top+ for _aligned, (left, top, right, bottom), pose_h in prepared.values():+ K = min(K, target_h * pose_h / max(1, bottom - top), target_w * pose_h / max(1, right - left))+ for state, (aligned, box, pose_h) in prepared.items():scale = K / max(1, pose_h)- sw, sh = max(1, round(uw * scale)), max(1, round(uh * scale))- px, py = round((CELL_WIDTH - sw) / 2), round((CELL_HEIGHT - pad // 2) - sh)-- cells = []- for a in aligned:- crop = a.crop((left, top, right, bottom))- if crop.size != (sw, sh):- crop = crop.resize((sw, sh), Image.Resampling.NEAREST) # keep pixel edges crisp- cells.append(_place(crop, (CELL_WIDTH, CELL_HEIGHT), (px, py)))- out[state] = cells+ sw, sh = max(1, round((box[2] - box[0]) * scale)), max(1, round((box[3] - box[1]) * scale))+ offset = round((CELL_WIDTH - sw) / 2), round((CELL_HEIGHT - pad // 2) - sh)+ crops = [a.crop(box) for a in aligned]+ out[state] = [_place(c if c.size == (sw, sh) else c.resize((sw, sh), _NEAREST), (CELL_WIDTH, CELL_HEIGHT), offset) for c in crops]return out-# ───────────────────────── atlas composition ─────────────────────────--def single_frame(image, *, fit: bool = True):- """One frame from a standalone image (idle fallback so a pet always renders).-- *fit* yields a finished cell; ``fit=False`` the raw keyed sprite for- :func:`normalize_cells`.- """+ """One frame from a standalone image (idle fallback); ``fit=False`` yields the raw keyed sprite for :func:`normalize_cells`."""keyed = remove_background(_load_rgba(image))return _fit_to_cell(keyed) if fit else _drop_side_bleed(keyed)def _clear_transparent_rgb(image):"""Zero the RGB of fully-transparent pixels (no colored-halo residue)."""- from PIL import Image-rgba = image.convert("RGBA")data = bytearray(rgba.tobytes())- for i in range(0, len(data), 4):- if data[i + 3] == 0:- data[i] = data[i + 1] = data[i + 2] = 0+ for i in range(3, len(data), 4):+ if data[i] == 0:+ data[i - 3 : i] = b"\0\0\0"return Image.frombytes("RGBA", rgba.size, bytes(data))def mirror_frames(frames: list) -> list:- """Flip each frame horizontally (per-frame, so order/timing is preserved).-- Derives ``running-left`` from ``running-right``; NOT a strip reverse.- """- from PIL import Image-- flip = getattr(Image, "Transpose", Image).FLIP_LEFT_RIGHT- return [frame.convert("RGBA").transpose(flip) for frame in frames]+ """Flip each frame horizontally (``running-left`` from ``running-right``; per-frame, NOT a strip reverse)."""+ return [frame.convert("RGBA").transpose(Image.Transpose.FLIP_LEFT_RIGHT) for frame in frames]def compose_atlas(frames_by_state: dict[str, list]):"""Pack per-state frame lists into the atlas; short states leave trailing cells transparent."""atlas = _blank((ATLAS_WIDTH, ATLAS_HEIGHT))for state, row, count in ROW_SPECS:- frames = frames_by_state.get(state) or []- for col, frame in enumerate(frames[:count]):+ for col, frame in enumerate((frames_by_state.get(state) or [])[:count]):cell = frame.convert("RGBA")- if cell.size != (CELL_WIDTH, CELL_HEIGHT):- cell = _fit_to_cell(cell)+ cell = cell if cell.size == (CELL_WIDTH, CELL_HEIGHT) else _fit_to_cell(cell)atlas.alpha_composite(cell, (col * CELL_WIDTH, row * CELL_HEIGHT))return _clear_transparent_rgb(atlas)def validate_atlas(atlas) -> dict:- """Check geometry, per-cell occupancy, and transparency invariants.-- Returns ``{ok, width, height, errors, warnings, filled_states}``; errors are- blockers, warnings soft (a whole state row blank).- """+ """Geometry/occupancy/transparency checks → ``{ok, width, height, errors, warnings, filled_states}``."""atlas = _load_rgba(atlas)- if atlas.size != (ATLAS_WIDTH, ATLAS_HEIGHT):- errors: list[str] = [f"expected {ATLAS_WIDTH}x{ATLAS_HEIGHT}, got {atlas.width}x{atlas.height}"]- warnings: list[str] = []- filled_states: list[str] = []+ if atlas.size == (ATLAS_WIDTH, ATLAS_HEIGHT):+ errors, warnings, filled = _check_atlas_cells(atlas)else:- errors, warnings, filled_states = _check_atlas_cells(atlas)- return {- "ok": not errors,- "width": atlas.width,- "height": atlas.height,- "errors": errors,- "warnings": warnings,- "filled_states": filled_states,- }+ errors, warnings, filled = [f"expected {ATLAS_WIDTH}x{ATLAS_HEIGHT}, got {atlas.width}x{atlas.height}"], [], []+ return {"ok": not errors, "width": atlas.width, "height": atlas.height, "errors": errors, "warnings": warnings, "filled_states": filled}def _check_atlas_cells(atlas) -> tuple[list[str], list[str], list[str]]:@@ -857,53 +629,36 @@ def _check_atlas_cells(atlas) -> tuple[list[str], list[str], list[str]]:filled_states: list[str] = []cell_boxes_by_state: dict[str, list[tuple[int, int, int, int]]] = {}for state, row, count in ROW_SPECS:- row_pixels = 0- boxes: list[tuple[int, int, int, int]] = []- for col in range(count):- left, top = col * CELL_WIDTH, row * CELL_HEIGHT- cell = atlas.crop((left, top, left + CELL_WIDTH, top + CELL_HEIGHT))- row_pixels += sum(cell.getchannel("A").histogram()[1:])- bbox = cell.getbbox()- if bbox is not None:- boxes.append(bbox)- if row_pixels > 0:+ cells = [atlas.crop((c * CELL_WIDTH, row * CELL_HEIGHT, (c + 1) * CELL_WIDTH, (row + 1) * CELL_HEIGHT)) for c in range(count)]+ if any(sum(cell.getchannel("A").histogram()[1:]) for cell in cells):filled_states.append(state)- cell_boxes_by_state[state] = boxes+ cell_boxes_by_state[state] = [bbox for cell in cells if (bbox := cell.getbbox()) is not None]else:warnings.append(f"state '{state}' has no frames")if not filled_states:errors.append("atlas is empty — no state produced any frames")-# A valid pet must occupy the cell: one bad row can poison global# normalization and shrink every state while still passing "non-empty".all_boxes = [b for boxes in cell_boxes_by_state.values() for b in boxes]- global_med_w = global_med_h = 0- if all_boxes:- global_med_w = _median(r - l for l, _t, r, _b in all_boxes)- global_med_h = _median(b - t for _l, t, _r, b in all_boxes)- if global_med_h < max(56, round(CELL_HEIGHT * 0.28)):- errors.append(f"atlas sprites are too small after normalization (median frame height {global_med_h}px)")-+ global_med_w = _median(r - l for l, _t, r, _b in all_boxes) if all_boxes else 0+ global_med_h = _median(b - t for _l, t, _r, b in all_boxes) if all_boxes else 0+ if all_boxes and global_med_h < max(56, round(CELL_HEIGHT * 0.28)):+ errors.append(f"atlas sprites are too small after normalization (median frame height {global_med_h}px)")for state, boxes in cell_boxes_by_state.items():if len(boxes) <= 1:continue- widths = [right - left for left, _top, right, _bottom in boxes]- heights = [bottom - top for _left, top, _right, bottom in boxes]+ widths, heights = [r - l for l, _t, r, _b in boxes], [b - t for _l, t, _r, b in boxes]med_w, med_h = max(1, _median(widths)), max(1, _median(heights))if _is_multi_pose_outlier(max(widths), max(heights), med_w, med_h):errors.append(f"state '{state}' contains a multi-pose frame outlier")# Per-state collapse guard: one malformed row must not pass on the# strength of the healthy ones.- if (global_med_w and global_med_h) and (- med_w < max(32, round(global_med_w * 0.42)) or med_h < max(40, round(global_med_h * 0.50))- ):- errors.append(- f"state '{state}' appears collapsed (median {med_w}x{med_h}px, global median {global_med_w}x{global_med_h}px)"- )-+ collapsed = med_w < max(32, round(global_med_w * 0.42)) or med_h < max(40, round(global_med_h * 0.50))+ if (global_med_w and global_med_h) and collapsed:+ errors.append(f"state '{state}' appears collapsed (median {med_w}x{med_h}px, global median {global_med_w}x{global_med_h}px)")data = atlas.tobytes()- residue = sum(1 for i in range(0, len(data), 4) if data[i + 3] == 0 and (data[i] or data[i + 1] or data[i + 2]))+ residue = sum(1 for i in range(3, len(data), 4) if data[i] == 0 and any(data[i - 3 : i]))if residue:errors.append(f"{residue} transparent pixels retain RGB residue")return errors, warnings, filled_statesdiff --git a/agent/pet/generate/imagegen.py b/agent/pet/generate/imagegen.pyindex 65c4630e8ea..9aff9ada362 100644--- a/agent/pet/generate/imagegen.py+++ b/agent/pet/generate/imagegen.py@@ -3,12 +3,9 @@Wraps the active :class:`~agent.image_gen_provider.ImageGenProvider` with thetwo things sprite generation needs that the agent-facing ``image_generate`` tooldoesn't expose: **N variants** (loop) and **reference-image grounding** (so each-animation row stays the same character as the chosen base).--Reference grounding only works on providers that support it — currently OpenAI-``gpt-image-2`` (image edits) and Krea (style references). We resolve to one of-those and surface a clear, actionable error otherwise rather than silently-producing an ungrounded, drifting pet.+animation row stays the same character as the chosen base). Grounding only+works on reference-capable providers; we resolve to one of those and surface an+actionable error otherwise rather than silently producing a drifting pet."""from __future__ import annotations@@ -26,8 +23,7 @@ logger = logging.getLogger(__name__)# so fidelity can vary by configured backend + model availability._REF_CAPABLE = ("nous", "openai", "openai-codex", "openrouter", "krea")-# Friendly display label per reference-capable provider, surfaced in the desktop-# pet-gen picker.+# Friendly display label per reference-capable provider (desktop pet-gen picker)._PROVIDER_LABELS: dict[str, str] = {"nous": "Nous Portal","openrouter": "OpenRouter",@@ -70,44 +66,31 @@ def _available(name: str):def resolve_provider(*, require_references: bool = True, prefer: str | None = None) -> SpriteProvider:"""Pick the image provider to use for sprite work.- Preference: an explicit *prefer* choice (the desktop pet-gen picker) when it's- reference-capable and configured, then the configured/active provider when- it's reference-capable, else the first available reference-capable provider.- With *require_references* off we fall back to any available provider (used for- prompt-only base drafts).+ Preference: ``HERMES_PET_IMAGE_PROVIDER`` (QA override, unknown values ignored),+ then an explicit *prefer* choice (the desktop picker) when reference-capable and+ configured, then the configured/active provider when reference-capable, else the+ first available reference-capable provider. With *require_references* off we+ fall back to any available provider (used for prompt-only base drafts)."""_discover()from agent.image_gen_registry import get_active_provider- # QA override: ``HERMES_PET_IMAGE_PROVIDER=<name>`` forces one ref-capable backend- # for pet-gen only (unknown values ignored). Then an explicit user pick (desktop- # picker) wins when ref-capable and configured; otherwise fall through.forced = os.environ.get("HERMES_PET_IMAGE_PROVIDER", "").strip().lower()for name in (forced, prefer):if name in _REF_CAPABLE and (chosen := _available(name)) is not None:return SpriteProvider(name=name, provider=chosen, supports_references=True)-- # Configured / active provider first.try:active = get_active_provider()except Exception: # noqa: BLE001active = None- if active is not None:- name = getattr(active, "name", "")- if name in _REF_CAPABLE and active.is_available():- return SpriteProvider(name=name, provider=active, supports_references=True)-- # Any available reference-capable provider.+ active_name = getattr(active, "name", "") if active is not None else ""+ if active_name in _REF_CAPABLE and active.is_available():+ return SpriteProvider(name=active_name, provider=active, supports_references=True)for name in _REF_CAPABLE:- provider = _available(name)- if provider is not None:+ if (provider := _available(name)) is not None:return SpriteProvider(name=name, provider=provider, supports_references=True)-if not require_references and active is not None and active.is_available():- return SpriteProvider(- name=getattr(active, "name", "unknown"), provider=active, supports_references=False- )-+ return SpriteProvider(name=getattr(active, "name", "unknown"), provider=active, supports_references=False)raise GenerationError("Pet generation needs an image backend that supports reference images. ""Open `hermes tools` → Image Generation and configure Nous Portal, "@@ -116,13 +99,10 @@ def resolve_provider(*, require_references: bool = True, prefer: str | None = Nodef list_sprite_providers() -> list[dict]:- """The reference-capable providers available to pick for pet generation.+ """``[{name, label, default}]`` for every configured ref-capable provider, in preference order.- Returns ``[{name, label, default}]`` for every ref-capable provider the user- actually has credentials for, in preference order, marking the one- :func:`resolve_provider` would choose with no explicit preference. Empty when- none is configured (the picker hides itself). Best-effort: discovery hiccups- yield an empty list.+ ``default`` marks the one :func:`resolve_provider` would choose with no explicit+ preference. Empty when none is configured (the picker hides itself)."""_discover()try:@@ -148,10 +128,9 @@ def _save_local(image_ref: str, *, prefix: str) -> Path:def _rejected_background(error: str) -> bool:"""True when a provider error is specifically about the ``background`` param.- Transparent backgrounds are a per-model capability (e.g. some gpt-image tiers- reject ``background=transparent`` outright). We detect that one rejection so- we can retry without the flag rather than failing the whole pet — our chroma- key pass makes the result transparent regardless.+ Transparent backgrounds are a per-model capability (some gpt-image tiers reject+ ``background=transparent`` outright); we retry without the flag instead of+ failing the pet — the chroma-key pass makes the result transparent regardless."""lowered = (error or "").lower()return "background" in lowered and ("not supported" in lowered or "transparent" in lowered)@@ -169,13 +148,12 @@ def generate("""Generate *n* sprite images and return their local paths.*reference_images* grounds the output on a base image (required for rows).- *aspect_ratio* picks the canvas: ``"square"`` for single-character base- drafts, ``"landscape"`` for multi-frame row strips (the wider 1536px canvas- gives every frame real horizontal room so winged poses don't have to be- shrunk to avoid touching their neighbors).- We *ask* for a transparent background, but fall back to an opaque generation- (cleaned up downstream by the chroma-key pass) on models that reject the- flag. Raises :class:`GenerationError` if nothing usable comes back.+ *aspect_ratio*: ``"square"`` for single-character base drafts, ``"landscape"``+ for multi-frame row strips (the wider 1536px canvas gives every frame real+ horizontal room so winged poses don't have to shrink to avoid touching).+ We *ask* for a transparent background but fall back to an opaque generation+ on models that reject the flag. Raises :class:`GenerationError` if nothing+ usable comes back."""sprite = provider or resolve_provider(require_references=bool(reference_images))if reference_images and not sprite.supports_references:@@ -186,23 +164,22 @@ def generate(refs = [str(p) for p in (reference_images or [])]+ # Providers disagree on the ref kwarg name: our OpenRouter/Nous backends read+ # ``reference_images``, OpenAI's gpt-image-2 reads ``reference_image_urls``.+ # Send both; each ignores the other.+ ref_kwargs = {"reference_images": refs, "reference_image_urls": refs} if refs else {}+def _run(extra: dict) -> tuple[Path | None, str]:- kwargs: dict = {"aspect_ratio": aspect_ratio, **extra}- if refs:- # Providers disagree on the ref kwarg name: our OpenRouter/Nous- # backends read ``reference_images``, OpenAI's gpt-image-2 reads- # ``reference_image_urls``. Send both; each ignores the other.- kwargs["reference_images"] = refs- kwargs["reference_image_urls"] = refstry:- result = sprite.provider.generate(prompt, **kwargs)+ result = sprite.provider.generate(prompt, aspect_ratio=aspect_ratio, **extra, **ref_kwargs)except Exception as exc: # noqa: BLE001 - normalize provider crasheslogger.debug("provider.generate crashed: %s", exc)return None, str(exc)- if not isinstance(result, dict) or not result.get("success"):- return None, (result or {}).get("error", "unknown error") if isinstance(result, dict) else "no result"- image_ref = result.get("image")- if not image_ref:+ if not isinstance(result, dict):+ return None, "no result"+ if not result.get("success"):+ return None, result.get("error", "unknown error")+ if not (image_ref := result.get("image")):return None, "provider returned no image"try:return _save_local(str(image_ref), prefix=prefix), ""diff --git a/agent/pet/generate/orchestrate.py b/agent/pet/generate/orchestrate.pyindex 344cb9b8978..31603099232 100644--- a/agent/pet/generate/orchestrate.py+++ b/agent/pet/generate/orchestrate.py@@ -11,8 +11,10 @@ once, on the pet you keep) and gives each UI a natural preview/loading point.from __future__ import annotations+import contextlibimport loggingimport time+from collections import Counterfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclassfrom pathlib import Path@@ -63,10 +65,8 @@ class HatchResult:def _unlink_quietly(path: Path) -> None:- try:+ with contextlib.suppress(OSError):path.unlink(missing_ok=True)- except OSError:- passdef _harden_transparency(path: Path) -> Path:@@ -160,9 +160,8 @@ def generate_base_drafts(results: dict[int, Path] = {}errors: list[str] = []- for index, path, err in _run_parallel(- _one, range(n), cancelled=cancelled, on_cancel_log="pet generate: cancelled — dropping remaining drafts"- ):+ cancel_log = "pet generate: cancelled — dropping remaining drafts"+ for index, path, err in _run_parallel(_one, range(n), cancelled=cancelled, on_cancel_log=cancel_log):if path is None:if err:errors.append(err)@@ -179,8 +178,6 @@ def generate_base_drafts(# Surface *why*: the most common failure reason is the representative cause.if not errors:raise GenerationError("image generation produced no usable drafts")- from collections import Counter-raise GenerationError(_humanize_image_error(Counter(errors).most_common(1)[0][0]))return drafts@@ -188,10 +185,53 @@ def generate_base_drafts(def _humanize_image_error(error: str) -> str:"""Turn a raw provider error into a friendly, actionable sentence."""low = error.lower()- for needles, message in _IMAGE_ERROR_HINTS:- if any(s in low for s in needles):- return message- return error.splitlines()[0].strip()[:200] # first line, sans provider envelope+ hint = next((message for needles, message in _IMAGE_ERROR_HINTS if any(s in low for s in needles)), None)+ return hint or error.splitlines()[0].strip()[:200] # first line, sans provider envelope+++def _generate_row(spec: tuple[str, int, int], *, base: Path, label: str, style: str, slug: str, sprite, cancelled) -> tuple[str, list | None]:+ """Generate + slice one animation row, retrying up to ``_ROW_GEN_ATTEMPTS`` times.++ Self-healing: a roll whose poses touch (no gutters) slices badly, so+ ``components`` (raises on touching poses) drives regeneration and only the+ final attempt uses lenient ``auto`` slicing. Returns ``(state, None)`` when+ cancelled or every attempt failed.+ """+ state, _row, count = spec+ if cancelled():+ return state, None+ t0 = time.monotonic()+ last_exc: Exception | None = None+ for attempt in range(_ROW_GEN_ATTEMPTS):+ if cancelled():+ return state, None+ strict = attempt < _ROW_GEN_ATTEMPTS - 1+ strips: list[Path] = []+ try:+ strips = imagegen.generate(+ prompts.build_row_prompt(state, count, label, style=style),+ n=1,+ reference_images=[base],+ provider=sprite,+ prefix=f"pet_row_{state}",+ # Wider canvas: each frame gets real horizontal room and clean gutters.+ aspect_ratio="landscape",+ )+ # fit=False keeps raw columns so normalize_cells registers the whole pet at once.+ method = "components" if strict else "auto"+ frames = atlas.extract_strip_frames(strips[0], count, method=method, fit=False)+ logger.info("pet hatch %r: row %r ready in %.1fs (attempt %d)", slug, state, time.monotonic() - t0, attempt + 1)+ return state, frames+ except Exception as exc: # noqa: BLE001 - retried; one bad row is tolerated+ last_exc = exc+ logger.warning("pet hatch %r: row %r attempt %d/%d failed: %s", slug, state, attempt + 1, _ROW_GEN_ATTEMPTS, exc)+ finally:+ # Strips are intermediates already decoded into memory; nothing+ # prunes cache/images outside the gateway loop, so drop them now.+ for strip in strips:+ _unlink_quietly(Path(strip))+ logger.warning("pet hatch %r: row %r gave up after %.1fs: %s", slug, state, time.monotonic() - t0, last_exc)+ return state, Nonedef hatch_pet(@@ -227,63 +267,13 @@ def hatch_pet(logger.info("pet hatch %r: generating %d animation rows", slug, total_rows)def _gen_row(spec: tuple[str, int, int]) -> tuple[str, list | None]:- state, _row, count = spec- if cancelled():- return state, None- t0 = time.monotonic()- last_exc: Exception | None = None- # Self-healing: a roll whose poses touch (no gutters) slices badly, so- # ``components`` (raises on touching poses) drives regeneration and only- # the final attempt uses lenient ``auto`` slicing.- for attempt in range(_ROW_GEN_ATTEMPTS):- if cancelled():- return state, None- strict = attempt < _ROW_GEN_ATTEMPTS - 1- strips: list[Path] = []- try:- strips = imagegen.generate(- prompts.build_row_prompt(state, count, label, style=style),- n=1,- reference_images=[base],- provider=sprite,- prefix=f"pet_row_{state}",- # Wider canvas: each frame gets real horizontal room and clean gutters.- aspect_ratio="landscape",- )- # fit=False keeps raw columns so normalize_cells registers the whole pet at once.- method = "components" if strict else "auto"- frames = atlas.extract_strip_frames(strips[0], count, method=method, fit=False)- logger.info(- "pet hatch %r: row %r ready in %.1fs (attempt %d)",- slug, state, time.monotonic() - t0, attempt + 1,- )- return state, frames- except Exception as exc: # noqa: BLE001 - retried; one bad row is tolerated- last_exc = exc- logger.warning(- "pet hatch %r: row %r attempt %d/%d failed: %s",- slug, state, attempt + 1, _ROW_GEN_ATTEMPTS, exc,- )- finally:- # Strips are intermediates already decoded into memory; nothing- # prunes cache/images outside the gateway loop, so drop them now.- for strip in strips:- _unlink_quietly(Path(strip))- logger.warning(- "pet hatch %r: row %r gave up after %.1fs: %s",- slug, state, time.monotonic() - t0, last_exc,- )- return state, None+ return _generate_row(spec, base=base, label=label, style=style, slug=slug, sprite=sprite, cancelled=cancelled)# running-left is mirrored from running-right (consistent, one fewer generation).generated_specs = [spec for spec in atlas.ROW_SPECS if spec[0] != "running-left"]+ cancel_log = f"pet hatch {slug!r}: cancelled — dropping remaining rows"done = 0- for state, frames in _run_parallel(- _gen_row,- generated_specs,- cancelled=cancelled,- on_cancel_log=f"pet hatch {slug!r}: cancelled — dropping remaining rows",- ):+ for state, frames in _run_parallel(_gen_row, generated_specs, cancelled=cancelled, on_cancel_log=cancel_log):done += 1progress("row", f"{state}:{done}:{total_rows}")if frames:@@ -319,24 +309,11 @@ def hatch_pet(if missing_required:raise GenerationError(f"missing required animation row(s): {', '.join(missing_required)}")if len(filled_states) < _MIN_FILLED_STATES:- raise GenerationError(- f"only {len(filled_states)}/{len(atlas.ROW_SPECS)} animation rows were usable; regenerate"- )+ raise GenerationError(f"only {len(filled_states)}/{len(atlas.ROW_SPECS)} animation rows were usable; regenerate")from agent.pet import storeprogress("save", slug)logger.info("pet hatch %r: saving pet", slug)- pet = store.register_local_pet(- sheet,- slug=slug,- display_name=display_name or slug,- description=description,- )- return HatchResult(- slug=pet.slug,- display_name=pet.display_name,- spritesheet=pet.spritesheet,- states=validation["filled_states"],- validation=validation,- )+ pet = store.register_local_pet(sheet, slug=slug, display_name=display_name or slug, description=description)+ return HatchResult(pet.slug, pet.display_name, pet.spritesheet, validation["filled_states"], validation)diff --git a/agent/pet/generate/prompts.py b/agent/pet/generate/prompts.pyindex 085f8a05fc6..d1f35b3c49a 100644--- a/agent/pet/generate/prompts.py+++ b/agent/pet/generate/prompts.py@@ -2,22 +2,17 @@Two prompt shapes: a *base* prompt (prompt-only, produces the canonical look theuser picks between) and per-*state* *row* prompts (grounded on the chosen base,-produce one horizontal strip of N poses). Prompts stay concise and-sprite-production oriented; the identity lock and "one transparent row" framing-matter more than flowery description.--We generate the full petdex/Codex nine-state set (see-:data:`agent.pet.generate.atlas.ROW_SPECS`) so a hatched pet is a valid-``petdex submit`` spritesheet.+produce one horizontal strip of N poses). The identity lock and "one transparent+row" framing matter more than flowery description. We generate the full+petdex/Codex nine-state set (:data:`agent.pet.generate.atlas.ROW_SPECS`) so a+hatched pet is a valid ``petdex submit`` spritesheet."""from __future__ import annotations-# What each petdex/Codex state should depict (kept short — these go straight into-# the row prompt). Phrased to avoid the common sprite-gen failure modes (detached-# effects, motion lines, shadows). Critical distinction: ``running`` is the-# *working* state (in place), while ``running-right`` / ``running-left`` are the-# actual directional walk/run cycles.+# What each petdex/Codex state should depict. Phrased to avoid the common+# sprite-gen failure modes (detached effects, motion lines, shadows). ``running``+# is the *working* state (in place); ``running-right``/``-left`` are the walk cycles.STATE_ACTIONS: dict[str, str] = {"idle": "a calm idle loop: subtle breathing, a tiny blink or gentle bob, no big gestures","running-right": (@@ -78,9 +73,8 @@ def style_hint(style: str | None) -> str:return _STYLE_HINTS.get((style or "auto").strip().lower(), "")-# Row strips are generated on the wider landscape canvas (see imagegen.generate /-# orchestrate). The extra width is what lets each pose stay a healthy size AND-# leave a real gutter — used here only to cite concrete pixel numbers.+# Row strips are generated on the wider landscape canvas (imagegen.generate /+# orchestrate); used here only to cite concrete pixel numbers._ASSUMED_STRIP_WIDTH = 1536@@ -88,23 +82,18 @@ def _spacing_spec(frame_count: int) -> tuple[int, int]:"""(per-pose width px, gap px) for a row of *frame_count* poses.Pixel counts alone don't hold — the model fills each slot edge-to-edge with- the full wingspan, so neighbors touch even when bodies are spaced. The lever- that works is proportional containment on a wide canvas: give each pose its- own equal cell and keep the ENTIRE silhouette (wings/tail/halo included)- inside it. On the 1536px landscape strip ~70% occupancy still leaves a- generous gutter, so the pet stays a normal, good-looking size — no shrinking.+ the full wingspan. The lever that works is proportional containment on a wide+ canvas: each pose gets an equal cell and the ENTIRE silhouette stays inside it.+ ~70% occupancy on the 1536px strip still leaves a generous gutter, no shrinking."""slots = max(1, frame_count)slot_w = _ASSUMED_STRIP_WIDTH / slots- pose_px = round(slot_w * 0.7)- gap_px = max(48, round(slot_w * 0.3))- return pose_px, gap_px+ return round(slot_w * 0.7), max(48, round(slot_w * 0.3))# Per-draft nudges so the 4 base options are actually distinct — gpt-image returns-# near-duplicates for a single prompt. We vary the *look* (palette, build,-# expression, accents), NOT the pose, so the chosen base still grounds clean,-# consistent animation rows.+# near-duplicates for a single prompt. Vary the *look* (palette, build, expression,+# accents), NOT the pose, so the chosen base still grounds consistent rows.BASE_VARIATIONS: tuple[str, ...] = ("","a distinctly different colour palette and markings",diff --git a/agent/pet/manifest.py b/agent/pet/manifest.pyindex 9d23a28de6d..d3ca01b3349 100644--- a/agent/pet/manifest.py+++ b/agent/pet/manifest.py@@ -1,20 +1,8 @@"""Fetch the public petdex manifest.``https://petdex.dev/api/manifest`` 307-redirects to a JSON document on R2:-- {- "generatedAt": "...",- "total": 2926,- "pets": [- {"slug": "boba", "displayName": "Boba", "kind": "creature",- "submittedBy": "railly",- "spritesheetUrl": "https://assets.petdex.dev/.../spritesheet.webp",- "petJsonUrl": "https://assets.petdex.dev/.../pet.json",- "zipUrl": "https://assets.petdex.dev/.../boba.zip"},- ...- ]- }-+``{"generatedAt", "total", "pets": [{"slug", "displayName", "kind",+"submittedBy", "spritesheetUrl", "petJsonUrl", "zipUrl"}, ...]}``.Read-only and unauthenticated; no credentials involved."""@@ -31,11 +19,9 @@ MANIFEST_URL = "https://petdex.dev/api/manifest"_DEFAULT_TIMEOUT = 10.0-# In-process cache for the (large, slow, identical-per-call) manifest. The list-# is a static CDN object that barely changes, yet a single session can ask for-# it many times — every gallery open, plus a full re-fetch per install/select-# (``find_entry``). A short TTL collapses those into one network hit without-# going stale for long. Cleared by :func:`clear_cache` (tests).+# In-process cache for the (large, slow, identical-per-call) manifest: a static+# CDN object a single session may ask for many times (every gallery open, plus a+# re-fetch per install/select). A short TTL collapses those into one network hit._MANIFEST_TTL = 300.0_cache: tuple[float, list[ManifestEntry]] | None = None@@ -57,8 +43,8 @@ def prefetch(*, timeout: float = _DEFAULT_TIMEOUT) -> None:"""Warm the manifest cache in a daemon thread — idempotent, never blocks.The desktop picker calls this when it loads the (instant) local-only gallery- so the full petdex catalog is usually cached by the time it's requested,- without ever holding up the user's own pets on a network round-trip.+ so the full catalog is usually cached by the time it's requested, without+ holding up the user's own pets on a network round-trip."""global _prefetching@@ -114,9 +100,8 @@ class ManifestError(RuntimeError):def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) -> list[ManifestEntry]:"""Return every approved pet from the public manifest.- Cached in-process for ``_MANIFEST_TTL`` seconds (pass ``force=True`` to- bypass). Follows the 307 redirect to R2. Raises :class:`ManifestError` on- any network/parse failure so callers can surface a clean message.+ Cached in-process for ``_MANIFEST_TTL`` seconds (``force=True`` bypasses).+ Raises :class:`ManifestError` on any network/parse failure."""global _cache@@ -129,12 +114,7 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->raise ManifestError("httpx is required to fetch the petdex manifest") from exctry:- resp = httpx.get(- MANIFEST_URL,- timeout=timeout,- follow_redirects=True,- headers={"User-Agent": "hermes-agent-petdex"},- )+ resp = httpx.get(MANIFEST_URL, timeout=timeout, follow_redirects=True, headers={"User-Agent": "hermes-agent-petdex"})resp.raise_for_status()payload = resp.json()except Exception as exc: # noqa: BLE001 - normalize to one error type@@ -153,7 +133,4 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->def find_entry(slug: str, *, timeout: float = _DEFAULT_TIMEOUT) -> ManifestEntry | None:"""Return the manifest entry for *slug*, or ``None`` if not listed."""slug = slug.strip().lower()- for entry in fetch_manifest(timeout=timeout):- if entry.slug.lower() == slug:- return entry- return None+ return next((entry for entry in fetch_manifest(timeout=timeout) if entry.slug.lower() == slug), None)diff --git a/agent/pet/render.py b/agent/pet/render.pyindex 3eb958ff7a3..7c729acdcbd 100644--- a/agent/pet/render.py+++ b/agent/pet/render.py@@ -15,17 +15,13 @@ import ioimport loggingimport osimport sys+import zlib+from dataclasses import KW_ONLY, dataclassfrom functools import lru_cache+from itertools import groupbyfrom pathlib import Path-from agent.pet.constants import (- DEFAULT_SCALE,- FRAME_H,- FRAME_W,- FRAMES_PER_STATE,- PetState,- state_row_index,-)+from agent.pet.constants import DEFAULT_SCALE, FRAME_H, FRAME_W, FRAMES_PER_STATE, PetState, state_row_indexlogger = logging.getLogger(__name__)@@ -33,9 +29,6 @@ logger = logging.getLogger(__name__)RENDER_MODES = ("auto", "kitty", "iterm", "sixel", "unicode", "off")-# ───────────────────────── terminal capability detection ─────────────────────────--def _is_wezterm() -> bool:return os.environ.get("TERM_PROGRAM", "").lower() == "wezterm" or bool(os.environ.get("WEZTERM_PANE"))@@ -93,8 +86,6 @@ def resolve_mode(configured: str | None, *, stream=None) -> str:return detect_terminal_graphics() if mode == "auto" else mode-# ───────────────────────── frame decoding ─────────────────────────-# Max alpha at/below which a frame is blank padding. petdex sheets are# left-packed, so a state with fewer real frames than FRAMES_PER_STATE has# fully transparent trailing cells; animating into one flashes the pet blank.@@ -124,8 +115,7 @@ def _raw_frames(sheet_path: str, state_value: str, frame_w: int, frame_h: int, fframes = []for i in range(min(frames_per_state, cols)):- left = i * frame_w- frame = sheet.crop((left, top, left + frame_w, top + frame_h))+ frame = sheet.crop((i * frame_w, top, (i + 1) * frame_w, top + frame_h))if _frame_is_blank(frame):breakframes.append(frame)@@ -136,15 +126,7 @@ def _raw_frames(sheet_path: str, state_value: str, frame_w: int, frame_h: int, f@lru_cache(maxsize=8)-def _frames_for(- sheet_path: str,- state_value: str,- frame_w: int,- frame_h: int,- frames_per_state: int,- scale_w: int,- scale_h: int,-):+def _frames_for(sheet_path: str, state_value: str, frame_w: int, frame_h: int, frames_per_state: int, scale_w: int, scale_h: int):"""Scaled :func:`_raw_frames` (both cached, so animation-time requests are free)."""raw = _raw_frames(sheet_path, state_value, frame_w, frame_h, frames_per_state)if not raw or (scale_w, scale_h) == (frame_w, frame_h):@@ -155,25 +137,15 @@ def _frames_for(def state_frame_counts(- sheet_path: str | Path,- *,- frame_w: int = FRAME_W,- frame_h: int = FRAME_H,- frames_per_state: int = FRAMES_PER_STATE,+ sheet_path: str | Path, *, frame_w: int = FRAME_W, frame_h: int = FRAME_H, frames_per_state: int = FRAMES_PER_STATE) -> dict[str, int]:- """Each driven :class:`PetState` → its real (padding-trimmed) frame count.-- The gateway ships this map to the desktop canvas, which steps its own loop.- """+ """Each driven :class:`PetState` → its real (padding-trimmed) frame count (shipped to the desktop canvas)."""return {state.value: len(_raw_frames(str(sheet_path), state.value, frame_w, frame_h, frames_per_state))for state in PetState}-# ───────────────────────── encoders ─────────────────────────--def _png_b64(frame) -> str:buf = io.BytesIO()frame.save(buf, format="PNG")@@ -186,14 +158,7 @@ def _crop_frames_to_alpha_union(frames):kitty paints the whole transmitted rectangle, transparent margins included,so an untrimmed pet looks small and adrift inside its cell box."""- boxes = []- for frame in frames:- try:- bbox = frame.getchannel("A").getbbox()- except Exception: # noqa: BLE001 - cosmetic; fail open- bbox = None- if bbox:- boxes.append(bbox)+ boxes = [b for b in (f.getchannel("A").getbbox() for f in frames) if b]if not boxes:return framesunion = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))@@ -232,16 +197,11 @@ def _kitty_apc(ctrl: str, data: str) -> str:def _encode_kitty(frame, *, cell_cols: int | None = None, cell_rows: int | None = None) -> str:"""kitty transmit+display at the cursor; ``c``/``r`` pin the cell box so frames overwrite each other."""- ctrl = "f=100,a=T,q=2"- if cell_cols:- ctrl += f",c={cell_cols}"- if cell_rows:- ctrl += f",r={cell_rows}"+ ctrl = "f=100,a=T,q=2" + (f",c={cell_cols}" if cell_cols else "") + (f",r={cell_rows}" if cell_rows else "")return _kitty_apc(ctrl, _png_b64(frame))-# ───────────────────────── kitty Unicode placeholders ─────────────────────────-# Ink owns the screen and measures every cell's width, so it can't host raw+# kitty Unicode placeholders. Ink owns the screen and measures every cell's width, so it can't host raw# kitty image escapes. The placeholder protocol is the grid-safe path: transmit# once as a virtual placement (U=1), then print ordinary-width placeholder cells# (U+10EEEE + diacritics) whose foreground color encodes the image id; Ink counts@@ -253,43 +213,26 @@ _KITTY_PLACEHOLDER = "\U0010eeee"# Row/column diacritics, index → diacritic, verbatim from kitty's# gen/rowcolumn-diacritics.txt. We only ever need the row index._ROWCOL_DIACRITICS: tuple[int, ...] = (- 0x0305, 0x030D, 0x030E, 0x0310, 0x0312, 0x033D, 0x033E, 0x033F, 0x0346, 0x034A,- 0x034B, 0x034C, 0x0350, 0x0351, 0x0352, 0x0357, 0x035B, 0x0363, 0x0364, 0x0365,- 0x0366, 0x0367, 0x0368, 0x0369, 0x036A, 0x036B, 0x036C, 0x036D, 0x036E, 0x036F,- 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592, 0x0593, 0x0594, 0x0595, 0x0597,- 0x0598, 0x0599, 0x059C, 0x059D, 0x059E, 0x059F, 0x05A0, 0x05A1, 0x05A8, 0x05A9,- 0x05AB, 0x05AC, 0x05AF, 0x05C4, 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615,- 0x0616, 0x0617, 0x0657, 0x0658, 0x0659, 0x065A, 0x065B, 0x065D, 0x065E, 0x06D6,- 0x06D7, 0x06D8, 0x06D9, 0x06DA, 0x06DB, 0x06DC, 0x06DF, 0x06E0, 0x06E1, 0x06E2,- 0x06E4, 0x06E7, 0x06E8, 0x06EB, 0x06EC, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736,- 0x073A, 0x073D, 0x073F, 0x0740, 0x0741, 0x0743, 0x0745, 0x0747, 0x0749, 0x074A,- 0x07EB, 0x07EC, 0x07ED, 0x07EE, 0x07EF, 0x07F0, 0x07F1, 0x07F3, 0x0816, 0x0817,- 0x0818, 0x0819, 0x081B, 0x081C, 0x081D, 0x081E, 0x081F, 0x0820, 0x0821, 0x0822,- 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082A, 0x082B, 0x082C, 0x082D, 0x0951,- 0x0953, 0x0954, 0x0F82, 0x0F83, 0x0F86, 0x0F87, 0x135D, 0x135E, 0x135F, 0x17DD,- 0x193A, 0x1A17, 0x1A75, 0x1A76, 0x1A77, 0x1A78, 0x1A79, 0x1A7A, 0x1A7B, 0x1A7C,- 0x1B6B, 0x1B6D, 0x1B6E, 0x1B6F, 0x1B70, 0x1B71, 0x1B72, 0x1B73, 0x1CD0, 0x1CD1,- 0x1CD2, 0x1CDA, 0x1CDB, 0x1CE0, 0x1DC0, 0x1DC1, 0x1DC3, 0x1DC4, 0x1DC5, 0x1DC6,- 0x1DC7, 0x1DC8, 0x1DC9, 0x1DCB, 0x1DCC, 0x1DD1, 0x1DD2, 0x1DD3, 0x1DD4, 0x1DD5,- 0x1DD6, 0x1DD7, 0x1DD8, 0x1DD9, 0x1DDA, 0x1DDB, 0x1DDC, 0x1DDD, 0x1DDE, 0x1DDF,- 0x1DE0, 0x1DE1, 0x1DE2, 0x1DE3, 0x1DE4, 0x1DE5, 0x1DE6, 0x1DFE, 0x20D0, 0x20D1,- 0x20D4, 0x20D5, 0x20D6, 0x20D7, 0x20DB, 0x20DC, 0x20E1, 0x20E7, 0x20E9, 0x20F0,- 0x2CEF, 0x2CF0, 0x2CF1, 0x2DE0, 0x2DE1, 0x2DE2, 0x2DE3, 0x2DE4, 0x2DE5, 0x2DE6,- 0x2DE7, 0x2DE8, 0x2DE9, 0x2DEA, 0x2DEB, 0x2DEC, 0x2DED, 0x2DEE, 0x2DEF, 0x2DF0,- 0x2DF1, 0x2DF2, 0x2DF3, 0x2DF4, 0x2DF5, 0x2DF6, 0x2DF7, 0x2DF8, 0x2DF9, 0x2DFA,- 0x2DFB, 0x2DFC, 0x2DFD, 0x2DFE, 0x2DFF, 0xA66F, 0xA67C, 0xA67D, 0xA6F0, 0xA6F1,- 0xA8E0, 0xA8E1, 0xA8E2, 0xA8E3, 0xA8E4, 0xA8E5, 0xA8E6, 0xA8E7, 0xA8E8, 0xA8E9,- 0xA8EA, 0xA8EB, 0xA8EC, 0xA8ED, 0xA8EE, 0xA8EF, 0xA8F0, 0xA8F1, 0xAAB0, 0xAAB2,- 0xAAB3, 0xAAB7, 0xAAB8, 0xAABE, 0xAABF, 0xAAC1, 0xFE20, 0xFE21, 0xFE22, 0xFE23,- 0xFE24, 0xFE25, 0xFE26, 0x10A0F, 0x10A38, 0x1D185, 0x1D186, 0x1D187, 0x1D188,- 0x1D189, 0x1D1AA, 0x1D1AB, 0x1D1AC, 0x1D1AD, 0x1D242, 0x1D243, 0x1D244,+ 0x0305, 0x030D, 0x030E, 0x0310, 0x0312, 0x033D, 0x033E, 0x033F, 0x0346, 0x034A, 0x034B, 0x034C, 0x0350, 0x0351, 0x0352, 0x0357, 0x035B, 0x0363, 0x0364, 0x0365,+ 0x0366, 0x0367, 0x0368, 0x0369, 0x036A, 0x036B, 0x036C, 0x036D, 0x036E, 0x036F, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592, 0x0593, 0x0594, 0x0595, 0x0597,+ 0x0598, 0x0599, 0x059C, 0x059D, 0x059E, 0x059F, 0x05A0, 0x05A1, 0x05A8, 0x05A9, 0x05AB, 0x05AC, 0x05AF, 0x05C4, 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615,+ 0x0616, 0x0617, 0x0657, 0x0658, 0x0659, 0x065A, 0x065B, 0x065D, 0x065E, 0x06D6, 0x06D7, 0x06D8, 0x06D9, 0x06DA, 0x06DB, 0x06DC, 0x06DF, 0x06E0, 0x06E1, 0x06E2,+ 0x06E4, 0x06E7, 0x06E8, 0x06EB, 0x06EC, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736, 0x073A, 0x073D, 0x073F, 0x0740, 0x0741, 0x0743, 0x0745, 0x0747, 0x0749, 0x074A,+ 0x07EB, 0x07EC, 0x07ED, 0x07EE, 0x07EF, 0x07F0, 0x07F1, 0x07F3, 0x0816, 0x0817, 0x0818, 0x0819, 0x081B, 0x081C, 0x081D, 0x081E, 0x081F, 0x0820, 0x0821, 0x0822,+ 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082A, 0x082B, 0x082C, 0x082D, 0x0951, 0x0953, 0x0954, 0x0F82, 0x0F83, 0x0F86, 0x0F87, 0x135D, 0x135E, 0x135F, 0x17DD,+ 0x193A, 0x1A17, 0x1A75, 0x1A76, 0x1A77, 0x1A78, 0x1A79, 0x1A7A, 0x1A7B, 0x1A7C, 0x1B6B, 0x1B6D, 0x1B6E, 0x1B6F, 0x1B70, 0x1B71, 0x1B72, 0x1B73, 0x1CD0, 0x1CD1,+ 0x1CD2, 0x1CDA, 0x1CDB, 0x1CE0, 0x1DC0, 0x1DC1, 0x1DC3, 0x1DC4, 0x1DC5, 0x1DC6, 0x1DC7, 0x1DC8, 0x1DC9, 0x1DCB, 0x1DCC, 0x1DD1, 0x1DD2, 0x1DD3, 0x1DD4, 0x1DD5,+ 0x1DD6, 0x1DD7, 0x1DD8, 0x1DD9, 0x1DDA, 0x1DDB, 0x1DDC, 0x1DDD, 0x1DDE, 0x1DDF, 0x1DE0, 0x1DE1, 0x1DE2, 0x1DE3, 0x1DE4, 0x1DE5, 0x1DE6, 0x1DFE, 0x20D0, 0x20D1,+ 0x20D4, 0x20D5, 0x20D6, 0x20D7, 0x20DB, 0x20DC, 0x20E1, 0x20E7, 0x20E9, 0x20F0, 0x2CEF, 0x2CF0, 0x2CF1, 0x2DE0, 0x2DE1, 0x2DE2, 0x2DE3, 0x2DE4, 0x2DE5, 0x2DE6,+ 0x2DE7, 0x2DE8, 0x2DE9, 0x2DEA, 0x2DEB, 0x2DEC, 0x2DED, 0x2DEE, 0x2DEF, 0x2DF0, 0x2DF1, 0x2DF2, 0x2DF3, 0x2DF4, 0x2DF5, 0x2DF6, 0x2DF7, 0x2DF8, 0x2DF9, 0x2DFA,+ 0x2DFB, 0x2DFC, 0x2DFD, 0x2DFE, 0x2DFF, 0xA66F, 0xA67C, 0xA67D, 0xA6F0, 0xA6F1, 0xA8E0, 0xA8E1, 0xA8E2, 0xA8E3, 0xA8E4, 0xA8E5, 0xA8E6, 0xA8E7, 0xA8E8, 0xA8E9,+ 0xA8EA, 0xA8EB, 0xA8EC, 0xA8ED, 0xA8EE, 0xA8EF, 0xA8F0, 0xA8F1, 0xAAB0, 0xAAB2, 0xAAB3, 0xAAB7, 0xAAB8, 0xAABE, 0xAABF, 0xAAC1, 0xFE20, 0xFE21, 0xFE22, 0xFE23,+ 0xFE24, 0xFE25, 0xFE26, 0x10A0F, 0x10A38, 0x1D185, 0x1D186, 0x1D187, 0x1D188, 0x1D189, 0x1D1AA, 0x1D1AB, 0x1D1AC, 0x1D1AD, 0x1D242, 0x1D243, 0x1D244,)def kitty_image_id(slug: str) -> int:"""Deterministic per-slug image id in ``[1, 0x7FFF]`` (non-zero; encoded in the placeholder fg color) so re-renders reuse the terminal-side image."""- import zlib-return (zlib.crc32(slug.encode("utf-8")) % 0x7FFE) + 1@@ -304,11 +247,10 @@ def kitty_placeholder_rows(cols: int, rows: int) -> list[str]:The foreground color (image id) is applied by the caller / Ink, not here."""cols = max(1, cols)- out: list[str] = []- for r in range(max(1, rows)):- idx = min(r, len(_ROWCOL_DIACRITICS) - 1)- out.append(_KITTY_PLACEHOLDER + chr(_ROWCOL_DIACRITICS[idx]) + _KITTY_PLACEHOLDER * (cols - 1))- return out+ return [+ _KITTY_PLACEHOLDER + chr(_ROWCOL_DIACRITICS[min(r, len(_ROWCOL_DIACRITICS) - 1)]) + _KITTY_PLACEHOLDER * (cols - 1)+ for r in range(max(1, rows))+ ]def _encode_kitty_virtual(frame, *, image_id: int, cols: int, rows: int) -> str:@@ -323,13 +265,17 @@ def _encode_iterm(frame, *, cell_cols: int | None = None, cell_rows: int | None"""iTerm2 inline image (OSC 1337 File)."""payload = _png_b64(frame)args = ["inline=1", f"size={len(payload)}", "preserveAspectRatio=1"]- if cell_cols:- args.append(f"width={cell_cols}")- if cell_rows:- args.append(f"height={cell_rows}")+ args += [f"width={cell_cols}"] if cell_cols else []+ args += [f"height={cell_rows}"] if cell_rows else []return f"\x1b]1337;File={';'.join(args)}:{payload}\x07"+def _sixel_runs(chars: list[str]) -> str:+ """Run-length encode one sixel band line (``!<n><ch>`` for runs longer than 3)."""+ runs = ((ch, len(list(group))) for ch, group in groupby(chars))+ return "".join("!%d%s" % (n, ch) if n > 3 else ch * n for ch, n in runs)++def _encode_sixel(frame) -> str:"""DEC sixel via a compact hand-rolled encoder (Pillow has no sixel writer).@@ -350,32 +296,10 @@ def _encode_sixel(frame) -> str:out.append("#%d;2;%d;%d;%d" % (idx, r * 100 // 255, g * 100 // 255, b * 100 // 255))for band in range(0, h, 6):+ ys = range(band, min(band + 6, h))for color_idx in used:- line = ["#%d" % color_idx]- run_char = None- run_len = 0-- def flush():- nonlocal run_char, run_len- if run_char is None:- return- line.append("!%d%s" % (run_len, run_char) if run_len > 3 else run_char * run_len)- run_char, run_len = None, 0-- for x in range(w):- bits = 0- for bit in range(6):- y = band + bit- if y < h and alpha[x, y] > 32 and px[x, y] == color_idx:- bits |= 1 << bit- ch = chr(63 + bits)- if ch == run_char:- run_len += 1- else:- flush()- run_char, run_len = ch, 1- flush()- out.append("".join(line) + "$") # carriage return within band+ chars = [chr(63 + sum(1 << (y - band) for y in ys if alpha[x, y] > 32 and px[x, y] == color_idx)) for x in range(w)]+ out.append("#%d" % color_idx + _sixel_runs(chars) + "$") # carriage return within bandout.append("-") # next bandout.append("\x1b\\")return "".join(out)@@ -417,9 +341,16 @@ def _encode_unicode(frame, *, target_cols: int) -> str:return "\n".join(lines)-# ───────────────────────── public renderer ─────────────────────────+def _cell_box(frame) -> tuple[int, int]:+ """Terminal cell box (~8×16 px per cell) for a scaled frame.++ kitty stretches the image to fill ``c``×``r`` cells, so this must track+ the scaled pixel size, not a native-aspect column count (that upscales small pets).+ """+ return max(1, frame.width // 8), max(1, frame.height // 16)+@dataclass(eq=False)class PetRenderer:"""Holds a pet's spritesheet and yields encoded frames per (state, index).@@ -427,24 +358,19 @@ class PetRenderer:decoded frames are cached so repeated calls are cheap."""- def __init__(- self,- spritesheet: str | Path,- *,- mode: str = "unicode",- scale: float = DEFAULT_SCALE,- unicode_cols: int = 20,- frame_w: int = FRAME_W,- frame_h: int = FRAME_H,- frames_per_state: int = FRAMES_PER_STATE,- ) -> None:- self.spritesheet = str(spritesheet)- self.mode = mode if mode in RENDER_MODES else "unicode"- self.scale = scale- self.unicode_cols = unicode_cols- self.frame_w = frame_w- self.frame_h = frame_h- self.frames_per_state = frames_per_state+ spritesheet: str | Path+ _: KW_ONLY+ mode: str = "unicode"+ scale: float = DEFAULT_SCALE+ unicode_cols: int = 20+ frame_w: int = FRAME_W+ frame_h: int = FRAME_H+ frames_per_state: int = FRAMES_PER_STATE++ def __post_init__(self) -> None:+ self.spritesheet = str(self.spritesheet)+ if self.mode not in RENDER_MODES:+ self.mode = "unicode"@propertydef available(self) -> bool:@@ -454,15 +380,9 @@ class PetRenderer:return len(self._frames(state))def _frames(self, state: PetState | str):- return _frames_for(- self.spritesheet,- state.value if isinstance(state, PetState) else str(state),- self.frame_w,- self.frame_h,- self.frames_per_state,- max(1, int(self.frame_w * self.scale)),- max(1, int(self.frame_h * self.scale)),- )+ name = state.value if isinstance(state, PetState) else str(state)+ scaled = max(1, int(self.frame_w * self.scale)), max(1, int(self.frame_h * self.scale))+ return _frames_for(self.spritesheet, name, self.frame_w, self.frame_h, self.frames_per_state, *scaled)def cells(self, state: PetState | str, index: int, *, cols: int | None = None) -> list[list[Cell]]:"""One frame as a half-block cell grid for Ink's native color props; ``[]`` when unavailable."""@@ -471,14 +391,6 @@ class PetRenderer:return []return _downscale_cells(frames[index % len(frames)], target_cols=cols or self.unicode_cols)- def _cell_box(self, frame) -> tuple[int, int]:- """Terminal cell box (~8×16 px per cell) for a scaled frame.-- kitty stretches the image to fill ``c``×``r`` cells, so this must track- the scaled pixel size, not a native-aspect column count (that upscales small pets).- """- return max(1, frame.width // 8), max(1, frame.height // 16)-def kitty_payload(self, state: PetState | str, *, image_id: int) -> dict | None:"""kitty Unicode-placeholder payload ``{cols, rows, placeholder, frames}`` for one state.@@ -489,13 +401,9 @@ class PetRenderer:if not frames:return Noneframes = _snap_frames_to_cell_grid(_crop_frames_to_alpha_union(frames))- cols, rows = self._cell_box(frames[0])- return {- "cols": cols,- "rows": rows,- "placeholder": kitty_placeholder_rows(cols, rows),- "frames": [_encode_kitty_virtual(f, image_id=image_id, cols=cols, rows=rows) for f in frames],- }+ cols, rows = _cell_box(frames[0])+ encoded = [_encode_kitty_virtual(f, image_id=image_id, cols=cols, rows=rows) for f in frames]+ return {"cols": cols, "rows": rows, "placeholder": kitty_placeholder_rows(cols, rows), "frames": encoded}def frame(self, state: PetState | str, index: int) -> str:"""Encoded escape string for one frame (``index`` taken modulo the frame count), or ``""``."""@@ -505,13 +413,11 @@ class PetRenderer:if not frames:return ""frame = frames[index % len(frames)]- cell_cols, cell_rows = self._cell_box(frame)-try:- if self.mode == "kitty":- return _encode_kitty(frame, cell_cols=cell_cols, cell_rows=cell_rows)- if self.mode == "iterm":- return _encode_iterm(frame, cell_cols=cell_cols, cell_rows=cell_rows)+ if self.mode in ("kitty", "iterm"):+ cell_cols, cell_rows = _cell_box(frame)+ encode = _encode_kitty if self.mode == "kitty" else _encode_iterm+ return encode(frame, cell_cols=cell_cols, cell_rows=cell_rows)if self.mode == "sixel":return _encode_sixel(frame)return _encode_unicode(frame, target_cols=self.unicode_cols)@@ -521,13 +427,7 @@ class PetRenderer:def build_renderer(- spritesheet: str | Path,- *,- configured_mode: str | None = None,- scale: float = DEFAULT_SCALE,- unicode_cols: int = 20,- stream=None,+ spritesheet: str | Path, *, configured_mode: str | None = None, scale: float = DEFAULT_SCALE, unicode_cols: int = 20, stream=None) -> PetRenderer:"""Resolve the mode from config+env, then construct a :class:`PetRenderer`."""- mode = resolve_mode(configured_mode, stream=stream)- return PetRenderer(spritesheet, mode=mode, scale=scale, unicode_cols=unicode_cols)+ return PetRenderer(spritesheet, mode=resolve_mode(configured_mode, stream=stream), scale=scale, unicode_cols=unicode_cols)diff --git a/agent/pet/state.py b/agent/pet/state.pyindex 3385098a0ec..892c83ba823 100644--- a/agent/pet/state.py+++ b/agent/pet/state.py@@ -1,16 +1,9 @@"""Map agent activity → a :class:`PetState`.-This is the one place the "what is the agent doing right now?" → "which-animation row?" decision lives. Each surface feeds it the signals it already-tracks:--- CLI — ``KawaiiSpinner`` waiting/thinking state + tool outcomes.-- TUI — gateway ``tool.start/complete`` + ``message.delta/complete`` events.-- Desktop — the ``$busy``/``$awaitingResponse``/tool-event nanostores- (re-implemented in TS, but mirroring this priority order).--Keeping the priority order here (and documenting it) lets the TypeScript-mirror stay faithful without a second design.+The one place the "what is the agent doing?" → "which animation row?" decision+lives. CLI (spinner state + tool outcomes), TUI (gateway tool/message events)+and Desktop (nanostores; re-implemented in TS mirroring this priority order)+all feed it the signals they already track."""from __future__ import annotations@@ -24,18 +17,13 @@ from agent.pet.constants import PetStatedef todos_all_done(todos: Iterable[Any] | None) -> bool:"""True iff there's ≥1 todo and every one is completed/cancelled.- The "celebrate" beat (``JUMP``) fires when a plan finishes; this mirrors- the TUI's ``isTodoDone`` so the trigger is defined once across surfaces.- Accepts dicts (``{"status": ...}``) or objects with a ``status`` attr.+ The "celebrate" beat (``JUMP``) fires when a plan finishes; mirrors the TUI's+ ``isTodoDone``. Accepts dicts (``{"status": ...}``) or objects with ``status``."""items = list(todos or [])- if not items:- return False-- def _status(t: Any) -> Any:- return t.get("status") if isinstance(t, dict) else getattr(t, "status", None)-- return all(_status(t) in ("completed", "cancelled") for t in items)+ return bool(items) and all(+ (t.get("status") if isinstance(t, dict) else getattr(t, "status", None)) in ("completed", "cancelled") for t in items+ )def derive_pet_state(@@ -56,11 +44,10 @@ def derive_pet_state(1. ``error`` → ``FAILED`` (a tool/turn just failed)2. ``celebrate`` → ``JUMP`` (explicit success beat, e.g. todos done)3. ``just_completed`` → ``WAVE`` (turn finished cleanly / greeting)- 4. ``awaiting_input`` → ``WAITING`` (blocked on the user — a clarify/approval- prompt is open; this outranks the in-flight signals below because the turn- is paused on *you*, even though a tool is technically mid-call)- 5. ``tool_running`` → ``RUN`` (a tool is executing)- 6. ``reasoning`` → ``REVIEW`` (model is thinking / reading)+ 4. ``awaiting_input`` → ``WAITING`` (blocked on the user — outranks the in-flight+ signals below because the turn is paused on *you*, even mid tool call)+ 5. ``tool_running`` → ``RUN``+ 6. ``reasoning`` → ``REVIEW``7. ``busy`` → ``RUN`` (turn in flight, unspecified work)8. otherwise → ``IDLE``"""diff --git a/agent/pet/store.py b/agent/pet/store.pyindex fd1891ecc88..6c1a46e5f8f 100644--- a/agent/pet/store.py+++ b/agent/pet/store.py@@ -9,11 +9,17 @@ caller-supplied ``display.pet.slug`` so this module stays free of the config loafrom __future__ import annotations+import contextlib+import io+import itertoolsimport jsonimport loggingimport re+import shutil+import zipfilefrom dataclasses import dataclassfrom pathlib import Path+from urllib.parse import urlparsefrom hermes_constants import get_hermes_home@@ -21,6 +27,9 @@ logger = logging.getLogger(__name__)_DOWNLOAD_TIMEOUT = 60.0_HTTP_HEADERS = {"User-Agent": "hermes-agent-petdex"}+_THUMB_FRAME_W = 192+_THUMB_FRAME_H = 208+_THUMB_W = 96 # rendered ~40px; 2x+ keeps it crisp on HiDPIclass PetStoreError(RuntimeError):@@ -63,10 +72,8 @@ def _thumb_path(slug: str) -> Path:def _read_pet_json(directory: Path) -> dict:pet_json = directory / "pet.json"- if not pet_json.is_file():- return {}try:- return json.loads(pet_json.read_text(encoding="utf-8"))+ return json.loads(pet_json.read_text(encoding="utf-8")) if pet_json.is_file() else {}except (OSError, ValueError) as exc:logger.debug("unreadable pet.json in %s: %s", directory, exc)return {}@@ -79,11 +86,8 @@ def _write_pet_json(directory: Path, meta: dict) -> None:def _resolve_spritesheet(directory: Path, meta: dict) -> Path:"""Honor ``spritesheetPath``, else probe conventional names (incl. petdex R2's ``sprite.webp``)."""declared = str(meta.get("spritesheetPath", "") or "").strip()- for name in ([declared] if declared else []) + ["spritesheet.webp", "spritesheet.png", "sprite.webp", "sprite.png"]:- candidate = directory / name- if candidate.is_file():- return candidate- return directory / "spritesheet.webp" # stable default even when missing+ names = ([declared] if declared else []) + ["spritesheet.webp", "spritesheet.png", "sprite.webp", "sprite.png"]+ return next((directory / n for n in names if (directory / n).is_file()), directory / "spritesheet.webp") # stable defaultdef _safe_slug(slug: str) -> str:@@ -99,10 +103,8 @@ def _safe_slug(slug: str) -> str:def load_pet(slug: str) -> InstalledPet | None:"""Return the :class:`InstalledPet` for *slug*, or ``None`` if absent."""slug = _safe_slug(slug)- if not slug:- return Nonedirectory = pets_dir() / slug- if not directory.is_dir():+ if not slug or not directory.is_dir():return Nonemeta = _read_pet_json(directory)return InstalledPet(@@ -115,31 +117,26 @@ def load_pet(slug: str) -> InstalledPet | None:)-def _loaded_pet_or_raise(slug: str, error: str) -> InstalledPet:+def _usable_pet(slug: str, error: str = "") -> InstalledPet | None:+ """:func:`load_pet` result only when its spritesheet is on disk; raises :class:`PetStoreError` *error* if given."""pet = load_pet(slug)- if pet is None or not pet.exists:+ if pet and pet.exists:+ return pet+ if error:raise PetStoreError(error)- return pet+ return Nonedef installed_pets() -> list[InstalledPet]:"""Return every installed pet (dirs containing a usable spritesheet)."""- out: list[InstalledPet] = []- for child in sorted(pets_dir().iterdir()):- if not child.is_dir():- continue- pet = load_pet(child.name)- if pet and pet.exists:- out.append(pet)- return out+ pets = (_usable_pet(child.name) for child in sorted(pets_dir().iterdir()) if child.is_dir())+ return [pet for pet in pets if pet]def resolve_active_pet(configured_slug: str | None = None) -> InstalledPet | None:"""The configured slug (``display.pet.slug``) if installed, else the first pet alphabetically."""- if configured_slug:- pet = load_pet(configured_slug.strip())- if pet and pet.exists:- return pet+ if configured_slug and (pet := _usable_pet(configured_slug.strip())):+ return petpets = installed_pets()return pets[0] if pets else None@@ -155,14 +152,12 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TIslug = _safe_slug(slug)if not slug:raise PetStoreError("invalid pet slug")- existing = load_pet(slug)- if existing and existing.exists and not force:+ existing = _usable_pet(slug)+ if existing and not force:return existing-entry = find_entry(slug, timeout=timeout)if entry is None:raise PetStoreError(f"pet '{slug}' is not in the petdex manifest")-# Host-pin asset URLs so a compromised/spoofed manifest can't redirect the# download to an arbitrary host (matches thumbnail_png).if not _is_petdex_host(entry.spritesheet_url):@@ -170,7 +165,6 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TIdirectory = pets_dir() / slugdirectory.mkdir(parents=True, exist_ok=True)-sprite_ext = ".png" if entry.spritesheet_url.lower().split("?")[0].endswith(".png") else ".webp"sprite_path = directory / f"spritesheet{sprite_ext}"_download(entry.spritesheet_url, sprite_path, timeout=timeout)@@ -179,16 +173,16 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TImeta: dict = {}if entry.pet_json_url and _is_petdex_host(entry.pet_json_url):try:- meta = _download_json(entry.pet_json_url, timeout=timeout)+ data = _http_get(entry.pet_json_url, timeout).json()+ meta = data if isinstance(data, dict) else {}except Exception as exc: # noqa: BLE001 - non-fatal, fall back belowlogger.debug("pet.json fetch failed for %s: %s", slug, exc)- if not meta:- meta = {"id": slug, "displayName": entry.display_name, "description": ""}+ meta = meta or {"id": slug, "displayName": entry.display_name, "description": ""}meta["spritesheetPath"] = sprite_path.namemeta.setdefault("id", slug)meta.setdefault("displayName", entry.display_name)_write_pet_json(directory, meta)- return _loaded_pet_or_raise(slug, f"install of '{slug}' did not produce a spritesheet")+ return _usable_pet(slug, f"install of '{slug}' did not produce a spritesheet")def slugify(name: str) -> str:@@ -200,12 +194,8 @@ def slugify(name: str) -> str:def unique_slug(name: str) -> str:"""A :func:`slugify` result that doesn't collide with an existing pet dir."""base = slugify(name)- slug = base- counter = 2- while (pets_dir() / slug).exists():- slug = f"{base}-{counter}"- counter += 1- return slug+ candidates = (base if i == 1 else f"{base}-{i}" for i in itertools.count(1))+ return next(slug for slug in candidates if not (pets_dir() / slug).exists())def _write_spritesheet(source, dest: Path) -> None:@@ -213,24 +203,12 @@ def _write_spritesheet(source, dest: Path) -> None:if isinstance(source, (bytes, bytearray)):dest.write_bytes(bytes(source))return+ from agent.pet.generate.atlas import _load_rgba- from PIL import Image+ _load_rgba(source).save(dest, format="WEBP", lossless=True, quality=100, method=6, exact=True)- if isinstance(source, (str, Path)):- with Image.open(source) as opened:- image = opened.convert("RGBA")- else:- image = source.convert("RGBA")- image.save(dest, format="WEBP", lossless=True, quality=100, method=6, exact=True)--def register_local_pet(- spritesheet,- *,- slug: str,- display_name: str = "",- description: str = "",-) -> InstalledPet:+def register_local_pet(spritesheet, *, slug: str, display_name: str = "", description: str = "") -> InstalledPet:"""Write a locally-generated pet (PIL image, WebP/PNG bytes, or path) into the store.It appears in :func:`installed_pets` immediately and, because :func:`install_pet`@@ -246,48 +224,29 @@ def register_local_pet(except Exception as exc: # noqa: BLE001 - normalize to one error typeraise PetStoreError(f"could not write spritesheet for '{slug}': {exc}") from exc- _write_pet_json(- directory,- {- "id": slug,- "displayName": display_name or slug,- "description": description or "",- "spritesheetPath": sprite_path.name,- "createdBy": "generator",- },- )- return _loaded_pet_or_raise(slug, f"register of generated pet '{slug}' did not produce a spritesheet")+ meta = {"id": slug, "displayName": display_name or slug, "description": description or "", "spritesheetPath": sprite_path.name}+ _write_pet_json(directory, {**meta, "createdBy": "generator"})+ return _usable_pet(slug, f"register of generated pet '{slug}' did not produce a spritesheet")def export_pet(slug: str) -> tuple[str, bytes]:"""Zip an installed pet's folder → ``(filename, bytes)``; dotfiles (thumbs, backups) skipped."""- import io- import zipfile-root = pets_dir()directory = root / slug.strip()# Traversal guard: the target must be a direct child of pets_dir.if directory.resolve().parent != root.resolve() or not directory.is_dir():raise PetStoreError(f"pet '{slug}' is not installed")- name = directory.namebuf = io.BytesIO()with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as archive:for path in sorted(directory.iterdir()):if path.is_file() and not path.name.startswith("."):- archive.write(path, f"{name}/{path.name}")- return f"{name}.zip", buf.getvalue()---_THUMB_FRAME_W = 192-_THUMB_FRAME_H = 208-_THUMB_W = 96 # rendered ~40px; 2x+ keeps it crisp on HiDPI+ archive.write(path, f"{directory.name}/{path.name}")+ return f"{directory.name}.zip", buf.getvalue()def _is_petdex_host(url: str) -> bool:"""True only for petdex.dev hosts — bounds server-side fetch (anti-SSRF)."""- from urllib.parse import urlparse-try:host = (urlparse(url).hostname or "").lower()except ValueError:@@ -295,6 +254,20 @@ def _is_petdex_host(url: str) -> bool:return host == "petdex.dev" or host.endswith(".petdex.dev")+def _thumb_source_bytes(slug: str, source_url: str, timeout: float) -> bytes | None:+ """Spritesheet bytes for a thumbnail: the installed sheet, else a petdex-hosted *source_url*."""+ pet = _usable_pet(slug)+ if pet:+ with contextlib.suppress(OSError):+ return pet.spritesheet.read_bytes()+ if source_url and _is_petdex_host(source_url):+ try:+ return _http_get(source_url, timeout).content+ except Exception as exc: # noqa: BLE001 - cosmetic, degrade to placeholder+ logger.debug("thumb fetch failed for %s: %s", slug, exc)+ return None++def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) -> bytes | None:"""Small idle-frame (top-left cell) PNG for *slug*, cached on disk.@@ -306,71 +279,37 @@ def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) ->slug = slug.strip()if not slug:return None-cache = _thumb_path(slug)if cache.is_file():- try:+ with contextlib.suppress(OSError):return cache.read_bytes()- except OSError:- pass-- sheet_bytes: bytes | None = None- pet = load_pet(slug)- if pet and pet.exists:- try:- sheet_bytes = pet.spritesheet.read_bytes()- except OSError:- pass-- if sheet_bytes is None and source_url and _is_petdex_host(source_url):- try:- import httpx-- resp = httpx.get(source_url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)- resp.raise_for_status()- sheet_bytes = resp.content- except Exception as exc: # noqa: BLE001 - cosmetic, degrade to placeholder- logger.debug("thumb fetch failed for %s: %s", slug, exc)-+ sheet_bytes = _thumb_source_bytes(slug, source_url, timeout)if not sheet_bytes:return None-try:- import io-from PIL import Imagewith Image.open(io.BytesIO(sheet_bytes)) as im:frame = im.convert("RGBA").crop((0, 0, min(_THUMB_FRAME_W, im.width), min(_THUMB_FRAME_H, im.height)))- frame = frame.resize((_THUMB_W, round(_THUMB_W * _THUMB_FRAME_H / _THUMB_FRAME_W)), Image.NEAREST)- buf = io.BytesIO()- frame.save(buf, format="PNG")- data = buf.getvalue()+ frame = frame.resize((_THUMB_W, round(_THUMB_W * _THUMB_FRAME_H / _THUMB_FRAME_W)), Image.NEAREST)+ buf = io.BytesIO()+ frame.save(buf, format="PNG")except Exception as exc: # noqa: BLE001logger.debug("thumb crop failed for %s: %s", slug, exc)return None-- try:- cache.write_bytes(data)- except OSError:- pass- return data+ with contextlib.suppress(OSError):+ cache.write_bytes(buf.getvalue())+ return buf.getvalue()def remove_pet(slug: str) -> bool:"""Delete an installed pet directory. Returns True if anything was removed."""- import shutil-slug = _safe_slug(slug)if not slug:return False-# Drop the cached thumb too or a later pet reusing this slug shows the stale one.- try:+ with contextlib.suppress(OSError):_thumb_path(slug).unlink(missing_ok=True)- except OSError:- pass-directory = pets_dir() / slugif not directory.is_dir():return False@@ -388,30 +327,24 @@ def rename_pet(slug: str, display_name: str) -> str | None:"""slug = _safe_slug(slug)display_name = (display_name or "").strip()- if not slug or not display_name:- return Nonedirectory = pets_dir() / slug- if not (directory / "pet.json").is_file():+ if not slug or not display_name or not (directory / "pet.json").is_file():return Nonemeta = _read_pet_json(directory)- if not isinstance(meta, dict):- meta = {}+ meta = meta if isinstance(meta, dict) else {}meta["displayName"] = display_name-new_slug = slugdesired = slugify(display_name)if desired and desired != slug and not (pets_dir() / desired).exists():try:directory.rename(pets_dir() / desired)- try:+ except OSError:+ pass # keep the provisional slug if the move fails+ else:+ with contextlib.suppress(OSError):_thumb_path(slug).rename(_thumb_path(desired))- except OSError:- passdirectory = pets_dir() / desired- new_slug = desired- meta["id"] = new_slug- except OSError:- new_slug = slug # keep the provisional slug if the move fails+ new_slug = meta["id"] = desiredtry:_write_pet_json(directory, meta)@@ -420,7 +353,17 @@ def rename_pet(slug: str, display_name: str) -> str | None:return new_slug+def _http_get(url: str, timeout: float):+ """GET *url* with the petdex UA, following redirects; raises on HTTP errors."""+ import httpx++ resp = httpx.get(url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)+ resp.raise_for_status()+ return resp++def _download(url: str, dest: Path, *, timeout: float) -> None:+ """Stream *url* to *dest* via a ``.part`` temp file so a failed download never leaves a truncated sheet."""import httpxtry:@@ -433,12 +376,3 @@ def _download(url: str, dest: Path, *, timeout: float) -> None:tmp.replace(dest)except Exception as exc: # noqa: BLE001raise PetStoreError(f"download failed for {url}: {exc}") from exc---def _download_json(url: str, *, timeout: float) -> dict:- import httpx-- resp = httpx.get(url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)- resp.raise_for_status()- data = resp.json()- return data if isinstance(data, dict) else {}