open-design/scripts/bake-community-pets.ts
Tom Huang 6fa2077651
feat(web): add pet companion with Codex hatch-pet integration (#296)
* feat(web): add pet companion with Codex hatch-pet integration

Introduces a customizable floating pet companion (overlay + entry-view rail
+ composer menu + dedicated Settings → Pets section) that supports built-in
pets, user customization (glyph/image/spritesheet), and one-click adoption
of pets packaged by the upstream Codex `hatch-pet` skill via a new
`/api/codex-pets` daemon endpoint. Vendors the unmodified `hatch-pet`
skill under `skills/hatch-pet/` and adds i18n strings across all locales.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(scripts): sync community Codex pets from public catalogs

Adds `pnpm sync:community-pets` which fetches all pets from
codex-pet-share.pages.dev (paginated Supabase Functions API) and
j20.nz/hatchery (single-shot JSON), then writes each one as
`<id>/pet.json` + `<id>/spritesheet.webp` under
`\${CODEX_HOME:-\$HOME/.codex}/pets/`. The existing daemon
`codex-pets` registry already scans that folder, so synced pets
appear under Settings → Pets → Recently hatched and adopt with one
click — no manual upload. Supports --source/--out/--force/--limit
flags and validates magic bytes so HTML error pages never end up
masquerading as `.webp` files.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(daemon): tighten codex-pets validation and document vendoring

- sanitizeId now rejects ids that still contain `..` after collapsing,
  closing a defensive gap on the path-traversal guard for the
  `/api/codex-pets/:id/spritesheet` route.
- listCodexPets emits the sanitised folder name as the public id so the
  download route resolves directly against the on-disk folder, even when
  `manifest.id` differs (manual drops, sanitiser-touched manifests).
- Drop `@ts-nocheck` from `codex-pets.ts`; module is now strict-typed
  with explicit interfaces, an unknown-narrowed JSON.parse path, and a
  `pickString` helper guarding manifest fields one by one.
- Restrict the spritesheet response CORS header to sandboxed-iframe
  callers (Origin: null) instead of unconditional `*`, matching the
  existing raw-file route pattern. Same-origin web traffic does not
  need the header (web proxies `/api/*` through the daemon).
- Add `skills/hatch-pet/README.md` explaining the vendoring trade-off,
  provenance, and re-sync procedure.
- Add `docs/codex-pets.md` covering where pets live, how to populate the
  registry without Codex installed, and the manifest contract.

Generated-By: looper 0.4.0 (runner=fixer, agent=claude-code)

* fix(i18n): add pet.* keys to Hungarian locale

Hungarian locale was added on main after this branch diverged, so the new
pet.* dictionary keys never landed there and tsc -b reports hu's Dict as
incomplete once main is merged in.

Generated-By: looper 0.4.0 (runner=fixer, agent=claude-code)

* feat(web): atlas-driven pet animations + bundled community pets

Builds on the existing pet companion (#296) with a richer animation
loop, a curated set of community pets that ship with the repo, and a
one-click sync into ~/.codex/pets/.

- Atlas-mode rendering: PetSpriteFace can now play the full Codex 8x9
  sprite atlas and swap rows from a JS-driven frame index. PetOverlay
  classifies pointer interactions (idle / hover / drag-direction /
  long-idle waiting) and maps them to the matching atlas row, so the
  pet waves on hover, runs on drag, and falls into a waiting pose
  after 6s of stillness. Single-strip pets keep their existing CSS
  steps() animation, with the steps timing fixed to jump-none so frame
  cells line up on cell boundaries.
- Atlas adoption: PetSettings exposes both "Use full atlas (animated)"
  and "Freeze to this row" — full mode keeps every row for the
  interaction state machine, single-row mode crops one strip via the
  existing canvas helper. New prepareCodexAtlas downscales the atlas
  to a localStorage-friendly PNG while preserving the grid layout.
- Settings tabs: pet sources are now split into Built-in / Custom /
  Community tabs so each origin gets its own dedicated surface.
- Bundled pets: scripts/bake-community-pets.ts seeds a curated set
  (clippit, dario, nyako-shigure, slavik, trump, tux, yelling-dario,
  yorha-sit-2b) into assets/community-pets/. The daemon scans this
  alongside the user's ~/.codex/pets/ root, with user pets winning
  when ids collide. CodexPetSummary gains a `bundled` flag so the UI
  can tag those cards with a "Bundled" pill.
- One-click community sync: daemon-side port of sync-community-pets
  exposed via POST /api/codex-pets/sync. Returns the same
  wrote/skipped/failed/total summary the CLI prints. Web Pet settings
  surface this as a "Download community pets" button under the
  Community tab.
- Avatar dropdown + hide rail: EntryView's avatar button is now a
  small menu (mirrors the project-view AvatarMenu) with toggles for
  hiding/showing the pet rail and opening Settings. PetRail gets a
  matching × button for the same hide flow.
- Locales: 7 new pet.* keys for tabs, sync, hide/show, atlas full
  mode, and the Bundled pill — translated into all 13 supported
  locales.

Typechecks pass across all workspace packages; daemon + web vitest
suites stay green.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(web): bundled-pets built-in tab, ambient atlas animations, and community sync button

The Built-in tab now sources its catalog from the bundled spritesheets
at `assets/community-pets/` instead of the eight emoji placeholders that
felt boring next to the Codex hatch-pet atlases.

- Daemon: `listCodexPets` flags `bundled: true` by curated-set membership
  in `assets/community-pets/`, not by which folder the sprite happened to
  be read from. Previously a fully-synced user inbox preempted every
  bundled id and left the tab empty.
- Settings → Pets → Built-in renders the same sprite-card grid as
  Community, filtered by `bundled: true`, and reuses the existing
  `adoptCodexPet` flow. Community tab filters to non-bundled so the
  curated set never appears twice.
- Community tab gains the long-promised "Download community pets"
  trigger that calls `/api/codex-pets/sync` and shows an inline status
  line for the run summary. Strings already existed in every locale; we
  just plumbed the button.
- `PetOverlay` gets ambient atlas-row choreography — while idle, the
  overlay occasionally swaps `idle` for a random non-idle row (wave /
  hop / look) so the pet doesn't feel frozen. User gestures cancel the
  beat and take over instantly. `pickAmbientRow` lives next to
  `pickAtlasRow` so both row pickers share the fallback discipline.
- One-shot `migrateCustomPetAtlas` heals configs adopted before the
  overlay learned row switching by re-downloading the full spritesheet
  so hover / drag / ambient variety light up on next launch.
- `BUILT_IN_PETS` is now an empty array (the type stays for backwards
  compat); legacy configs whose `petId` still points at an emoji id
  (`mochi`, `pixel`, …) fall back to the user's custom slot in
  `resolveActivePet` so the overlay never renders blank.
- i18n: refresh `pet.tabBuiltInHint` (drop "emoji companions") and add
  `pet.builtInEmpty` across all locales.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-02 23:45:39 +08:00

199 lines
6.2 KiB
JavaScript

#!/usr/bin/env node
// Bake a curated handful of community pets from Codex Pet Share into
// the repo so they ship out-of-the-box without users having to hit the
// "Download community pets" button in Pet settings. The daemon scans
// `assets/community-pets/` alongside `${CODEX_HOME:-$HOME/.codex}/pets/`
// so anything written here shows up in the "Recently hatched" grid as
// a built-in pet that any user can adopt with one click.
//
// Run after editing the `BUNDLED_PETS` list below:
// node --experimental-strip-types scripts/bake-community-pets.ts
//
// Flags:
// --force Re-download pets that already exist on disk.
// --out <dir> Destination folder (defaults to assets/community-pets).
import { mkdir, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const PETSHARE_BASE = 'https://ihzwckyzfcuktrljwpha.supabase.co/functions/v1/petshare';
// Hand-picked pets that should ship with the repo. Add to this list
// (and re-run this script) to bundle a new pet. Keep entries sorted
// alphabetically by id so review diffs stay clean.
const BUNDLED_PETS = [
'clippit',
'dario',
'nyako-shigure',
'slavik',
'trump',
'tux',
'yelling-dario',
'yorha-sit-2b',
];
interface PetShareDetail {
id: string;
displayName: string;
description?: string;
spritesheetPath?: string;
ownerName?: string;
tags?: string[];
spritesheetUrl: string;
}
interface PetShareEnvelope {
pet: PetShareDetail;
}
interface ParsedArgs {
out: string;
force: boolean;
}
function parseArgs(argv: string[]): ParsedArgs {
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, '..');
const args: ParsedArgs = {
out: path.join(repoRoot, 'assets', 'community-pets'),
force: false,
};
for (let i = 2; i < argv.length; i++) {
const flag = argv[i];
if (flag === '--force') {
args.force = true;
continue;
}
if (flag === '--out') {
const value = argv[++i];
if (!value) throw new Error('--out expects a value');
args.out = path.resolve(value);
continue;
}
if (flag === '-h' || flag === '--help') {
console.log('Usage: bake-community-pets.ts [--force] [--out <dir>]');
process.exit(0);
}
throw new Error(`unknown flag: ${flag}`);
}
return args;
}
function extOf(url: string | undefined): 'webp' | 'png' | 'gif' {
if (!url) return 'webp';
const clean = url.split('?')[0] ?? '';
const ext = clean.split('.').pop()?.toLowerCase() ?? 'webp';
if (ext === 'png' || ext === 'gif') return ext;
return 'webp';
}
async function pathExists(p: string): Promise<boolean> {
try {
await stat(p);
return true;
} catch {
return false;
}
}
async function fetchPetDetail(id: string): Promise<PetShareDetail> {
const url = `${PETSHARE_BASE}/api/pets/${encodeURIComponent(id)}`;
const resp = await fetch(url);
if (!resp.ok) {
throw new Error(`fetch ${id}: ${resp.status} ${resp.statusText}`);
}
const data = (await resp.json()) as PetShareEnvelope;
if (!data?.pet?.id) throw new Error(`fetch ${id}: empty pet payload`);
return data.pet;
}
async function downloadBinary(url: string): Promise<Buffer> {
const resp = await fetch(url);
if (!resp.ok) {
throw new Error(`download ${url}: ${resp.status} ${resp.statusText}`);
}
return Buffer.from(await resp.arrayBuffer());
}
function isPlausibleSpritesheet(bytes: Buffer): boolean {
if (bytes.length < 16) return false;
const head = bytes.subarray(0, 12);
const isWebp = head.toString('ascii', 0, 4) === 'RIFF' && head.toString('ascii', 8, 12) === 'WEBP';
const isPng = head.toString('hex', 0, 8) === '89504e470d0a1a0a';
const isGif = head.toString('ascii', 0, 6) === 'GIF87a' || head.toString('ascii', 0, 6) === 'GIF89a';
return isWebp || isPng || isGif;
}
async function bakePet(id: string, outRoot: string, force: boolean): Promise<'wrote' | 'skipped'> {
const detail = await fetchPetDetail(id);
const ext = extOf(detail.spritesheetPath ?? detail.spritesheetUrl);
const dir = path.join(outRoot, id);
const sheetPath = path.join(dir, `spritesheet.${ext}`);
const manifestPath = path.join(dir, 'pet.json');
if (!force && (await pathExists(sheetPath)) && (await pathExists(manifestPath))) {
return 'skipped';
}
const spritesheetUrl = detail.spritesheetUrl.startsWith('http')
? detail.spritesheetUrl
: `${PETSHARE_BASE}${detail.spritesheetUrl}`;
const bytes = await downloadBinary(spritesheetUrl);
if (!isPlausibleSpritesheet(bytes)) {
throw new Error(`${id}: spritesheet is not webp/png/gif`);
}
await mkdir(dir, { recursive: true });
await writeFile(sheetPath, bytes);
// Mirror the manifest shape the daemon's `listCodexPets` reader
// expects, plus an explicit `source` block so the in-repo origin is
// documented next to the bytes (handy when re-baking).
const manifest = {
id: detail.id,
displayName: detail.displayName,
description: detail.description ?? '',
spritesheetPath: `spritesheet.${ext}`,
author: detail.ownerName,
tags: detail.tags ?? [],
source: 'codex-pet-share',
sourceUrl: `https://codex-pet-share.pages.dev/#/pets/${encodeURIComponent(detail.id)}`,
};
await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
return 'wrote';
}
async function main(): Promise<void> {
let args: ParsedArgs;
try {
args = parseArgs(process.argv);
} catch (err) {
console.error(String((err as Error).message ?? err));
process.exit(1);
}
console.log(`Destination: ${args.out}`);
await mkdir(args.out, { recursive: true });
let wrote = 0;
let skipped = 0;
let failed = 0;
for (const id of BUNDLED_PETS) {
try {
const result = await bakePet(id, args.out, args.force);
if (result === 'wrote') {
wrote++;
console.log(`+ ${id}`);
} else {
skipped++;
console.log(`= ${id} (skipped, use --force to re-download)`);
}
} catch (err) {
failed++;
console.error(`! ${id}: ${(err as Error).message ?? err}`);
}
}
console.log(`\nDone. wrote=${wrote} skipped=${skipped} failed=${failed} (total=${BUNDLED_PETS.length})`);
if (failed > 0) process.exitCode = 1;
}
main().catch((err) => {
console.error(err);
process.exit(1);
});