Skip to content

The agent that grows with you

refactor(agent): pet — pass 2 (render/store/orchestrate helper collapse, dispatch, docstring compaction; 25% LOC cut)

Teknium6c41acbddd39
diff --git a/agent/pet/__init__.py b/agent/pet/__init__.py
index 66e07528f36..64f3213084c 100644
--- a/agent/pet/__init__.py
+++ b/agent/pet/__init__.py
@@ -11,24 +11,7 @@ A pure display concern: no model tool, no prompt/toolset mutation, so zero
effect on prompt caching.
"""
-from agent.pet.constants import (
- DEFAULT_SCALE,
- FRAME_H,
- FRAME_W,
- FRAMES_PER_STATE,
- LOOP_MS,
- STATE_ROWS,
- PetState,
-)
+from agent.pet.constants import DEFAULT_SCALE, FRAME_H, FRAME_W, FRAMES_PER_STATE, LOOP_MS, STATE_ROWS, PetState
from agent.pet.state import derive_pet_state
-__all__ = [
- "DEFAULT_SCALE",
- "FRAME_H",
- "FRAME_W",
- "FRAMES_PER_STATE",
- "LOOP_MS",
- "STATE_ROWS",
- "PetState",
- "derive_pet_state",
-]
+__all__ = ["DEFAULT_SCALE", "FRAME_H", "FRAME_W", "FRAMES_PER_STATE", "LOOP_MS", "STATE_ROWS", "PetState", "derive_pet_state"]
diff --git a/agent/pet/constants.py b/agent/pet/constants.py
index 66892b96c56..fc291c1dc12 100644
--- a/agent/pet/constants.py
+++ b/agent/pet/constants.py
@@ -10,30 +10,21 @@ from __future__ import annotations
from enum import Enum
-# 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 geometry (pixels). Codex/petdex sheets are 8 cols x 9 rows (1536x1872);
+# older sheets 9 x 8 (1728x1664). Renderers derive taxonomy/columns from the sheet.
FRAME_W = 192
FRAME_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 N.
+# Frames stepped per state (petdex CSS ``steps(6)``); extra physical columns are ignored.
FRAMES_PER_STATE = 6
+LOOP_MS = 1100 # full-loop duration for one state, ms (petdex default)
-# 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 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.
+# ``display.pet.scale`` is the single master scalar: the desktop canvas multiplies
+# native pixels by it and every terminal surface derives its column width from it
+# (:func:`cols_for_scale`). petdex clients render at 0.7; we default smaller so the
+# mascot stays a glanceable corner sprite (half-blocks clamp to ``UNICODE_MIN_COLS``).
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.
+# User-settable bounds (``/pet scale``, desktop slider): floor keeps the pet
+# clickable/visible; ceiling stops a fat-fingered value from filling the screen.
MIN_SCALE = 0.1
MAX_SCALE = 3.0
@@ -43,25 +34,17 @@ def clamp_scale(scale: float) -> float:
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 192px → 24 cells. Mirrors the kitty placement (``scaled_px // 8``) so at
-# full scale every renderer agrees.
+# Cells one native frame spans at ``scale == 1.0`` (~8px cells → 24); 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
-# 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). ``scale`` shrinks the unicode pet down TO this
-# floor, not past it into noise.
+# Legibility floor for half-blocks: a cell samples 1 horizontal + 2 vertical taps,
+# so below this width the pet is an unreadable blob regardless of scale (kitty/GUI
+# draw true pixels, no floor). ``scale`` shrinks the unicode pet TO this floor, not past it.
UNICODE_MIN_COLS = 16
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.
- """
+ """Half-block width implied by *scale*, clamped to the legibility floor (tracks the kitty cell box above it)."""
return max(UNICODE_MIN_COLS, round(BASE_UNICODE_COLS * (scale or DEFAULT_SCALE)))
@@ -71,12 +54,7 @@ def resolve_cols(scale: float, unicode_cols: int = 0) -> int:
class PetState(str, Enum):
- """Animation state a pet can be shown in.
-
- 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``).
- """
+ """Animation state a pet can be shown in (Hermes names; Codex rows say ``jumping``/``running`` for ``jump``/``run``)."""
IDLE = "idle"
WAVE = "wave"
@@ -93,12 +71,9 @@ LEGACY_STATE_ROWS: list[str] = ["idle", "wave", "run", "failed", "review", "jump
# 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.
+# Default for callers without a sheet: generated pets and the Codex contract use 9 rows.
STATE_ROWS: list[str] = CODEX_STATE_ROWS
-
-# Canonical Hermes activity names -> accepted row-name aliases in descending
-# preference, so internal names stay stable while matching Petdex's taxonomy.
+# Canonical Hermes names -> accepted row-name aliases in descending preference.
_CODEX_NAMES = {"wave": "waving", "jump": "jumping", "run": "running"}
STATE_ALIASES: dict[str, tuple[str, ...]] = {
s.value: (s.value, _CODEX_NAMES[s.value]) if s.value in _CODEX_NAMES else (s.value,) for s in PetState
diff --git a/agent/pet/generate/atlas.py b/agent/pet/generate/atlas.py
index d1de0e0889c..2eeb334bac9 100644
--- a/agent/pet/generate/atlas.py
+++ b/agent/pet/generate/atlas.py
@@ -38,12 +38,8 @@ 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
-# Normalized cells fill like real petdex pets (~5px from the edges); the width
-# clamp, not the pad, prevents clipping.
-_NORMALIZE_PAD = 14
-# 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
+_NORMALIZE_PAD = 14 # normalized cells fill like real petdex pets (~5px from the edges)
+_SIDE_LOBE_RATIO = 0.18 # adjacent-pose bleed is a small lobe; sizeable lobes (wide poses) survive
_NEIGHBOURS = ((1, 0), (-1, 0), (0, 1), (0, -1))
_NEAREST = Image.Resampling.NEAREST # interpolating resamples blur hard pixel-art edges
@@ -97,7 +93,7 @@ def _border_flood(w: int, h: int, visited: bytearray, accept) -> list[tuple[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:
+ for x, y in border: # corners appear twice in ``border``; the visited mark dedupes them
if not visited[y * w + x] and accept(x, y):
visited[y * w + x] = 1
seeds.append((x, y))
@@ -341,6 +337,13 @@ def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[i
Merges when vertical spans overlap and the horizontal gap is tiny relative to
the component size; never bridges the larger gaps between separate poses.
"""
+
+ def related(a, b) -> bool:
+ (al, at, ar, ab), (bl, bt, br, bb) = a, b
+ 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))
+ return v_overlap >= min_h * 0.45 and gap <= max(14, min_w * 0.22)
+
boxes = list(boxes)
changed = True
while changed:
@@ -350,19 +353,13 @@ def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[i
for i, a in enumerate(boxes):
if used[i]:
continue
- al, at, ar, ab = a
used[i] = True
for j in range(i + 1, len(boxes)):
- if used[j]:
- continue
- bl, bt, br, bb = boxes[j]
- 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
- changed = True
- merged.append((al, at, ar, ab))
+ if not used[j] and related(a, boxes[j]):
+ b = boxes[j]
+ a = (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))
+ used[j] = changed = True
+ merged.append(a)
boxes = merged
return boxes
diff --git a/agent/pet/generate/imagegen.py b/agent/pet/generate/imagegen.py
index 9aff9ada362..abe75651d78 100644
--- a/agent/pet/generate/imagegen.py
+++ b/agent/pet/generate/imagegen.py
@@ -1,11 +1,9 @@
"""Thin image-generation layer for pet sprites.
-Wraps the active :class:`~agent.image_gen_provider.ImageGenProvider` with the
-two things sprite generation needs that the agent-facing ``image_generate`` tool
-doesn't expose: **N variants** (loop) and **reference-image grounding** (so each
-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.
+Wraps the active ``ImageGenProvider`` with what the ``image_generate`` tool
+doesn't expose: N variants and reference-image grounding (each animation row
+stays the same character as the chosen base). Grounding needs a ref-capable
+provider; we resolve to one or raise an actionable error rather than drift.
"""
from __future__ import annotations
@@ -17,20 +15,12 @@ from pathlib import Path
logger = logging.getLogger(__name__)
-# Providers that can ground generation on a reference image, in preference order
-# (Nous Portal → OpenAI → OpenRouter → …). OpenRouter/Nous run a quality-first
-# model chain and may fall back depending on account access and endpoint behavior,
-# so fidelity can vary by configured backend + model availability.
+# Providers that can ground generation on a reference image, in preference order.
+# OpenRouter/Nous run a quality-first model chain and may fall back depending on
+# account access, so fidelity can vary by configured backend.
_REF_CAPABLE = ("nous", "openai", "openai-codex", "openrouter", "krea")
-
# Friendly display label per reference-capable provider (desktop pet-gen picker).
-_PROVIDER_LABELS: dict[str, str] = {
- "nous": "Nous Portal",
- "openrouter": "OpenRouter",
- "openai": "OpenAI",
- "openai-codex": "OpenAI (Codex)",
- "krea": "Krea",
-}
+_PROVIDER_LABELS = {"nous": "Nous Portal", "openrouter": "OpenRouter", "openai": "OpenAI", "openai-codex": "OpenAI (Codex)", "krea": "Krea"}
class GenerationError(RuntimeError):
@@ -64,13 +54,12 @@ 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.
+ """Pick the image provider for sprite work.
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).
+ then *prefer* (desktop picker), then the active provider, then the first available
+ — each only if ref-capable and configured. With *require_references* off, any
+ available active provider is accepted (prompt-only base drafts).
"""
_discover()
from agent.image_gen_registry import get_active_provider
@@ -99,11 +88,7 @@ def resolve_provider(*, require_references: bool = True, prefer: str | None = No
def list_sprite_providers() -> list[dict]:
- """``[{name, label, default}]`` for every configured ref-capable provider, in preference order.
-
- ``default`` marks the one :func:`resolve_provider` would choose with no explicit
- preference. Empty when none is configured (the picker hides itself).
- """
+ """``[{name, label, default}]`` per configured ref-capable provider, in preference order; empty hides the picker."""
_discover()
try:
default_name = resolve_provider(require_references=True).name
@@ -126,12 +111,7 @@ 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 (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.
- """
+ """True when a provider error is specifically about ``background=transparent`` (a per-model capability; we retry without it)."""
lowered = (error or "").lower()
return "background" in lowered and ("not supported" in lowered or "transparent" in lowered)
@@ -148,12 +128,10 @@ 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*: ``"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.
+ *aspect_ratio* ``"landscape"`` (row strips) gives every frame horizontal room so
+ winged poses needn't shrink. We *ask* for a transparent background but fall
+ back to opaque 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:
diff --git a/agent/pet/generate/orchestrate.py b/agent/pet/generate/orchestrate.py
index 31603099232..aec37df703f 100644
--- a/agent/pet/generate/orchestrate.py
+++ b/agent/pet/generate/orchestrate.py
@@ -1,12 +1,10 @@
"""Pet generation orchestration — the base-draft → hatch flow.
-1. :func:`generate_base_drafts` — a few cheap prompt-only "what should this pet
- look like" variants; the user picks one (or retries).
-2. :func:`hatch_pet` — grounds one row strip per Hermes state on the chosen base,
- slices frames, composes + validates the atlas, and writes it to the store.
-
-Splitting bounds cost (4 cheap base calls per round; the ~8 row calls happen
-once, on the pet you keep) and gives each UI a natural preview/loading point.
+:func:`generate_base_drafts` makes a few cheap prompt-only look variants the user
+picks between; :func:`hatch_pet` grounds one row strip per state on the chosen
+base, slices frames, composes + validates the atlas, and writes it to the store.
+Splitting bounds cost (the ~8 row calls happen once, on the pet you keep) and
+gives each UI a natural preview/loading point.
"""
from __future__ import annotations
@@ -28,11 +26,9 @@ logger = logging.getLogger(__name__)
# (event, detail) — e.g. ("row", "idle"), ("compose", ""), ("save", "<slug>").
ProgressFn = Callable[[str, str], None]
-# Generations are independent network calls, fanned out so a hatch (~8 rows)
-# doesn't blow the client's RPC timeout; capped to respect provider rate limits.
+# Fan-out so a hatch (~8 rows) doesn't blow the client's RPC timeout; capped for provider rate limits.
_MAX_PARALLEL_GENERATIONS = 4
-# Row (re)generation attempts: early ones demand clean per-pose gutters, the
-# last is lenient so a stubborn row still yields frames instead of dropping out.
+# Row attempts: early ones demand clean per-pose gutters, the last is lenient so a stubborn row still yields.
_ROW_GEN_ATTEMPTS = 3
_MIN_FILLED_STATES = 6
_REQUIRED_STATES = frozenset({"idle", "running-right", "waving"})
@@ -40,15 +36,11 @@ _REQUIRED_STATES = frozenset({"idle", "running-right", "waving"})
# (substrings, friendly message), first match wins. Moderation is the big one:
# image models refuse trademarked characters / real people as an opaque 400.
_IMAGE_ERROR_HINTS: tuple[tuple[tuple[str, ...], str], ...] = (
- (
- ("moderation_blocked", "safety system", "content policy", "content_policy"),
- "The image provider blocked this prompt — its safety filter rejects "
- "trademarked characters and real people. Try an original description.",
- ),
- (
- ("api key", "unauthorized", "401", "auth"),
- "The image provider rejected the request — check your API key in Settings → Providers.",
- ),
+ (("moderation_blocked", "safety system", "content policy", "content_policy"),
+ "The image provider blocked this prompt — its safety filter rejects "
+ "trademarked characters and real people. Try an original description."),
+ (("api key", "unauthorized", "401", "auth"),
+ "The image provider rejected the request — check your API key in Settings → Providers."),
(("rate limit", "429"), "The image provider is rate-limiting — wait a moment and try again."),
)
@@ -72,25 +64,18 @@ def _unlink_quietly(path: Path) -> None:
def _harden_transparency(path: Path) -> Path:
"""Key out any solid backdrop the provider painted; save as an RGBA PNG.
- ``background=transparent`` is requested but honored inconsistently, so run the
- row extractor's chroma-key pass on every base draft. Best-effort: a decode
- failure leaves the original untouched.
+ ``background=transparent`` is honored inconsistently, so every base draft gets
+ the chroma-key pass. Best-effort: a decode failure leaves the original untouched.
"""
- from PIL import Image
-
try:
- with Image.open(path) as opened:
- keyed = atlas.remove_background(opened.convert("RGBA"))
- keyed = atlas._clear_transparent_rgb(keyed) # no colored halo on the dark UI
+ keyed = atlas._clear_transparent_rgb(atlas.remove_background(atlas._load_rgba(path))) # no halo on the dark UI
# PNGs (any case) are hardened in place: with_suffix(".png") on ".PNG" would
# name the same file on case-insensitive filesystems and the unlink below
# would delete the hardened output.
out = path if path.suffix.lower() == ".png" else path.with_suffix(".png")
keyed.save(out, format="PNG")
if out != path:
- # Nothing prunes cache/images outside the gateway loop: drop the
- # non-PNG original the hardened PNG replaces.
- _unlink_quietly(path)
+ _unlink_quietly(path) # nothing else prunes cache/images outside the gateway loop
return out
except Exception as exc: # noqa: BLE001 - cosmetic; fall back to the raw image
logger.debug("base draft transparency hardening failed for %s: %s", path, exc)
@@ -100,9 +85,9 @@ def _harden_transparency(path: Path) -> Path:
def _run_parallel(fn, items, *, cancelled, on_cancel_log: str) -> Iterator:
"""Fan *fn* over *items* in a pool, yielding results in completion order.
- ``as_completed`` runs on the caller's (request) thread, so callbacks fired
- from the results inherit the request's bound transport, unlike the workers.
- Once *cancelled* trips, queued work is cancelled and in-flight results dropped.
+ ``as_completed`` runs on the caller's thread, so result callbacks inherit the
+ request's bound transport (workers don't). Once *cancelled* trips, queued work
+ is cancelled and in-flight results dropped.
"""
workers = max(1, min(len(items), _MAX_PARALLEL_GENERATIONS))
with ThreadPoolExecutor(max_workers=workers) as pool:
@@ -126,26 +111,22 @@ def generate_base_drafts(
on_draft: Callable[[int, Path], None] | None = None,
is_cancelled: Callable[[], bool] | None = None,
) -> list[Path]:
- """Generate *n* candidate base looks for *concept*; returns image paths.
+ """Generate *n* candidate base looks for *concept* concurrently; returns image paths.
- Drafts run concurrently and are hardened to transparent cutouts;
- *on_draft(index, path)* fires as each finishes so UIs can stream previews.
- *is_cancelled* is polled cooperatively (unstarted drafts skipped, queued work
- cancelled, in-flight results dropped).
+ Drafts are hardened to transparent cutouts; *on_draft(index, path)* fires as each
+ finishes so UIs can stream previews. *is_cancelled* is polled cooperatively.
"""
# A user reference image grounds every draft, so it needs a reference-capable provider.
refs = reference_images or None
sprite = provider or imagegen.resolve_provider(require_references=bool(refs))
cancelled = is_cancelled or (lambda: False)
-
logger.info("pet generate: drafting %d base looks for %r (style=%s)", n, concept, style)
def _one(index: int) -> tuple[int, Path | None, str | None]:
if cancelled():
return index, None, None
t0 = time.monotonic()
- # Distinct variation nudge per draft so the options aren't near-duplicates.
- variation = prompts.BASE_VARIATIONS[index % len(prompts.BASE_VARIATIONS)]
+ variation = prompts.BASE_VARIATIONS[index % len(prompts.BASE_VARIATIONS)] # distinct look per draft
prompt = prompts.build_base_prompt(concept, style=style, variation=variation)
try:
out = imagegen.generate(prompt, n=1, reference_images=refs, provider=sprite, prefix="pet_base")
@@ -163,8 +144,7 @@ def generate_base_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)
+ errors += [err] if err else []
continue
results[index] = path
if on_draft is not None:
@@ -172,7 +152,6 @@ def generate_base_drafts(
on_draft(index, path)
except Exception as exc: # noqa: BLE001 - progress is best-effort
logger.debug("on_draft callback failed: %s", exc)
-
drafts = [results[i] for i in sorted(results)]
if not drafts and not cancelled():
# Surface *why*: the most common failure reason is the representative cause.
@@ -198,27 +177,20 @@ def _generate_row(spec: tuple[str, int, int], *, base: Path, label: str, style:
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:
+ # Landscape: each frame gets real horizontal room and clean gutters.
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",
+ prompts.build_row_prompt(state, count, label, style=style), n=1, reference_images=[base],
+ provider=sprite, prefix=f"pet_row_{state}", aspect_ratio="landscape",
)
# fit=False keeps raw columns so normalize_cells registers the whole pet at once.
- method = "components" if strict else "auto"
+ method = "components" if attempt < _ROW_GEN_ATTEMPTS - 1 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
@@ -249,19 +221,16 @@ def hatch_pet(
"""Turn an approved base image into a full, installed Hermes pet.
Idle falls back to the base look so the pet always renders. Raises
- :class:`GenerationError` on failure. *is_cancelled* is polled cooperatively
- and, once tripped, aborts before composing/saving so a stopped hatch never
- writes a half-built pet.
+ :class:`GenerationError` on failure. Once *is_cancelled* trips, aborts before
+ composing/saving so a stopped hatch never writes a half-built pet.
"""
base = Path(base_image)
if not base.is_file():
raise GenerationError(f"base image not found: {base}")
-
sprite = provider or imagegen.resolve_provider(require_references=True)
progress = on_progress or (lambda *_: None)
cancelled = is_cancelled or (lambda: False)
label = concept or display_name or slug
-
frames_by_state: dict[str, list] = {}
total_rows = len(atlas.ROW_SPECS)
logger.info("pet hatch %r: generating %d animation rows", slug, total_rows)
@@ -278,7 +247,6 @@ def hatch_pet(
progress("row", f"{state}:{done}:{total_rows}")
if frames:
frames_by_state[state] = frames
-
if cancelled():
raise GenerationError("hatch cancelled")
@@ -305,11 +273,10 @@ def hatch_pet(
if not validation["ok"]:
raise GenerationError("; ".join(validation["errors"]) or "atlas validation failed")
filled_states = set(validation["filled_states"])
- missing_required = sorted(_REQUIRED_STATES - filled_states)
- if missing_required:
+ if missing_required := sorted(_REQUIRED_STATES - filled_states):
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)}/{total_rows} animation rows were usable; regenerate")
from agent.pet import store
diff --git a/agent/pet/generate/prompts.py b/agent/pet/generate/prompts.py
index d1f35b3c49a..01b64769367 100644
--- a/agent/pet/generate/prompts.py
+++ b/agent/pet/generate/prompts.py
@@ -10,9 +10,8 @@ hatched pet is a valid ``petdex submit`` spritesheet.
from __future__ import annotations
-# 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.
+# What each state depicts, phrased to avoid sprite-gen failure modes (detached
+# effects, motion lines, shadows). ``running`` = working in place; ``-right/-left`` = walk.
STATE_ACTIONS: dict[str, str] = {
"idle": "a calm idle loop: subtle breathing, a tiny blink or gentle bob, no big gestures",
"running-right": (
@@ -73,27 +72,23 @@ 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 (imagegen.generate /
-# orchestrate); used here only to cite concrete pixel numbers.
-_ASSUMED_STRIP_WIDTH = 1536
+_ASSUMED_STRIP_WIDTH = 1536 # landscape row canvas; used only to cite concrete pixel numbers
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. 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.
+ Pixel counts alone don't hold — the model fills each slot edge-to-edge. The lever
+ that works is proportional containment: equal cells, whole silhouette inside,
+ ~70% occupancy (still a generous gutter on 1536px, no shrinking).
"""
slots = max(1, frame_count)
slot_w = _ASSUMED_STRIP_WIDTH / slots
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. Vary the *look* (palette, build, expression,
-# accents), NOT the pose, so the chosen base still grounds consistent rows.
+# Per-draft nudges so base options are distinct (gpt-image near-duplicates one
+# prompt). Vary the *look*, NOT the pose, so the base still grounds consistent rows.
BASE_VARIATIONS: tuple[str, ...] = (
"",
"a distinctly different colour palette and markings",
@@ -105,10 +100,7 @@ BASE_VARIATIONS: tuple[str, ...] = (
def build_base_prompt(concept: str, *, style: str | None = "auto", variation: str = "") -> str:
- """The base look: a single, clean, centered full-body mascot.
-
- *variation* differentiates one draft from the next (see :data:`BASE_VARIATIONS`).
- """
+ """The base look: a single, clean, centered full-body mascot; *variation* differentiates drafts."""
concept = (concept or "a distinctive mascot creature").strip()
nudge = f" Make this design distinct: {variation}." if variation else ""
return (
@@ -127,11 +119,7 @@ def build_base_prompt(concept: str, *, style: str | None = "auto", variation: st
def build_row_prompt(state: str, frame_count: int, concept: str, *, style: str | None = "auto") -> str:
- """A row strip: *frame_count* poses of the SAME character, left→right.
-
- The attached base image is the identity source of truth; the prompt locks
- species, palette, face, and props to it.
- """
+ """A row strip: *frame_count* poses of the SAME character, left→right, identity locked to the attached base image."""
action = STATE_ACTIONS.get(state, "a simple idle pose")
concept = (concept or "the mascot").strip()
pose_px, gap_px = _spacing_spec(frame_count)
diff --git a/agent/pet/manifest.py b/agent/pet/manifest.py
index d3ca01b3349..ebd76f68bad 100644
--- a/agent/pet/manifest.py
+++ b/agent/pet/manifest.py
@@ -42,15 +42,12 @@ def _cache_is_warm() -> bool:
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 catalog is usually cached by the time it's requested, without
- holding up the user's own pets on a network round-trip.
+ The desktop picker calls this when loading the instant local-only gallery so
+ the full catalog is usually cached by the time it's requested.
"""
global _prefetching
-
if _cache_is_warm():
return
-
with _prefetch_lock:
if _prefetching:
return
@@ -98,21 +95,14 @@ 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 (``force=True`` bypasses).
- Raises :class:`ManifestError` on any network/parse failure.
- """
+ """Every approved pet from the public manifest; cached for ``_MANIFEST_TTL`` s unless *force*. Raises :class:`ManifestError`."""
global _cache
-
if not force and _cache_is_warm():
return _cache[1]
-
try:
import httpx
except ImportError as exc: # pragma: no cover - httpx is a core dep
raise ManifestError("httpx is required to fetch the petdex manifest") from exc
-
try:
resp = httpx.get(MANIFEST_URL, timeout=timeout, follow_redirects=True, headers={"User-Agent": "hermes-agent-petdex"})
resp.raise_for_status()
@@ -123,7 +113,6 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->
pets = payload.get("pets") if isinstance(payload, dict) else None
if not isinstance(pets, list):
raise ManifestError("petdex manifest had no 'pets' array")
-
parsed = (ManifestEntry.from_dict(raw) for raw in pets if isinstance(raw, dict))
entries = [entry for entry in parsed if entry.slug and entry.spritesheet_url]
_cache = (time.monotonic(), entries)
diff --git a/agent/pet/render.py b/agent/pet/render.py
index 7c729acdcbd..c8cb8139c04 100644
--- a/agent/pet/render.py
+++ b/agent/pet/render.py
@@ -1,11 +1,11 @@
"""Decode a pet spritesheet and encode frames for a terminal.
-Shared by the base CLI (writes escape bytes to stdout) and the TUI (ships the
-encoded bytes to Ink) so decode + capability detection + protocol encoding
-exist once. Output modes, in fidelity order: ``kitty`` (kitty, Ghostty,
-WezTerm), ``iterm`` (iTerm2, WezTerm), ``sixel`` (xterm -ti vt340, foot,
-mlterm, …), ``unicode`` (24-bit half-blocks; any truecolor terminal). Missing
-Pillow or spritesheet degrades to an empty string rather than raising.
+Shared by the base CLI (escape bytes to stdout) and the TUI (bytes shipped to
+Ink) so decode + capability detection + protocol encoding exist once. Modes in
+fidelity order: ``kitty`` (kitty, Ghostty, WezTerm), ``iterm`` (iTerm2, WezTerm),
+``sixel`` (xterm -ti vt340, foot, mlterm, …), ``unicode`` (24-bit half-blocks).
+Missing Pillow or spritesheet degrades to an empty string rather than raising
+(PIL is imported lazily on purpose).
"""
from __future__ import annotations
@@ -34,14 +34,9 @@ def _is_wezterm() -> bool:
def detect_terminal_graphics() -> str:
- """Best-effort richest protocol from env vars only (never a DA1 query that could hang a pipe).
-
- Returns ``kitty`` / ``iterm`` / ``sixel`` / ``unicode``; unknown terminals get
- ``unicode``, which works anywhere with truecolor.
- """
+ """Richest protocol (``kitty``/``iterm``/``sixel``/``unicode``) from env vars only — never a DA1 query that could hang a pipe."""
term = os.environ.get("TERM", "").lower()
term_program = os.environ.get("TERM_PROGRAM", "").lower()
-
# VS Code/Cursor set TERM_PROGRAM=vscode but don't scrub inherited
# ITERM_SESSION_ID/KITTY_WINDOW_ID; trusting those emits a protocol xterm.js
# can't show (blank frame). Inline images there are opt-in, so default to
@@ -60,35 +55,27 @@ def detect_terminal_graphics() -> str:
def supports_kitty_placeholders() -> bool:
- """True when the terminal paints kitty Unicode placeholders (U+10EEEE).
-
- Narrower than ``detect_terminal_graphics() == "kitty"``: WezTerm accepts
- kitty APC transmits but lacks the placeholder grid (cells render as tofu).
- """
+ """True when the terminal paints kitty Unicode placeholders; WezTerm speaks kitty APC but renders placeholders as tofu."""
return detect_terminal_graphics() == "kitty" and not _is_wezterm()
def resolve_mode(configured: str | None, *, stream=None) -> str:
"""Effective render mode from ``display.pet.render_mode`` + env; ``off`` when not a TTY."""
mode = (configured or "auto").strip().lower()
- if mode not in RENDER_MODES:
- mode = "auto"
+ mode = mode if mode in RENDER_MODES else "auto"
if mode == "off":
return "off"
-
stream = stream or sys.stdout
try:
if not (hasattr(stream, "isatty") and stream.isatty()):
return "off"
except (ValueError, OSError):
return "off"
-
return detect_terminal_graphics() if mode == "auto" else mode
-# 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.
+# Max alpha at/below which a frame is blank padding: petdex sheets are left-packed,
+# so short states have transparent trailing cells; animating into one flashes blank.
_BLANK_ALPHA = 8
@@ -98,21 +85,14 @@ def _frame_is_blank(frame) -> bool:
@lru_cache(maxsize=16)
def _raw_frames(sheet_path: str, state_value: str, frame_w: int, frame_h: int, frames_per_state: int) -> tuple:
- """Cropped RGBA frames for one state row, stopping at the first blank column.
-
- Cached; returns ``()`` on any decode failure.
- """
+ """Cropped RGBA frames for one state row, stopping at the first blank column; ``()`` on any decode failure."""
try:
from PIL import Image
sheet = Image.open(Path(sheet_path)).convert("RGBA")
- cols = max(1, sheet.width // frame_w)
- rows = max(1, sheet.height // frame_h)
- top = state_row_index(state_value, rows) * frame_h
+ cols, rows = max(1, sheet.width // frame_w), max(1, sheet.height // frame_h)
# Clamp to the sheet: some pets ship fewer rows than the taxonomy reserves.
- if top + frame_h > sheet.height:
- top = max(0, sheet.height - frame_h)
-
+ top = min(state_row_index(state_value, rows) * frame_h, max(0, sheet.height - frame_h))
frames = []
for i in range(min(frames_per_state, cols)):
frame = sheet.crop((i * frame_w, top, (i + 1) * frame_w, top + frame_h))
@@ -140,10 +120,7 @@ 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
) -> dict[str, int]:
"""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
- }
+ return {s.value: len(_raw_frames(str(sheet_path), s.value, frame_w, frame_h, frames_per_state)) for s in PetState}
def _png_b64(frame) -> str:
@@ -153,11 +130,7 @@ def _png_b64(frame) -> str:
def _crop_frames_to_alpha_union(frames):
- """Crop every frame to the union opaque bbox (a stable trim across the animation).
-
- kitty paints the whole transmitted rectangle, transparent margins included,
- so an untrimmed pet looks small and adrift inside its cell box.
- """
+ """Crop every frame to the union opaque bbox: kitty paints transparent margins too, so an untrimmed pet looks small and adrift."""
boxes = [b for b in (f.getchannel("A").getbbox() for f in frames) if b]
if not boxes:
return frames
@@ -165,12 +138,10 @@ def _crop_frames_to_alpha_union(frames):
return [f.crop(union) for f in frames]
-# Nominal terminal cell size in pixels. kitty fits an image to its cell
-# rectangle preserving aspect, so a frame that isn't a whole cell multiple
-# rounds up, clipping the bottom row ("clipped feet") and letterboxing a blank
-# row. Snapping to an exact multiple avoids that (cf. ratatui-image #57).
-_CELL_W = 8
-_CELL_H = 16
+# Nominal terminal cell size in pixels. kitty fits an image to its cell rectangle
+# preserving aspect, so a frame that isn't a whole cell multiple rounds up, clipping
+# the bottom row ("clipped feet"); snapping to an exact multiple avoids that.
+_CELL_W, _CELL_H = 8, 16
def _snap_frames_to_cell_grid(frames):
@@ -181,18 +152,14 @@ def _snap_frames_to_cell_grid(frames):
w, h = frames[0].size
target = (max(1, round(w / _CELL_W)) * _CELL_W, max(1, round(h / _CELL_H)) * _CELL_H)
- if (w, h) == target:
- return frames
- return [f.resize(target, Image.LANCZOS) for f in frames]
+ return frames if (w, h) == target else [f.resize(target, Image.LANCZOS) for f in frames]
def _kitty_apc(ctrl: str, data: str) -> str:
- """kitty APC escape for *data*, chunked into ≤4096-byte ``m`` pieces."""
+ """kitty APC escape for *data*, chunked into ≤4096-byte ``m`` pieces (``m=1`` = more chunks follow)."""
pieces = [data[i : i + 4096] for i in range(0, len(data), 4096)] or [""]
last = len(pieces) - 1
- return "".join(
- f"\x1b_G{ctrl + ',' if i == 0 else ''}m={0 if i == last else 1};{piece}\x1b\\" for i, piece in enumerate(pieces)
- )
+ return "".join(f"\x1b_G{ctrl + ',' if i == 0 else ''}m={int(i != last)};{piece}\x1b\\" for i, piece in enumerate(pieces))
def _encode_kitty(frame, *, cell_cols: int | None = None, cell_rows: int | None = None) -> str:
@@ -201,17 +168,13 @@ def _encode_kitty(frame, *, cell_cols: int | None = None, cell_rows: int | None
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 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
-# them as width-1 text and the terminal paints the image underneath.
+# kitty Unicode placeholders: Ink owns the screen and measures every cell, so it
+# can't host raw kitty image escapes. Transmit once as a virtual placement (U=1),
+# then print ordinary-width placeholder cells (U+10EEEE + row diacritic) whose
+# foreground color encodes the image id; the terminal paints the image underneath.
# https://sw.kovidgoyal.net/kitty/graphics-protocol/#unicode-placeholders
-
_KITTY_PLACEHOLDER = "\U0010eeee"
-
-# Row/column diacritics, index → diacritic, verbatim from kitty's
-# gen/rowcolumn-diacritics.txt. We only ever need the row index.
+# Row diacritics by index, verbatim from kitty's gen/rowcolumn-diacritics.txt.
_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,
@@ -242,10 +205,7 @@ def kitty_color_hex(image_id: int) -> str:
def kitty_placeholder_rows(cols: int, rows: int) -> list[str]:
- """Placeholder text grid: first cell carries the row diacritic, the rest auto-increment the column.
-
- The foreground color (image id) is applied by the caller / Ink, not here.
- """
+ """Placeholder text grid: first cell carries the row diacritic, the rest auto-increment the column (fg color applied by Ink)."""
cols = max(1, cols)
return [
_KITTY_PLACEHOLDER + chr(_ROWCOL_DIACRITICS[min(r, len(_ROWCOL_DIACRITICS) - 1)]) + _KITTY_PLACEHOLDER * (cols - 1)
@@ -254,10 +214,7 @@ def kitty_placeholder_rows(cols: int, rows: int) -> list[str]:
def _encode_kitty_virtual(frame, *, image_id: int, cols: int, rows: int) -> str:
- """Transmit a frame as a kitty virtual placement (``U=1``; ``q=2`` mutes replies that would corrupt Ink's output).
-
- Re-sending with the same ``i`` replaces the image, so static placeholder cells animate underneath.
- """
+ """kitty virtual placement (``U=1``; ``q=2`` mutes replies that would corrupt Ink). Re-sending the same ``i`` animates in place."""
return _kitty_apc(f"a=T,U=1,i={image_id},c={cols},r={rows},f=100,q=2", _png_b64(frame))
@@ -277,10 +234,7 @@ def _sixel_runs(chars: list[str]) -> str:
def _encode_sixel(frame) -> str:
- """DEC sixel via a compact hand-rolled encoder (Pillow has no sixel writer).
-
- Quantizes to ≤255 adaptive colors; transparent pixels are skipped (render as background).
- """
+ """DEC sixel via a compact hand-rolled encoder (Pillow has none); ≤255 adaptive colors, transparent pixels skipped."""
from PIL import Image
pal = frame.convert("RGB").quantize(colors=255, method=Image.MEDIANCUT)
@@ -288,7 +242,6 @@ def _encode_sixel(frame) -> str:
px = pal.load()
alpha = frame.getchannel("A").load()
w, h = pal.size
-
out = ["\x1bP0;1;0q", '"1;1;%d;%d' % (w, h)]
used = sorted({px[x, y] for y in range(h) for x in range(w)})
for idx in used: # color registers on a 0..100 scale
@@ -301,27 +254,20 @@ def _encode_sixel(frame) -> str:
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 band
out.append("-") # next band
- out.append("\x1b\\")
- return "".join(out)
+ return "".join(out) + "\x1b\\"
_HALF_BLOCK = "▀"
-
# A single half-block cell: top pixel + bottom pixel as (r, g, b, a) tuples.
Cell = tuple[tuple[int, int, int, int], tuple[int, int, int, int]]
def _downscale_cells(frame, *, target_cols: int) -> list[list[Cell]]:
- """Downscale a frame to rows of half-block cells (one terminal row = two pixel rows).
-
- Framework-neutral representation shared by the ANSI encoder (CLI) and the
- structured ``cells`` API (Ink).
- """
+ """Downscale to rows of half-block cells (one terminal row = two pixel rows); shared by the ANSI encoder and Ink."""
from PIL import Image
target_cols = max(4, target_cols)
- aspect = frame.height / max(1, frame.width)
- target_rows = max(2, int(round(target_cols * aspect * 0.5)) * 2)
+ target_rows = max(2, int(round(target_cols * (frame.height / max(1, frame.width)) * 0.5)) * 2)
px = frame.resize((target_cols, target_rows), Image.LANCZOS).convert("RGBA").load()
return [
[(px[x, y], px[x, y + 1] if y + 1 < target_rows else (0, 0, 0, 0)) for x in range(target_cols)]
@@ -331,32 +277,26 @@ def _downscale_cells(frame, *, target_cols: int) -> list[list[Cell]]:
def _encode_unicode(frame, *, target_cols: int) -> str:
"""Truecolor ANSI half-blocks (one char = 2 vertical pixels)."""
- lines: list[str] = []
- for row in _downscale_cells(frame, target_cols=target_cols):
- cells = [
- "\x1b[0m " if ta < 32 and ba < 32 else f"\x1b[38;2;{tr};{tg};{tb}m\x1b[48;2;{br};{bg};{bb}m{_HALF_BLOCK}"
- for (tr, tg, tb, ta), (br, bg, bb, ba) in row
- ]
- lines.append("".join(cells) + "\x1b[0m")
- return "\n".join(lines)
+
+ def cell(top, bottom) -> str:
+ (tr, tg, tb, ta), (br, bg, bb, ba) = top, bottom
+ return "\x1b[0m " if ta < 32 and ba < 32 else f"\x1b[38;2;{tr};{tg};{tb}m\x1b[48;2;{br};{bg};{bb}m{_HALF_BLOCK}"
+
+ return "\n".join("".join(cell(t, b) for t, b in row) + "\x1b[0m" for row in _downscale_cells(frame, target_cols=target_cols))
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).
+ 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)
+ return max(1, frame.width // _CELL_W), max(1, frame.height // _CELL_H)
@dataclass(eq=False)
class PetRenderer:
- """Holds a pet's spritesheet and yields encoded frames per (state, index).
-
- Construct once per pet, then call :meth:`frame` on an animation timer;
- decoded frames are cached so repeated calls are cheap.
- """
+ """Holds a pet's spritesheet and yields encoded frames per (state, index); decoded frames are cached."""
spritesheet: str | Path
_: KW_ONLY
@@ -392,11 +332,7 @@ class PetRenderer:
return _downscale_cells(frames[index % len(frames)], target_cols=cols or self.unicode_cols)
def kitty_payload(self, state: PetState | str, *, image_id: int) -> dict | None:
- """kitty Unicode-placeholder payload ``{cols, rows, placeholder, frames}`` for one state.
-
- ``frames`` are transmit escapes (all reusing ``image_id``); ``placeholder``
- is the static text grid Ink paints. ``None`` when no frame is available.
- """
+ """kitty placeholder payload ``{cols, rows, placeholder, frames}`` (transmit escapes + static text grid); ``None`` if no frames."""
frames = self._frames(state)
if not frames:
return None
diff --git a/agent/pet/state.py b/agent/pet/state.py
index 892c83ba823..f4e51c7ddf9 100644
--- a/agent/pet/state.py
+++ b/agent/pet/state.py
@@ -1,9 +1,7 @@
"""Map agent activity → a :class:`PetState`.
-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.
+The one place the "what is the agent doing?" → "which row?" decision lives; CLI,
+TUI and Desktop (TS mirror of this priority order) feed it the signals they track.
"""
from __future__ import annotations
@@ -15,11 +13,7 @@ from agent.pet.constants import PetState
def 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; mirrors the TUI's
- ``isTodoDone``. Accepts dicts (``{"status": ...}``) or objects with ``status``.
- """
+ """True iff ≥1 todo and all completed/cancelled (the ``JUMP`` celebrate beat; mirrors the TUI's ``isTodoDone``)."""
items = list(todos or [])
return bool(items) and all(
(t.get("status") if isinstance(t, dict) else getattr(t, "status", None)) in ("completed", "cancelled") for t in items
diff --git a/agent/pet/store.py b/agent/pet/store.py
index 6c1a46e5f8f..b0c6092afd9 100644
--- a/agent/pet/store.py
+++ b/agent/pet/store.py
@@ -1,10 +1,9 @@
"""On-disk pet store — install / list / resolve pets.
-Pets live under ``get_hermes_home()/pets/<slug>/`` (profile-scoped; we do NOT
-reuse petdex's ``~/.codex/pets``, which the petdex CLI owns). Each pet dir holds
-``pet.json`` ({id, displayName, description, spritesheetPath}) plus
-``spritesheet.webp`` (or .png). The active pet is resolved from the
-caller-supplied ``display.pet.slug`` so this module stays free of the config loader.
+Pets live under ``get_hermes_home()/pets/<slug>/`` (profile-scoped; NOT petdex's
+``~/.codex/pets``, which its CLI owns): ``pet.json`` ({id, displayName,
+description, spritesheetPath}) plus ``spritesheet.webp`` (or .png). The active
+pet comes from the caller-supplied ``display.pet.slug`` (no config loader here).
"""
from __future__ import annotations
@@ -91,11 +90,7 @@ def _resolve_spritesheet(directory: Path, meta: dict) -> Path:
def _safe_slug(slug: str) -> str:
- """Normalize a slug to a single bare path segment.
-
- Slugs index ``pets_dir()/<slug>/`` for load/remove, so separators (``../``,
- absolute paths) must not escape the pets directory; ``.``/``..`` are rejected.
- """
+ """Normalize a slug to one bare path segment so ``pets_dir()/<slug>`` can never escape the pets directory."""
segment = Path(str(slug).strip()).name
return "" if segment in ("", ".", "..") else segment
@@ -142,18 +137,13 @@ def resolve_active_pet(configured_slug: str | None = None) -> InstalledPet | Non
def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TIMEOUT) -> InstalledPet:
- """Download *slug* from the manifest into the pets directory.
-
- Idempotent: a fully-installed pet is returned as-is unless *force*. Raises
- :class:`PetStoreError` / :class:`~agent.pet.manifest.ManifestError` on failure.
- """
+ """Download *slug* from the manifest; idempotent unless *force*. Raises :class:`PetStoreError` / ``ManifestError``."""
from agent.pet.manifest import find_entry
slug = _safe_slug(slug)
if not slug:
raise PetStoreError("invalid pet slug")
- existing = _usable_pet(slug)
- if existing and not force:
+ if not force and (existing := _usable_pet(slug)):
return existing
entry = find_entry(slug, timeout=timeout)
if entry is None:
@@ -178,7 +168,7 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TI
except Exception as exc: # noqa: BLE001 - non-fatal, fall back below
logger.debug("pet.json fetch failed for %s: %s", slug, exc)
meta = meta or {"id": slug, "displayName": entry.display_name, "description": ""}
- meta["spritesheetPath"] = sprite_path.name
+ meta["spritesheetPath"] = sprite_path.name # key order matters: pet.json is written verbatim
meta.setdefault("id", slug)
meta.setdefault("displayName", entry.display_name)
_write_pet_json(directory, meta)
@@ -211,9 +201,8 @@ def _write_spritesheet(source, dest: Path) -> None:
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`
- returns an on-disk pet before consulting the manifest, can be adopted without
- a manifest entry.
+ Appears in :func:`installed_pets` immediately; :func:`install_pet` returns on-disk
+ pets before consulting the manifest, so no manifest entry is needed.
"""
slug = slugify(slug)
directory = pets_dir() / slug
@@ -223,7 +212,6 @@ def register_local_pet(spritesheet, *, slug: str, display_name: str = "", descri
_write_spritesheet(spritesheet, sprite_path)
except Exception as exc: # noqa: BLE001 - normalize to one error type
raise PetStoreError(f"could not write spritesheet for '{slug}': {exc}") from exc
-
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")
@@ -236,7 +224,6 @@ def export_pet(slug: str) -> tuple[str, bytes]:
# 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")
-
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as archive:
for path in sorted(directory.iterdir()):
@@ -269,12 +256,11 @@ def _thumb_source_bytes(slug: str, source_url: str, timeout: float) -> bytes | N
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.
+ """Small idle-frame (top-left cell) PNG for *slug*, cached on disk; ``None`` on any failure.
- Source: the installed spritesheet, else *source_url* only when it points at
- petdex (the gateway never fetches an arbitrary client URL). ``None`` when no
- usable source or Pillow/network fails. Server-side so the result rides the
- authenticated gateway as a same-origin data URL, sidestepping CSP/hotlink limits.
+ Source: the installed sheet, else *source_url* only when petdex-hosted (the gateway
+ never fetches arbitrary client URLs). Server-side so it rides the authenticated
+ gateway as a same-origin data URL, sidestepping CSP/hotlink limits.
"""
slug = slug.strip()
if not slug:
@@ -320,10 +306,9 @@ def remove_pet(slug: str) -> bool:
def rename_pet(slug: str, display_name: str) -> str | None:
"""Rename a pet's ``displayName`` AND realign its slug/dir to match.
- Generated pets hatch under a provisional prompt-derived slug; naming on the
- reveal screen makes that name the real identity. The dir (and cached thumb)
- moves to ``slugify(name)`` when that's a free, different slug; otherwise the
- slug stays. Returns the resulting slug, or ``None`` on failure.
+ Generated pets hatch under a provisional slug; naming makes that the identity.
+ The dir (and thumb) moves to ``slugify(name)`` when that's a free, different
+ slug. Returns the resulting slug, or ``None`` on failure.
"""
slug = _safe_slug(slug)
display_name = (display_name or "").strip()