SLOPSHOPPER

pixel-pets

Pixel-art pets above the prompt that react to what Claude and each subagent are doing

bandguardcommandtoastprompttimer
★ 2v0.7.0MITupdated 2026-10-14HenriqueSchroeder/pixel-pets
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pixel-pets
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /pet ⎿ pixel-pets: Pets hidden. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

pixel-pets

English · Português

A pixel-art pet that lives above your Claude Code prompt and reacts to what Claude is doing: it thinks, types while Claude runs commands, reads while Claude reads files, cheers when a turn ends and gets sad when a tool fails. Every subagent Claude starts gets a small pet of its own, in its own color, showing what that agent is doing right now.

Pets are plain JSON files, so you can draw your own or use one someone else made.

pixel-pets: clawd above the prompt while three subagents work

pixel-pets: the dragon in the same scene, flying off to land elsewhere and breathing fire when a long job is done

pixel-pets: the ghost in the same scene, fading out and turning up elsewhere as it strolls

pixel-pets: the fox in the same scene

pixel-pets: the capybara in the same scene, chewing grass as a bird lands on its head

pixel-pets: the kaomoji in the same scene, a little face of text that hums as it strolls

pixel-pets: the wizard in the same scene, drawn in text, vanishing in a swirl of sparkles and brewing potions

pixel-pets: the duck in the same scene, a yellow duckling waddling, flapping its wings and quacking

What it shows

MoodWhenBorrows from
sleepingno turn is running(required)
deepSleepnothing has happened for 10 minutes; from then on spells of 8 to 15 minutes, with a light sleep of 3 to 6 between themsleeping
idleawake with nothing to do, for a while after Claude finishes (see awakeMinutes)thinking
sleepyidle at night, from 22h to 6hidle
tiredidle after 3 hours of work with no break of an hoursleepy
walkingstrolling around while idle and alone; a pack without it never walksidle
watchingyou are typing in the prompt while Claude is idle, or your pointer rests on itreading
wakingfor a moment when a prompt wakes it from a deep sleepthinking
thinkinga turn startedsleeping
typingany other tool, MCP tools includedthinking
runningBashtyping
writingEdit, Writetyping
readingReadthinking
searchingGrep, Glob, WebFetch, WebSearch, LSPreading
supervisingClaude is waiting for its agents, or only thinking while they run, or they still run in the background after the turnthinking
compactingthe conversation is being compactedthinking
sweatinga turn has run for over 2 minutes and Claude is thinking or running a commandthinking
worriedidle after a few failures in a rowsweating
grumpyidle after many failures in a rowsad
proudidle after a streak of turns that went wellhappy
happyfor two seconds after the last agent is done, now and then after a turn of work, or after you allow a permission prompt ("thanks!")sleeping
celebratingfor four seconds after a turn of 5 minutes or more goes well, and on an anniversaryhappy
sadfor two seconds after a tool fails, a turn errors, or you deny a permission prompt ("okay, I won't")sleeping

A pack only has to draw sleeping. Any mood it leaves out borrows the frames of its nearest drawn parent, so running falls back to typing, then thinking, then sleeping.

The pet walks a stage under Claude's line: it strolls while idle, and when subagents start it stays put and they gather around it, each on the side with more free room: on both sides when it stands in the middle, on one when it is in a corner. Each keeps its side until it leaves. When they do not fit where it stands, it walks aside to make room and they join as it gets there. Only a pack that draws walking walks. One that draws main.teleport instead gets about by vanishing and turning up elsewhere, as the slime and the ghost do; a pack with neither stays put at the left. Packs draw their pet facing right; pixel-pets mirrors it to face left, unless the pack says "mirror": false, as the kaomoji does: then it faces you whichever way it goes.

It keeps track of how the session goes. A failed tool or turn worries it and a turn that goes well makes it proud; a failed turn ends a streak of pride. Both fade a point every five minutes, and when it is idle the strongest feeling shows: grumpy, then worried, then tired, then proud, then sleepy at night. Worry and pride last for the session only; tiredness counts your work in every session, as a break is an hour with no prompt in any of them.

It has wants of its own too, for the session. Energy: sleep fills it and work drains it, and a pet low on energy dozes off sooner and rests longer between strolls. Boredom: it builds while nothing happens, and a bored pet gets up from a nap on its own for half a minute to a minute and a half, though never out of a deep sleep: it waits for that sleep to turn light, even hours in. Longing: it builds while you are away, and a pet that misses you strolls near the prompt and greets your first key after half an hour away ("missed you!"), unless a turn is running.

The time of day is your local time. At night it is sleepy and dozes off in half of awakeMinutes. It remembers you across sessions. The day's first sight of you opens with one welcome: an anniversary (a week, a month, 100 days, each year together), "missed you!" after two days or more away, or good morning. /pet also says how long you have been together. Late at night it says so once, whichever session sees you first. A claude -p run does not count as seeing you.

Now and then it says something of its own, in quotes on Claude's line: "hmm…" after 30 seconds of thinking with no tool, a remark on the 20th file read in a turn, on three agents at work at once, on a prompt at night, a sigh when boredom gets it up from a nap, and a word in its sleep now and then. Each at most once a turn, and never two within three minutes.

You can touch it with the pointer. A click pets it ("♥ petted", or "missed you!" if it did), and at work it is glad for a moment while Claude's line still says what runs. A click wakes a dozing pet glad and up for a while; out of a deep sleep it grumbles ("woke me up…") and sleeps on. Four clicks within three seconds annoy it ("hey, stop it!"), and it ignores clicks for three seconds. Resting the pointer on it half a second while it is idle gets a look back. A petting gives way to a reaction already showing, as a failure.

Each subagent gets a mini pet with its type (Explore, Plan, ...) and its current action. When the agent ends, its pet is happy (or sad, if it failed) for a moment and then leaves.

Requirements

  • Claude Code 2.1.287 or later, where mods load by default. Built and tested on 2.1.291.
  • A terminal for the pixel art. The Desktop app's Code tab shows a line of text instead, and the VS Code chat panel and claude -p draw nothing.

Install

In a Claude Code session:

/plugin marketplace add HenriqueSchroeder/pixel-pets
/plugin install pixel-pets@pixel-pets

Or from your shell, then /reload-plugins in any open session:

claude plugin marketplace add HenriqueSchroeder/pixel-pets
claude plugin install pixel-pets@pixel-pets

/pet hides the pets and brings them back. /pet <name> gives the current project a pet of its own, so each of your Claude Code windows can tell which project it is in; it is kept for the project's next sessions too, and /pet default goes back to the one in your settings.

Configure

Run /plugin configure pixel-pets@pixel-pets, or find pixel-pets in /config:

OptionDefaultWhat it does
petcatWhich pet to show, picked from the shipped ones (see below), or custom for your own
customPetYour own pack when pet is custom: a file in ~/.claude/pets/, without .json
languageautoauto follows Claude Code's language setting, then $LANG. Or pick en, pt-BR
awakeMinutes1How long the pet stays awake, strolling around, after Claude finishes, before it falls asleep (half as long at night). 0 sends it straight to sleep
labelLinetrueShows Claude's line above the pet: what it is doing, how long the turn has run and what the pet says. false leaves the pet and its agents alone, one row shorter
agentLabelstrueShows each subagent's type and what it is doing under its mini pet. false leaves the mini pets alone, standing closer, told apart only by their color
livelytrueThe pet lives by its own whims, which drift over days, and by what you pet it for at each time of day, and tires of repeating itself. It wakes up in a temper, waits for you about when you usually turn up, and finds an unusual moment curious. What it learns stays in the plugin's store (learning, familiar, rhythm), never what you write. false makes it the pet it always was
learningExperimentfalseMakes the pet lively only every other day and logs each day to ~/.claude/pixel-pets/learning/, a file per session, to compare the two: each activity shown, each annoyed click, each arrival and how unusual each prompt's moment is

Use another pet

  1. Save the pack as ~/.claude/pets/<name>.json. The file name must match the pack's name.
  2. Pick custom in the pet option and set customPet to <name>.

A pack in ~/.claude/pets/ wins over a shipped one with the same name. If a pack can't be read, pixel-pets says why in a toast and shows the cat.

Shipped pets:

  • cat, the default, which turns side on to walk, and slime, which bounces in place, melts into a puddle in a deep sleep and never walks: it sinks into the floor and wells up somewhere else.
  • dog, which wags its tail, pants, tilts its head when it thinks and turns side on to walk.
  • ghost, which floats instead of walking, says boo now and then, fades as it sleeps and turns up elsewhere with a boo.
  • owl, which blinks slowly and turns its head all the way round.
  • clawd, shown at the top with the dragon, the ghost, the fox and the capybara: the critter on Claude Code's welcome screen, waving its little arms, cheering with both when a long job is done and cracking a whip at its agents to keep them at it. Fan art: not made or endorsed by Anthropic.
  • fox, which sways its brush, pounces on mice under the snow and turns side on to walk.
  • dragon, a big red dragon that breathes fire, counts its hoard and flies off to land elsewhere. It draws no mini pets.
  • capybara, the calmest of them all: it chews grass, lets a bird sit on its head and balances an orange. It draws no mini pets.
  • kaomoji, a little face drawn in text that hums as it strolls and never turns its back on you.
  • wizard, a wizard drawn in text: instead of walking it vanishes in a swirl of sparkles and turns up elsewhere. It brews potions, juggles orbs, plays with its bat and zaps the sky with its staff, startling its agents, who are little apprentices.
  • duck, a yellow duckling that waddles and quacks, splashes in puddles, pecks at crumbs, chases butterflies, trips over its own feet and talks things through with a rubber duck. Its agents are ducklings in their colours.

The cat, slime, dog and owl, idle, thinking, happy and asleep

Draw your own

A pack is a palette and some frames. Each frame is rows of palette letters, and . is see-through:

{
  "$schema": "https://raw.githubusercontent.com/HenriqueSchroeder/pixel-pets/main/schema/pet.schema.json",
  "name": "blob",
  "palette": { "o": "#1a1a1a", "b": "#7cc4f2", "e": "#ffffff" },
  "main": {
    "moods": {
      "sleeping": [
        ["..oooo..", ".obbbbo.", "obbbbbbo", "obobbobo", "obbbbbbo", ".oooooo."]
      ]
    }
  },
  "mini": { "moods": { "working": [[".oo.", "obbo", ".oo."]] } }
}
  • Only sleeping is required. A mood you leave out borrows from its parent, as the table in What it shows lists.
  • Give a mood several frames and they play in a loop at fps frames per second (1–12, default 4). Repeat a frame to hold a pose: at 4 fps, the same frame four times in a row holds it for a second.
  • Every frame of the main pet has the same size, up to 48×32 pixels. The mini pet goes up to 12×12.
  • Two pixel rows fit in one terminal row, so a 12×12 pet takes 12 columns and 6 rows.
  • The mini pet needs working. Its happy and sad, shown when an agent ends, and startled, shown while an action that startles plays, fall back to working.
  • mini.tint (default b) is the letter recolored for each subagent.
  • "mini": false draws no mini pets: while agents work, the pet shows them only by its own supervising. Handy for a wide pet that leaves little room beside it.
  • See every mood of a pack, and what it borrows, in your terminal: npx tsx scripts/preview-pet.ts <name or path>.
  • "mirror": false keeps the pet from flipping when it heads left, for art that looks wrong mirrored, such as letters or a logo.

Draw it in text

Say "style": "ascii" and a frame is rows of text instead: each character takes one terminal cell, and a space is see-through. ink is the color of the text:

{
  "name": "face",
  "style": "ascii",
  "ink": "#f0ece2",
  "palette": { "y": "#ffd23f" },
  "main": {
    "moods": {
      "sleeping": [["      z", "  (-ᴗ-)"], ["     zZ", "  (-ᴗ-)"]],
      "proud": [{ "art": ["      ✧", "  (≖ᴗ≖)"], "color": ["......y", "......."] }]
    }
  },
  "mini": { "moods": { "working": [["(•_•)"]] } }
}
  • To color some characters, give the frame as { "art": [...], "color": [...] }: color has the same rows and widths as art, each character a palette letter, or . for the ink. The palette is optional when everything is in ink.
  • A text row is a whole terminal row, so the pet goes up to 48 columns by 16 rows, and the mini pet up to 12 by 6.
  • Use characters that take one cell: no emoji, CJK or fullwidth letters, which the pack refuses. Some symbols, such as • and °, take two cells in East Asian terminals.
  • mini.tint defaults to ., the ink, so a mini pet drawn all in ink takes its agent's color whole.
  • When it mirrors, pixel-pets swaps the characters that point one way, ( for ), / for \, < for > and the like. A face that still looks wrong flipped wants "mirror": false.

Make it feel alive

A loop alone looks like a machine. Four optional keys under main make the pet unpredictable:

"variants": {
  "thinking": [[["...frame..."], ["...frame..."]]]
},
"transitions": {
  "*>sleeping": [["...yawn..."], ["...eyes droop..."]],
  "sleeping>*": [["...stretch..."]]
},
"actions": {
  "blink": { "frames": [["...eyes shut..."]], "moods": ["thinking", "reading"], "every": [2, 6] }
},
"activities": {
  "yarn": {
    "start": [["...a ball rolls in..."]], "loop": [["...push..."], ["...roll..."]], "end": [["...bat it away..."]],
    "seconds": [15, 40], "moods": ["idle"], "every": [60, 150],
    "label": { "en": "playing with yarn", "pt-BR": "brincando com o novelo" }
  }
}
  • variants: more loops for a mood you draw in moods. One of them, or the mood's own loop, is picked at random each time the mood starts.
  • transitions: frames played once when the mood changes, keyed from>to. Either side may be *. An exact key wins over from>*, which wins over *>to.
  • actions: frames played once at a random moment while the pet is in one of moods, every [min, max] seconds after the last time. Blinks, ear twitches and yawns live here, so the loops can stay calm. An action with startles, a frame counted from 0, makes the agents' mini pets on the side the pet faces play startled from that frame until it ends, always from its first frame: clawd's whip crack.
  • activities: longer plays, timed like an action, in idle or a mood that stands in for it (proud, sleepy, tired, worried, grumpy). start plays once, loop repeats in whole loops for seconds [min, max], then end plays once; start and end are optional. While it plays, label (by language code, one line of up to 40 characters) takes the place of the status words, and the pet neither naps nor strolls off. Any other mood cuts it short, its end unplayed. Up from a nap, the pet soon starts one. Every shipped pet has a few: the cat chases a butterfly, the capybara soaks in a hot spring, the dragon counts its hoard. Up to 8; an activity cannot share a name with an action.
  • In a work mood (thinking, typing, running, writing, reading, searching, supervising) an activity never plays on its own timer. It is what the pet drifts off to after about 20 seconds at the same work, for 8 seconds at most, and the status words keep saying what Claude does. A pack that draws none for that mood still drifts off, borrowing by how the pet feels: an idle activity or action when bored, a tired or sleepy one when its energy runs low, its own watching when it misses you.
  • An action is a whole frame, so keep its face the same as the moods it plays in. The cat has one blink per expression for that reason.
  • A mood holds up to 16 frames; at 4 fps that is 4 seconds.

Give it a voice with speech, at the top level: lines by language code and situation, one picked at random. A language or situation you leave out says the default line.

"speech": {
  "en": { "longThink": ["mrrp… hmm"], "manyReads": ["so many files… mrow!"] },
  "pt-BR": { "longThink": ["mrrp… hmm"] }
}

The situations are longThink, manyReads, manyAgents, lateNight, bored and dreaming. Up to 8 lines each, one line of up to 40 characters.

A pet that does not walk can teleport: give main a teleport with vanish, played where it stands, and appear, played where it lands, frames like any other. It is how it strolls and how it makes room for agents.

Give it a nature with personality, at the root of the pack: three traits from 0 to 1, each the usual 0.5 when left out. energetic tires slower, curious gets bored and up from a nap sooner (0 never does), affectionate misses you sooner (0 never does). The dog is { "energetic": 0.8, "curious": 0.6, "affectionate": 0.9 }; the slime, lazy, is { "energetic": 0.2, "curious": 0.3, "affectionate": 0.6 }.

The schema gives your editor completion and checks. To share a pet, see CONTRIBUTING.md.

Check what it does before you install

A mod runs with your permissions. Clone this repository and list every event it hooks and every call it makes:

claude plugin validate ./pixel-pets

pixel-pets reads your pet packs, Claude Code's language setting and the HOME and LANG variables, and draws above the prompt. It never writes files, runs commands, or uses the network.

Limitations

  • The pixel art needs a terminal. Other surfaces get a line of text.
  • Touching the pet needs a terminal that reports the pointer to Claude Code. Elsewhere it only shows.
  • A pet pack is read when the plugin loads. After editing one, run /reload-plugins.
  • The mods API is in early access and can change between Claude Code releases.

Development

claude --plugin-dir .            # try it in a session
claude plugin validate .         # manifest, hooks and calls
claude plugin test .             # tests/
npx tsx scripts/check-pets.ts    # every pack in pets/
npx tsc -p .                     # types (after one --plugin-dir run lays them)

License

MIT

Source 22 files
hooks/register.tsx 1214 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer, ToolCallInput } from 'claude-code'
3
4import type { Activity, AgentPet, Feelings, Label, MiniMood, Mood, Reaction, Situation, Traits } from '../types'
5import { alertness, drift, engaged, misses, paceOf, rested, seen, stirred, stirs, urgeOf, USUAL } from './drives'
6import type { Drives, State } from './drives'
7import { calm, cheer, feel, idleMood, isNight, nightOf } from './feelings'
8import { pickLocale, say } from './i18n'
9import type { Locale, Text } from './i18n'
10import type { Bandit } from '../learn/bandit'
11import { novelty, see } from '../learn/recall'
12import {
13  annoyed,
14  armOf,
15  asBandit,
16  asFamiliarity,
17  CREDIT_MS,
18  daypartOf,
19  FAMILIAR_HALF_LIFE_MS,
20  KNOWS,
21  logLine,
22  momentCode,
23  ODD,
24  ODD_GAP_MS,
25  petted,
26  pickFor,
27  settle,
28  tempered,
29  temperOf,
30} from './learning'
31import type { Shown } from './learning'
32import { asVisit, daysBetween, welcome } from './memory'
33import type { Visit } from './memory'
34import { activityIn, step } from './motion'
35import type { Motion } from './motion'
36import { ANNOY_MS, gazes, hover, leave, press, untouched } from './gestures'
37import type { Poke, Sleep, Touch } from './gestures'
38import { DEFAULT_PET, packPaths, parsePack } from './pack'
39import type { Pack } from './pack'
40import { artOf, encode, facingFrame, sizeOf } from './render'
41import { arrived, asRhythm, AWAY_MS, expects, PATIENCE_MS } from './rhythm'
42import type { Rhythm } from './rhythm'
43import { FIRST_NAP_MS, isDeep } from './sleep'
44import { LONG_THINK_MS, MANY_AGENTS, MANY_READS, lineFor, maySpeak, quiet, spoke } from './speech'
45import type { Speaker } from './speech'
46import type { Art } from './touch'
47import { EMPTY_STAGE, faceFor, holdFacing, moveOnStage, sideIn } from './walk'
48import type { Held, Side, Stage } from './walk'
49
50const asleep: Activity = { mood: 'sleeping', label: { text: 'sleeping', detail: '' } }
51
52const activity = atom({ plugin: 'pixel-pets', key: 'activity' } as const, asleep)
53const reaction = atom({ plugin: 'pixel-pets', key: 'reaction' } as const, null as Reaction | null)
54const override = atom({ plugin: 'pixel-pets', key: 'override' } as const, null as Activity | null)
55const turnStartedAt = atom({ plugin: 'pixel-pets', key: 'turnStartedAt' } as const, null as number | null)
56const lastActiveAt = atom({ plugin: 'pixel-pets', key: 'lastActiveAt' } as const, null as number | null)
57const typingAt = atom({ plugin: 'pixel-pets', key: 'typingAt' } as const, null as number | null)
58const agents = atom({ plugin: 'pixel-pets', key: 'agents' } as const, [] as AgentPet[])
59const isHidden = atom({ plugin: 'pixel-pets', key: 'isHidden' } as const, false)
60const feelings = atom({ plugin: 'pixel-pets', key: 'feelings' } as const, calm as Feelings)
61const restedAt = atom({ plugin: 'pixel-pets', key: 'restedAt' } as const, null as number | null)
62
63const REACTION_MS = 2000
64const WAKING_MS = 1200
65const LEAVING_MS = 1500
66const LONG_TURN_MS = 2 * 60_000
67// A break this long rests it, as far as getting tired goes.
68const BREAK_MS = 60 * 60_000
69const GREETING_MS = 2500
70// A turn this long that goes well earns a bigger, longer celebration.
71const LONG_WIN_MS = 5 * 60_000
72const CELEBRATION_MS = 4000
73// How long a line it says stays on Claude's line.
74const SPEECH_MS = 4000
75// How long the pet keeps watching the prompt after the last key.
76const TYPING_MS = 2000
77// How long it stays up when boredom gets it out of a nap, in seconds.
78const STIR_SECONDS: [number, number] = [30, 90]
79// How long into a nap it may talk in its sleep, in minutes.
80const DREAM_MINUTES: [number, number] = [10, 20]
81const AGENT_SLOT = 20
82// Room kept for the " +N" that stands for agents with no slot.
83const OVERFLOW_COLUMNS = 4
84const MAX_AGENTS = 6
85// While only the pets' frames move, the clock repaints them and redraws the band
86// in full only this often, in seconds, for what changes with time alone (dozing
87// off, a long turn's minutes): once a second awake, every 5 asleep.
88const REDRAW_AWAKE_S = 1
89const REDRAW_ASLEEP_S = 5
90
91// What the band shows on a tick: `layout` stands for all of it but the pets'
92// drawings: the main pet's `art` (`main` its key) and the agents' Raster cells by key.
93type Shot = { layout: string; main: string; art: Art; rasters: Record<string, string> }
94// The band as last drawn: what it showed, how to play it a tick on, and the tick
95// by which something it shows runs out.
96type Scene = { requestId: string; shot: Shot; play: () => Shot; redrawAt: number; isAsleep: boolean }
97
98// One body color per subagent, picked in spawn order.
99const AGENT_COLORS = [0x7cc4f2, 0x9bd57a, 0xc69af2, 0xf2d16b, 0xf28fb0, 0x6fd8c8]
100
101const SEARCHERS = new Set(['Grep', 'Glob', 'WebFetch', 'WebSearch', 'LSP'])
102
103// Waiting on something slow: these turn into sweating when a turn runs long.
104const PATIENT: readonly Mood[] = ['thinking', 'running', 'supervising']
105
106const short = (text: string, max = 32) => (text.length > max ? `${text.slice(0, max - 1)}…` : text)
107const basename = (path: string) => path.split('/').pop() ?? path
108const label = (text: Text, detail = ''): Label => ({ text, detail })
109const stillHere = (list: AgentPet[], now: number) => list.filter(pet => pet.leaving === undefined || pet.leaving.until > now)
110const stirFor = () => (STIR_SECONDS[0] + (STIR_SECONDS[1] - STIR_SECONDS[0]) * Math.random()) * 1000
111// A reaction still showing that a new one waits for: one the pointer did gives way.
112const holds = (live: Reaction | null, now: number) => live !== null && live.until > now && live.byTouch !== true
113
114// What the pointer posted: the kinds of what it did, in order. Code sent it, so it is checked.
115const pointerEvents = (data: unknown): string[] => {
116  const events = (data as { events?: unknown } | null)?.events
117  return Array.isArray(events) ? events.filter((one): one is string => typeof one === 'string') : []
118}
119
120const reactionTo = (poke: Exclude<Poke, 'ignore'>, missed: boolean, now: number): Reaction => {
121  const until = now + REACTION_MS
122  switch (poke) {
123    case 'pet':
124      return { mood: 'happy', label: label(missed ? 'missedYou' : 'petted'), until, byTouch: true }
125    case 'wake':
126      return { mood: 'happy', label: label('wakingUp'), until, byTouch: true }
127    case 'rouse':
128      return { mood: 'grumpy', label: label('rudeAwakening'), until, byTouch: true }
129    case 'annoy':
130      return { mood: 'grumpy', label: label('annoyed'), until: now + ANNOY_MS, byTouch: true }
131  }
132}
133
134const describe = (e: ToolCallInput): Activity => {
135  switch (e.tool) {
136    case 'Bash':
137      return { mood: 'running', label: label('running', short(e.command)) }
138    case 'Edit':
139    case 'Write':
140      return { mood: 'writing', label: label('writing', basename(e.file_path)) }
141    case 'Read':
142      return { mood: 'reading', label: label('reading', basename(e.file_path)) }
143    case 'Agent':
144      return { mood: 'supervising', label: label('waitingForAgents') }
145  }
146  const tool = String(e.tool)
147  return SEARCHERS.has(tool)
148    ? { mood: 'searching', label: label('searching', tool) }
149    : { mood: 'typing', label: label('using', short(tool, 24)) }
150}
151
152const callKey = (agentId: string | undefined, tool: string) => `${agentId ?? 'main'}:${tool}`
153
154// The engine's words for a call the person said no to: there is no flag for it.
155const isDenial = (ran: { isError?: boolean; result?: unknown }) =>
156  ran.isError === true && typeof ran.result === 'string' && ran.result.includes("doesn't want to proceed")
157
158const reason = (error: unknown) => (error instanceof Error ? error.message : String(error))
159
160// The language and the pack are read once per module load: a settings change
161// reloads the module, and with it these.
162let choosing: Promise<Locale> | undefined
163// Kept with the name it is for: a draw can ask before `session.start` has read the
164// project's own pet, and the settings' pet must not stand in for it after.
165let loading: { name: string; pack: Promise<Pack> } | undefined
166
167function localeOf($: EngineInterface, choice: string) {
168  choosing ??= (async () => {
169    const settings = await $.settings.read()
170    return pickLocale(choice, settings.language, await $.env.get('LANG'))
171  })()
172  return choosing
173}
174
175// The first pack found wins; a broken or missing one is why not, in words.
176async function findPack($: EngineInterface, name: string, locale: Locale): Promise<Pack | string> {
177  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
178  const paths = packPaths(name, home, $.plugin.root)
179  let problem = say(locale, paths === undefined ? 'invalidName' : 'notFound', name)
180
181  for (const path of paths ?? []) {
182    let text: string
183    try {
184      text = await $.fs.read(path)
185    } catch {
186      continue
187    }
188    try {
189      return parsePack(JSON.parse(text))
190    } catch (error) {
191      problem = `${path}: ${reason(error)}`
192      break
193    }
194  }
195  return problem
196}
197
198// A broken or missing pack falls back to the shipped default, and the toast says why.
199async function readPack($: EngineInterface, name: string, locale: Locale): Promise<Pack> {
200  const found = await findPack($, name, locale)
201  if (typeof found !== 'string') return found
202  const fallback = parsePack(JSON.parse(await $.fs.read(`${$.plugin.root}/pets/${DEFAULT_PET}.json`)))
203  $.ui.toast(say(locale, 'fallback', found))
204  return fallback
205}
206
207function packOf($: EngineInterface, name: string, locale: Locale) {
208  if (loading?.name !== name) loading = { name, pack: readPack($, name, locale) }
209  return loading.pack
210}
211
212// `/pet <name>` picks a project's own pet, kept by project root; `/pet default`
213// goes back to the one in the settings.
214const DEFAULT_ARG = 'default'
215
216async function projectPets($: EngineInterface): Promise<Record<string, string>> {
217  const kept = await $.store.get('projectPets')
218  return typeof kept === 'object' && kept !== null && !Array.isArray(kept) ? (kept as Record<string, string>) : {}
219}
220
221// This session's project's pet, if one was picked.
222async function projectPet($: EngineInterface) {
223  try {
224    const name = (await projectPets($))[await $.session.root()]
225    return typeof name === 'string' ? name : undefined
226  } catch {
227    return undefined
228  }
229}
230
231async function keepProjectPet($: EngineInterface, root: string, name: string | undefined) {
232  const { [root]: _, ...others } = await projectPets($)
233  await $.store.set('projectPets', name === undefined ? others : { ...others, [root]: name })
234}
235
236const hourOf = (now: number) => new Date(now).getHours()
237const anniversary = (days: number): Label =>
238  days === 7
239    ? label('aWeekTogether')
240    : days === 30
241      ? label('aMonthTogether')
242      : days === 365
243        ? label('aYearTogether')
244        : days % 365 === 0
245          ? label('yearsTogether', String(days / 365))
246          : label('daysTogether', String(days))
247
248// Notes that the person is here now, and when they first met. Returns the visit
249// before this one. With no store it remembers nothing, and holds nothing up.
250async function remember($: EngineInterface, now: number) {
251  try {
252    const visit = asVisit(await $.store.get('visit'))
253    await $.store.set('visit', { metAt: visit?.metAt ?? now, lastSeenAt: now })
254    return visit
255  } catch {
256    return undefined
257  }
258}
259
260// How the day's first sight of the person goes: an anniversary, missing them, or
261// good morning. Checked when a session opens and on each prompt, so a session left
262// open overnight still greets the morning. `before` is the visit before this one.
263async function greet($: EngineInterface, now: number, before: Visit | undefined) {
264  const hello = welcome(before, now, hourOf(now))
265  if (hello === undefined) return
266  const until = now + GREETING_MS
267  const shown: Reaction =
268    hello.kind === 'anniversary'
269      ? { mood: 'celebrating', label: anniversary(hello.days), until: now + CELEBRATION_MS }
270      : hello.kind === 'missedYou'
271        ? { mood: 'happy', label: label('missedYou'), until }
272        : { mood: 'waking', label: label('goodMorning'), until }
273  await update($, reaction, () => shown)
274}
275
276// When the person came back from their last break, across every session: an hour
277// with no prompt in any of them rests the pet. `before` is the visit before this one.
278async function restedSince($: EngineInterface, now: number, before: Visit | undefined) {
279  try {
280    const kept = await $.store.get('restedAt')
281    if (typeof kept === 'number' && before !== undefined && now - before.lastSeenAt < BREAK_MS) return kept
282    await $.store.set('restedAt', now)
283  } catch {
284    // No store: rested as of now, as a session that remembers nothing.
285  }
286  return now
287}
288
289// Whether no session has said the late-night line yet tonight.
290async function quietTonight($: EngineInterface, now: number) {
291  try {
292    return (await $.store.get('lateNight')) !== nightOf(now)
293  } catch {
294    return true
295  }
296}
297
298async function saidTonight($: EngineInterface, now: number) {
299  try {
300    await $.store.set('lateNight', nightOf(now))
301  } catch {
302    // No store: this session alone keeps it.
303  }
304}
305
306// The person is at the prompt: the day's welcome, and their rest, from the visit
307// before, which it returns.
308async function atThePrompt($: EngineInterface, now: number) {
309  const before = await remember($, now)
310  await greet($, now, before)
311  const since = await restedSince($, now, before)
312  await update($, restedAt, () => since)
313  return before
314}
315
316// "Together for 12 days", for /pet; nothing when it has no memory of the person.
317async function together($: EngineInterface, locale: Locale) {
318  try {
319    const visit = asVisit(await $.store.get('visit'))
320    if (visit === undefined) return ''
321    const days = daysBetween(visit.metAt, await $.clock.now())
322    const said = days === 0 ? say(locale, 'justMet') : days === 1 ? say(locale, 'togetherADay') : say(locale, 'togetherDays', String(days))
323    return ` ${said.charAt(0).toUpperCase()}${said.slice(1)}.`
324  } catch {
325    return ''
326  }
327}
328
329// What it learned of the person's taste, shared by every session, and the seed that
330// fixes its whims and tempers (and, in the experiment, which days are lively). The
331// first load picks the seed. With no store it learns nothing and lives as it always did.
332type Learning = { seed: number; bandit: Bandit }
333
334async function loadLearning($: EngineInterface): Promise<Learning | undefined> {
335  try {
336    const kept = (await $.store.get('learning')) as { seed?: unknown; bandit?: unknown } | undefined
337    if (typeof kept?.seed === 'number') return { seed: kept.seed, bandit: asBandit(kept.bandit) }
338    await $.store.set('learning', { seed: Math.floor(Math.random() * 2 ** 32), bandit: {} })
339    // Read back: a session starting at the same moment may have set its own seed last.
340    const settled = (await $.store.get('learning')) as { seed?: unknown; bandit?: unknown } | undefined
341    return typeof settled?.seed === 'number' ? { seed: settled.seed, bandit: asBandit(settled.bandit) } : undefined
342  } catch {
343    return undefined
344  }
345}
346
347// The experiment's log, a line per event, where the person can read and delete it:
348// a file per session, so sessions open at once never write over each other's lines.
349// With no experiment there is no file name, and nothing is logged.
350async function logPath($: EngineInterface, name: string) {
351  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
352  return home === undefined ? undefined : `${home}/.claude/pixel-pets/learning/${name}.jsonl`
353}
354
355// No append in $.fs: the session's file is read and written again, which a
356// session's few hundred lines afford.
357async function appendLog($: EngineInterface, name: string | undefined, lines: string[]) {
358  const path = name === undefined ? undefined : await logPath($, name)
359  if (path === undefined || lines.length === 0) return
360  // A read that fails stops the write, rather than write the lines over what was there.
361  const text = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
362  await $.fs.write(path, text + lines.map(line => `${line}\n`).join(''))
363}
364
365// What is past its minute counts for the bandit, read again from the store as
366// another session may have learned meanwhile, and goes in the log.
367// ponytail: two sessions settling at the same moment may lose one's update; take a
368// lock in the store if the log shows tallies short of its lines.
369// With no store it learns nothing, but the log still gets its lines.
370async function keepLearned($: EngineInterface, name: string | undefined, done: Shown[]) {
371  let learned: Learning | undefined
372  try {
373    const kept = await loadLearning($)
374    if (kept !== undefined) {
375      learned = { ...kept, bandit: settle(kept.bandit, done, Infinity).bandit }
376      await $.store.set('learning', learned)
377    }
378  } catch {
379    learned = undefined
380  }
381  await appendLog($, name, done.map(logLine))
382  return learned
383}
384
385// How unusual a prompt's moment is, before it becomes a little more familiar; and
386// how many of the person's moments it knew by then.
387async function noteMoment($: EngineInterface, name: string | undefined, code: number[], now: number, seed: number) {
388  const { seen: known, cells } = asFamiliarity(await $.store.get('familiar'))
389  const news = novelty(cells, code, now, FAMILIAR_HALF_LIFE_MS)
390  see(cells, code, now, FAMILIAR_HALF_LIFE_MS)
391  await $.store.set('familiar', { seen: known + 1, cells })
392  const line = { kind: 'novelty', at: now, arm: armOf(seed, now), temper: temperOf(seed, now), daypart: daypartOf(hourOf(now)), novelty: news }
393  await appendLog($, name, [JSON.stringify(line)])
394  return { news, known }
395}
396
397async function loadRhythm($: EngineInterface) {
398  try {
399    return asRhythm(await $.store.get('rhythm'))
400  } catch {
401    return {}
402  }
403}
404
405// The person turned up: one more arrival at this half hour of the day.
406async function noteArrival($: EngineInterface, name: string | undefined, now: number) {
407  const rhythm = arrived(await loadRhythm($), now)
408  await $.store.set('rhythm', rhythm)
409  await appendLog($, name, [JSON.stringify({ kind: 'arrival', at: now })])
410  return rhythm
411}
412
413// Clears the override only if it is still the one this hook set.
414async function release($: EngineInterface, mood: Mood) {
415  await update($, override, current => (current?.mood === mood ? null : current))
416}
417
418export const register: Register = (on, options) => {
419  // The picker names a shipped pet, or `custom` for the person's own pack named in `customPet`.
420  const picked = options.pet === 'custom' ? options.customPet : options.pet
421  const configured = typeof picked === 'string' && picked !== '' ? picked : DEFAULT_PET
422  // The project's own pet, if `/pet <name>` picked one, else the settings'.
423  let petName = configured
424  // The pack the frame clock plays, the clock, and a way to start it again at another pack's pace.
425  let playing: Pack | undefined
426  let timer: Timer | undefined
427  let restartClock = () => {}
428  const language = typeof options.language === 'string' ? options.language : 'auto'
429  // false: the band is the stage alone, without Claude's line above it.
430  const showsLine = options.labelLine !== false
431  // false: each agent is its mini pet alone, without its name and words under it.
432  const showsAgentLabels = options.agentLabels !== false
433  // On (the default), the pet lives by its own whims and what it learns of the
434  // person; off, it lives as it always did, and keeps nothing of them.
435  const isAlive = options.lively !== false
436  // The experiment: lively and usual days in turn, each logged, to compare them.
437  const experiments = isAlive && options.learningExperiment === true
438  let learning: Learning | undefined
439  // When the person usually turns up; what it did lately, the latest first; and
440  // when it last found a moment odd.
441  let rhythm: Rhythm = {}
442  let lately: string[] = []
443  let oddAt = 0
444  // Loaded once, at session.start or, after a reload (a settings change), at the next draw.
445  let hasLoaded = false
446  // Today it lives by what it learned and its whims, rather than as it always did:
447  // every day, but in the experiment only on its lively days.
448  const isLively = (now: number) => learning !== undefined && (!experiments || armOf(learning.seed, now) === 'learned')
449  // Away a while and about to turn up, as they usually do now: it waits for them,
450  // until it has greeted them or run out of patience. `waitingFrom` is when it began
451  // to wait through the pause that began at its `idleSince`.
452  let waitingFrom: { idleSince: number; at: number } | undefined
453  const waitsFor = (idleSince: number | null, now: number) => {
454    if (idleSince === null || !isLively(now) || now - idleSince < AWAY_MS || !expects(rhythm, now) || wokeForThem(idleSince)) return false
455    if (waitingFrom?.idleSince !== idleSince) waitingFrom = { idleSince, at: now }
456    return now - waitingFrom.at < PATIENCE_MS
457  }
458  // Activities shown in the last minute, waiting for a pet; and the learned pick last made.
459  let recent: Shown[] = []
460  let lastPick: { activity: string; propensity: number } | undefined
461  // The store and the log are written one change at a time, in order, the log to
462  // a file of this session's own: its day, and a few random letters.
463  let writing = Promise.resolve()
464  let logName: string | undefined
465  const logNameAt = (now: number) =>
466    experiments ? (logName ??= `${new Date(now).toISOString().slice(0, 10)}-${Math.random().toString(36).slice(2, 8)}`) : undefined
467  const awakeMs = (typeof options.awakeMinutes === 'number' && options.awakeMinutes >= 0 ? options.awakeMinutes : 1) * 60_000
468  let frame = 0
469  // What the main pet is playing and where it stands, between draws; a reload starts them fresh.
470  let motion: Motion | undefined
471  // Where it stands and each agent's side, kept so none hops over when another leaves.
472  let stage: Stage = EMPTY_STAGE
473  // A full redraw costs Claude Code far more than repainting a Raster, and every
474  // open session pays it. The band keeps how to play itself a tick on: the clock
475  // plays it, repaints the agents' Rasters whose cells changed, leaves the main
476  // pet's frame for its Client to ask for, and redraws in full only when anything
477  // else would change (a step, its words), when something it shows runs out, and
478  // now and then for what changes with time alone. While the pet is hidden the
479  // clock redraws nothing, as showing it again redraws.
480  let scene: Scene | null = null
481  // The main pet's frame its Client has, by `Shot.main`.
482  let sentMain: string | null = null
483  // What the pointer has done to it, and whether it was looking back as last drawn.
484  let touched: Touch = untouched
485  let gazing = false
486  // With no Client drawn, no `leave` comes: the pointer counts as gone.
487  const letGo = () => {
488    touched = leave(touched)
489    gazing = false
490  }
491  let isOff = false
492  // The tool call running for each agent and tool, so a permission prompt (which
493  // names only those) finds the call it is for; and the calls that asked.
494  // ponytail: two same-named calls of one agent at once share a key; the later wins.
495  const openCalls = new Map<string, string>()
496  const asked = new Set<string>()
497  // Only a session with a person at the prompt counts as seeing them: a `claude -p`
498  // run must not spend the day's welcome.
499  let isInteractive = false
500  // What it said lately and what it is saying now; a reload starts them fresh.
501  let speaker: Speaker = quiet
502  let saying: { text: string; until: number } | null = null
503  // Since when the main loop has run no tool (null while one runs), and its tools and reads this turn.
504  let thinkingSince: number | null = null
505  let toolsThisTurn = 0
506  let readsThisTurn = 0
507  // An agent finished since the pet last cheered: the turn that reports it is worth a cheer.
508  let agentsDone = false
509  // The night it last said it was getting late, by its evening's date.
510  let saidNight: string | null = null
511  // What it wants, from the first draw on, and what the band showed last, which is
512  // what it has been up to since; plus until when it is up on its own.
513  let drives: Drives | undefined
514  // How the pet is made, from its pack once the band has drawn it.
515  let traits: Traits = USUAL
516  let lastState: State = 'awake'
517  let stirredUntil = 0
518  // The way it faced as the action it plays began, kept until it ends.
519  let heldFacing: Held
520  // When it last woke up glad at the person's first key after a long while away,
521  // and whether that was since it went idle at `idleSince`.
522  let gladAt: number | null = null
523  // When it talks in its sleep next; null until it naps after a turn. Up on its own
524  // for a moment, it keeps the time, or a long pause would leave it no time to dream.
525  let dreamAt: number | null = null
526  const wokeForThem = (idleSince: number | null) => gladAt !== null && idleSince !== null && gladAt >= idleSince
527  // Busy with an activity, it is up whatever the time: sleep would cut it short.
528  const isPlaying = () => activityIn(motion, frame) !== undefined
529  // It dozes off sooner at night, and when it runs low on energy; not drawn yet, it is rested.
530  const howLongAwake = (now: number) =>
531    (isNight(hourOf(now)) ? awakeMs / 2 : awakeMs) * (drives === undefined ? 1 : alertness(drift(drives, now, lastState, traits)))
532  // Dozed off a while back and in a deep spell of the pause that began at `idleSince`, and
533  // not up on its own nor glad to see them.
534  const isFastAsleep = (idleSince: number | null, now: number) =>
535    idleSince !== null &&
536    now - idleSince > howLongAwake(now) + FIRST_NAP_MS &&
537    now >= stirredUntil &&
538    !isPlaying() &&
539    isDeep(idleSince, now - idleSince) &&
540    !wokeForThem(idleSince)
541  // Long idle, it naps, unless up on its own or busy with an activity; `isDozing`
542  // also unless bored enough to get up.
543  const isDrowsy = (idleSince: number | null, now: number) => {
544    const awakeFor = howLongAwake(now)
545    // Unknown idle time (nothing has run yet) counts as a plain nap.
546    const idleFor = idleSince === null ? awakeFor + 1 : now - idleSince
547    return idleFor > awakeFor && now >= stirredUntil && !isPlaying()
548  }
549  const isDozing = (idleSince: number | null, now: number) =>
550    isDrowsy(idleSince, now) && !(drives !== undefined && stirs(drift(drives, now, lastState, traits)))
551  // Brings the drives up to `now` before `change` touches them.
552  const touch = (now: number, change: (settled: Drives) => Drives) => {
553    if (drives !== undefined) drives = change(drift(drives, now, lastState, traits))
554  }
555
556  // Says the line for `situation`, unless it spoke too lately or already did this turn.
557  const speak = (situation: Situation, now: number, pack: Pack, locale: Locale) => {
558    if (!maySpeak(speaker, situation, now)) return false
559    speaker = spoke(speaker, situation, now)
560    saying = { text: lineFor(pack.speech, locale.code, situation, say(locale, situation), Math.random), until: now + SPEECH_MS }
561    return true
562  }
563
564  on('session.start', async ($, e, next) => {
565    const locale = await localeOf($, language)
566    await $.command.register({ name: 'pet', description: say(locale, 'commandDescription'), argumentHint: '[name | default]' })
567    petName = (await projectPet($)) ?? configured
568    playing = await packOf($, petName, locale)
569    if (isAlive && !hasLoaded) {
570      hasLoaded = true
571      learning = await loadLearning($)
572      rhythm = await loadRhythm($)
573    }
574    const now = await $.clock.now()
575    await update($, lastActiveAt, () => now)
576    const tick = () => {
577      const pack = playing
578      frame += 1
579      if (isOff || pack === undefined) return
580      const last = scene
581      const every = pack.fps * (last?.isAsleep === true ? REDRAW_ASLEEP_S : REDRAW_AWAKE_S)
582      // With no stage of its own drawn (a survey, or a line of text), there is nothing to play.
583      if (last === null) {
584        if (frame % every === 0) $.ui.invalidate('ui.render')
585        return
586      }
587      if (frame % every === 0 || frame >= last.redrawAt) {
588        $.ui.invalidate('ui.render')
589        return
590      }
591      const shot = last.play()
592      if (shot.layout !== last.shot.layout) {
593        $.ui.invalidate('ui.render')
594        return
595      }
596      // The agents' Rasters are repainted here; the main pet's Client asks for its frame.
597      const changed = Object.entries(shot.rasters).filter(([key, cells]) => last.shot.rasters[key] !== cells)
598      last.shot = shot
599      if (changed.length === 0) return
600      // Refused when the band is no longer last as it was: redraw it in full.
601      void Promise.all(changed.map(([key, cells]) => $.ui.blit({ requestId: last.requestId, key, cells })))
602        .then(done => done.some(one => one.deny !== undefined))
603        .catch(() => true)
604        .then(refused => {
605          if (refused) $.ui.invalidate('ui.render')
606        })
607    }
608    restartClock = () => {
609      timer?.cancel()
610      timer = $.clock.every(Math.round(1000 / (playing?.fps ?? 4)), tick)
611    }
612    restartClock()
613    isInteractive = e.isInteractive
614    if (isInteractive) {
615      const before = await atThePrompt($, now)
616      if (learning !== undefined && (before === undefined || now - before.lastSeenAt >= AWAY_MS)) {
617        const name = logNameAt(now)
618        writing = writing.then(() => noteArrival($, name, now).then(kept => void (rhythm = kept))).catch(() => {})
619      }
620    } else await update($, restedAt, at => at ?? now)
621    return next(e)
622  })
623
624  // The main pet's Client hands over what the pointer did each tick, and asks for
625  // its frame: it gets the one the clock played last, when it has not had it yet.
626  on('ui.message', async ($, e, next) => {
627    if (e.element !== 'touch') return next(e)
628    const now = await $.clock.now()
629    const events = pointerEvents(e.data)
630    // How a click finds it: at work or watching agents it is awake whatever the time.
631    let sleep: Sleep = 'awake'
632    if (events.includes('down')) {
633      const idleSince = await read($, lastActiveAt)
634      const isBusy = (await read($, turnStartedAt)) !== null || stillHere(await read($, agents), now).some(one => one.leaving === undefined)
635      // Up waiting for them, it is awake whatever the time.
636      sleep = isBusy || waitsFor(idleSince, now) ? 'awake' : isFastAsleep(idleSince, now) ? 'deep' : isDozing(idleSince, now) ? 'dozing' : 'awake'
637    }
638    let poke: Poke = 'ignore'
639    for (const event of events) {
640      if (event === 'down') {
641        const pressed = press(touched, now, sleep)
642        touched = pressed.touch
643        if (pressed.poke !== 'ignore') poke = pressed.poke
644      } else if (event === 'leave') touched = leave(touched)
645      else if (event === 'enter' || event === 'move') touched = hover(touched, now)
646    }
647    if (learning !== undefined && poke === 'pet') recent = petted(recent, now)
648    if (learning !== undefined && poke === 'annoy') {
649      recent = annoyed(recent, now)
650      const line = JSON.stringify({ kind: 'annoy', at: now, arm: isLively(now) ? 'learned' : 'hand' })
651      const name = logNameAt(now)
652      writing = writing.then(() => appendLog($, name, [line])).catch(() => {})
653    }
654    if (poke !== 'ignore') {
655      // Any touch is the person being there; woken glad, it stays up a while.
656      let missed = false
657      touch(now, settled => {
658        missed = misses(settled)
659        return seen(settled)
660      })
661      if (poke === 'wake') stirredUntil = now + stirFor()
662      const shown = reactionTo(poke, missed, now)
663      await update($, reaction, live => (holds(live, now) ? live : shown))
664      $.ui.invalidate('ui.render')
665    }
666    if (gazes(touched, now) !== gazing) {
667      gazing = !gazing
668      $.ui.invalidate('ui.render')
669    }
670    const shot = scene?.shot
671    if (shot === undefined || shot.main === sentMain) return {}
672    sentMain = shot.main
673    return { props: shot.art }
674  })
675
676  on('command.run', { command: 'pet' }, async ($, e) => {
677    const locale = await localeOf($, language)
678    const asked = (e.args ?? '').trim()
679    if (asked === '') {
680      const hidden = await update($, isHidden, value => !value)
681      return { text: `${say(locale, hidden ? 'hidden' : 'shown')}${await together($, locale)}` }
682    }
683
684    // A pet asked by name is tried before it is kept: one that does not load leaves
685    // things as they were. `default` always lets go of the project's own, even when
686    // the settings' pet is broken and falls back to the shipped one.
687    const isDefault = asked === DEFAULT_ARG
688    const name = isDefault ? configured : asked
689    const found = isDefault ? await readPack($, name, locale) : await findPack($, name, locale)
690    if (typeof found === 'string') return { text: say(locale, 'projectPetFailed', found) }
691    try {
692      await keepProjectPet($, await $.session.root(), isDefault ? undefined : name)
693    } catch {
694      // No store: the pet changes for this session alone.
695    }
696    petName = name
697    loading = { name, pack: Promise.resolve(found) }
698    playing = found
699    motion = undefined
700    scene = null
701    restartClock()
702    $.ui.invalidate('ui.render')
703    return { text: say(locale, isDefault ? 'projectPetDefault' : 'projectPet', name) }
704  })
705
706  // The pet looks at the prompt while the person types in it, glad at the first key
707  // after a long while away, unless a turn or something else is showing.
708  on('prompt.edit', async ($, e, next) => {
709    const now = await $.clock.now()
710    await update($, typingAt, () => now)
711    // Waiting up for them, it is glad they came as it thought they would.
712    const waited = waitsFor(await read($, lastActiveAt), now)
713    let missed = false
714    touch(now, settled => {
715      missed = misses(settled)
716      return seen(settled)
717    })
718    if ((missed || waited) && (await read($, turnStartedAt)) === null) {
719      gladAt = now
720      const glad: Reaction = { mood: 'happy', label: label(waited ? 'thereYouAre' : 'missedYou'), until: now + REACTION_MS }
721      await update($, reaction, live => (holds(live, now) ? live : glad))
722    }
723    return next(e)
724  }).catch(($, e, next) => next(e))
725
726  // What is still waiting for a pet when the session ends counts as it stands: no
727  // pet can come any more. The writes left are seen through before it goes.
728  on('session.end', async ($, e, next) => {
729    if (learning !== undefined && recent.length > 0) {
730      const done = recent
731      recent = []
732      const name = logNameAt(await $.clock.now())
733      writing = writing.then(() => keepLearned($, name, done).then(() => {})).catch(() => {})
734    }
735    await writing
736    return next(e)
737  }).catch(($, e, next) => next(e))
738
739  // Only a pet in deep sleep is startled awake; a dozing one just starts thinking,
740  // one keeping an eye on background agents was awake all along, and one glad to
741  // see the person woke up already.
742  on('prompt.submit', async ($, e, next) => {
743    const now = await $.clock.now()
744    const idleSince = await read($, lastActiveAt)
745    const busySince = await read($, turnStartedAt)
746    const isSupervising = stillHere(await read($, agents), now).some(one => one.leaving === undefined)
747    // Up waiting for them, it is no more asleep than when they type.
748    if (busySince === null && !isSupervising && isFastAsleep(idleSince, now) && !waitsFor(idleSince, now)) {
749      await update($, reaction, (): Reaction => ({ mood: 'waking', label: label('wakingUp'), until: now + WAKING_MS }))
750    }
751    touch(now, seen)
752    // How unusual this moment is. Once it knows the person's moments well, an odd
753    // one gets a curious look on a lively day, an hour apart at most.
754    // A `claude -p` run is no moment of the person's.
755    if (learning !== undefined && isInteractive) {
756      const { seed } = learning
757      const code = momentCode(hourOf(now), idleSince === null ? 0 : (now - idleSince) / 60_000, toolsThisTurn)
758      const name = logNameAt(now)
759      const noted = writing.then(() => noteMoment($, name, code, now, seed))
760      writing = noted.then(
761        () => {},
762        () => {},
763      )
764      const moment = await noted.catch(() => undefined)
765      if (moment !== undefined && isLively(now) && moment.known >= KNOWS && moment.news >= ODD && now - oddAt >= ODD_GAP_MS) {
766        oddAt = now
767        const curious: Reaction = { mood: 'watching', label: label('somethingNew'), until: now + REACTION_MS }
768        await update($, reaction, live => (holds(live, now) ? live : curious))
769      }
770    }
771    if (isInteractive) {
772      const before = await atThePrompt($, now)
773      // Away a while: they just turned up, and when is worth remembering.
774      const isArrival = (before === undefined || now - before.lastSeenAt >= AWAY_MS) && (idleSince === null || now - idleSince >= AWAY_MS)
775      if (learning !== undefined && isArrival) {
776        const name = logNameAt(now)
777        writing = writing.then(() => noteArrival($, name, now).then(kept => void (rhythm = kept))).catch(() => {})
778      }
779    }
780    // Once a night across every session: the first to see the person late says it.
781    const tonight = nightOf(now)
782    if (isNight(hourOf(now)) && saidNight !== tonight) {
783      if (await quietTonight($, now)) {
784        const locale = await localeOf($, language)
785        if (speak('lateNight', now, await packOf($, petName, locale), locale)) {
786          saidNight = tonight
787          await saidTonight($, now)
788        }
789      } else saidNight = tonight
790    }
791    return next(e)
792  }).catch(($, e, next) => next(e))
793
794  on('turn.start', async ($, e, next) => {
795    const now = await $.clock.now()
796    await update($, activity, (): Activity => ({ mood: 'thinking', label: label('thinking') }))
797    await update($, turnStartedAt, () => now)
798    speaker = { ...speaker, saidThisTurn: [] }
799    touch(now, engaged)
800    thinkingSince = now
801    toolsThisTurn = 0
802    readsThisTurn = 0
803    return next(e)
804  })
805
806  on('turn.complete', async ($, e, next) => {
807    const now = await $.clock.now()
808    const isBad = e.reason === 'error' || e.reason === 'refusal'
809
810    if (e.agentId !== undefined) {
811      const id = e.agentId
812      const leaving = { mood: (isBad || e.isAborted ? 'sad' : 'happy') as MiniMood, until: now + LEAVING_MS }
813      await update($, agents, list => stillHere(list, now).map(pet => (pet.id === id ? { ...pet, leaving } : pet)))
814      await update($, lastActiveAt, () => now)
815      agentsDone = true
816      return next(e)
817    }
818
819    if (!e.isAborted) await update($, feelings, felt => feel(felt, isBad ? 'turnFailed' : 'turnOk', now))
820    const startedAt = await read($, turnStartedAt)
821    const tookLong = startedAt !== null && now - startedAt >= LONG_WIN_MS
822    const agentsLeft = stillHere(await read($, agents), now).filter(one => one.leaving === undefined).length
823    const cheered = cheer({ tookLong, tools: toolsThisTurn, agentsDone, agentsLeft }, Math.random)
824    if (agentsLeft === 0) agentsDone = false
825    const until = now + REACTION_MS
826    // An interrupted turn earns no reaction, and one still showing (a thanks, a
827    // "fine, I won't" after a denied permission, a failure) is left to finish.
828    // A failure always shows; a turn that went well only sometimes cheers.
829    const live = await read($, reaction)
830    if (!e.isAborted && !holds(live, now) && (isBad || cheered !== null)) {
831      await update($, reaction, (): Reaction =>
832        isBad
833          ? { mood: 'sad', label: label('wentWrong'), until }
834          : cheered === 'celebrating'
835            ? { mood: 'celebrating', label: label('phew'), until: now + CELEBRATION_MS }
836            : { mood: 'happy', label: label('done'), until },
837      )
838    }
839    await update($, override, () => null)
840    await update($, turnStartedAt, () => null)
841    await update($, lastActiveAt, () => now)
842    return next(e)
843  })
844
845  on('agent.spawn', async ($, e, next) => {
846    const started = await next(e)
847    const id = 'agentId' in started ? started.agentId : undefined
848    if (id !== undefined) {
849      const now = await $.clock.now()
850      await update($, agents, list => {
851        const color = AGENT_COLORS[list.length % AGENT_COLORS.length] ?? 0xffffff
852        const pet: AgentPet = { id, toolUseId: e.tool_use_id, type: e.subagentType, label: label('thinking'), color }
853        return [...stillHere(list, now), pet]
854      })
855      const working = stillHere(await read($, agents), now).filter(one => one.leaving === undefined)
856      if (working.length >= MANY_AGENTS) {
857        const locale = await localeOf($, language)
858        speak('manyAgents', now, await packOf($, petName, locale), locale)
859      }
860    }
861    return started
862  }).catch(($, e, next) => next(e))
863
864  on('tool.call', async ($, e, next) => {
865    const now = describe(e)
866    const agentId = e.agentId
867
868    if (agentId === undefined) {
869      await update($, activity, () => now)
870    } else {
871      await update($, agents, list => list.map(pet => (pet.id === agentId ? { ...pet, label: now.label } : pet)))
872    }
873
874    if (agentId === undefined) {
875      thinkingSince = null
876      toolsThisTurn += 1
877    }
878    const key = callKey(agentId, String(e.tool))
879    openCalls.set(key, e.tool_use_id)
880    let ran: Awaited<ReturnType<typeof next>>
881    let wasAsked = false
882    try {
883      ran = await next(e)
884    } finally {
885      if (openCalls.get(key) === e.tool_use_id) openCalls.delete(key)
886      wasAsked = asked.delete(e.tool_use_id)
887    }
888
889    // A background agent's tool call returns at once; its pet leaves on its own
890    // turn.complete. Only a spawn that failed is dropped here.
891    if (e.tool === 'Agent' && ran.isError === true) {
892      await update($, agents, list => list.filter(pet => pet.toolUseId !== e.tool_use_id))
893    }
894    const at = await $.clock.now()
895    const until = at + REACTION_MS
896    if (agentId === undefined) {
897      thinkingSince = at
898      if (e.tool === 'Read' && (readsThisTurn += 1) === MANY_READS) {
899        const locale = await localeOf($, language)
900        speak('manyReads', at, await packOf($, petName, locale), locale)
901      }
902    }
903    if (wasAsked) {
904      // The person answered a permission prompt: thanks for a yes, fine for a no.
905      const thanked: Reaction = isDenial(ran)
906        ? { mood: 'sad', label: label('denied'), until }
907        : { mood: 'happy', label: label('thanks'), until }
908      await update($, reaction, () => thanked)
909    } else if (agentId === undefined && ran.isError === true) {
910      // "failed: npm test", or the tool's name when the action has no detail.
911      const failed = label('failed', short(now.label.detail || String(e.tool), 24))
912      await update($, reaction, (): Reaction => ({ mood: 'sad', label: failed, until }))
913      await update($, feelings, felt => feel(felt, 'toolFailed', at))
914    }
915    return ran
916  }).catch(($, e, next) => next(e))
917
918  // The band is hidden while a permission dialog is open (and `$.ui.notice` does
919  // not show under the terminal's), so the pet only marks the call that asked;
920  // tool.call reacts once the person has answered.
921  on('classic.PermissionRequest', async ($, e, next) => {
922    const id = openCalls.get(callKey(e.agent_id, e.tool_name))
923    if (id !== undefined) asked.add(id)
924    return next(e)
925  }).catch(($, e, next) => next(e))
926
927  on('session.compact', async ($, e, next) => {
928    await update($, override, (): Activity => ({ mood: 'compacting', label: label('compacting') }))
929    try {
930      return await next(e)
931    } finally {
932      await release($, 'compacting')
933    }
934  }).catch(($, e, next) => next(e))
935
936  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
937    scene = null
938    isOff = await read($, isHidden)
939    if (e.props.hasSurvey || isOff) {
940      letGo()
941      return next(e)
942    }
943
944    const locale = await localeOf($, language)
945    const pack = await packOf($, petName, locale)
946    const now = await $.clock.now()
947    const busy = await read($, override)
948    const flash = await read($, reaction)
949    const doing = await read($, activity)
950    const startedAt = await read($, turnStartedAt)
951    const idleSince = await read($, lastActiveAt)
952    const typedAt = await read($, typingAt)
953    const list = stillHere(await read($, agents), now)
954    const words = (one: Label) => say(locale, one.text, one.detail)
955    // ponytail: the drives move only when the band is drawn, so a band hidden by /pet
956    // counts all that time as what it last showed; give them a clock of their own if that skews them.
957    if (isAlive && !hasLoaded) {
958      hasLoaded = true
959      learning = await loadLearning($)
960      rhythm = await loadRhythm($)
961    }
962    // On a lively day it wakes up in a temper: a little more playful, lazy, clingy or curious.
963    traits = learning !== undefined && isLively(now) ? tempered(pack.personality, temperOf(learning.seed, now)) : pack.personality
964    drives = drives === undefined ? rested(now) : drift(drives, now, lastState, traits)
965    // What is past its minute counts for what it learned, and goes in the log.
966    const done = recent.filter(one => now - one.at > CREDIT_MS)
967    if (done.length > 0) {
968      recent = recent.filter(one => now - one.at <= CREDIT_MS)
969      const name = logNameAt(now)
970      writing = writing
971        .then(() => keepLearned($, name, done))
972        .then(kept => {
973          if (kept !== undefined) learning = kept
974        })
975        .catch(() => {})
976    }
977
978    let shown: Activity
979    let extra = ''
980    const isFlashing = flash !== null && flash.until > now
981    // Petted at work, it shows it but leaves Claude's line be.
982    const isPettedAtWork = isFlashing && flash.byTouch === true && e.props.isWorking
983    if (busy !== null) {
984      shown = busy
985    } else if (isFlashing && !isPettedAtWork) {
986      shown = flash
987    } else if (e.props.isWorking) {
988      const elapsed = startedAt === null ? 0 : now - startedAt
989      const isLong = elapsed > LONG_TURN_MS && PATIENT.includes(doing.mood)
990      if (thinkingSince !== null && now - thinkingSince >= LONG_THINK_MS) speak('longThink', now, pack, locale)
991      // A turn that only thinks while agents still run is waiting on them.
992      const current: Activity =
993        doing.mood === 'thinking' && list.some(one => one.leaving === undefined)
994          ? { mood: 'supervising', label: label('waitingForAgents') }
995          : doing
996      shown = isPettedAtWork ? { ...current, mood: flash.mood } : isLong ? { ...current, mood: 'sweating' } : current
997      if (isLong) extra = ` · ${Math.floor(elapsed / 60_000)}m`
998    } else {
999      const hour = hourOf(now)
1000      const isTyping = typedAt !== null && now - typedAt < TYPING_MS
1001      // Once glad to see them it only dozes, so the prompt it sends does not startle it.
1002      const isDeeplyAsleep = isFastAsleep(idleSince, now)
1003      // Fast asleep it does not look up.
1004      if (isTyping && !isDeeplyAsleep) shown = { mood: 'watching', label: label('watching') }
1005      // Background agents still at work: it keeps an eye on them rather than dozing off.
1006      else if (list.some(one => one.leaving === undefined)) shown = { mood: 'supervising', label: label('waitingForAgents') }
1007      // About when they usually turn up, it gets up and watches the prompt for them.
1008      else if (waitsFor(idleSince, now)) shown = { mood: 'watching', label: label('waitingForYou') }
1009      else if (isDeeplyAsleep) shown = { mood: 'deepSleep', label: label('deepSleep') }
1010      else if (isDozing(idleSince, now)) shown = asleep
1011      else {
1012        // Bored in a nap, it gets up for a while on its own.
1013        if (isDrowsy(idleSince, now)) {
1014          stirredUntil = now + stirFor()
1015          drives = stirred(drives)
1016          speak('bored', now, pack, locale)
1017        }
1018        const felt = idleMood(await read($, feelings), now, await read($, restedAt), hour)
1019        // A pointer resting on it gets a look back.
1020        if (gazes(touched, now)) shown = { mood: 'watching', label: label('lookingAtYou') }
1021        else shown = felt === undefined ? { mood: 'idle', label: label('idle') } : { mood: felt, label: label(felt) }
1022      }
1023    }
1024
1025    lastState = shown.mood === 'sleeping' || shown.mood === 'deepSleep' ? 'asleep' : e.props.isWorking ? 'working' : 'awake'
1026    // Asleep, it talks in its sleep now and then, as rarely as it speaks at all.
1027    const dreamGap = () => (DREAM_MINUTES[0] + (DREAM_MINUTES[1] - DREAM_MINUTES[0]) * Math.random()) * 60_000
1028    if (lastState === 'working') dreamAt = null
1029    else if (lastState === 'asleep') {
1030      if (dreamAt === null) dreamAt = now + dreamGap()
1031      else if (now >= dreamAt) {
1032        speak('dreaming', now, pack, locale)
1033        dreamAt = now + dreamGap()
1034      }
1035    }
1036
1037    const miniSize = sizeOf(pack.mini?.working[0] ?? [])
1038    const slot = showsAgentLabels ? Math.max(miniSize.columns, AGENT_SLOT) : miniSize.columns
1039    const petColumns = sizeOf(pack.moods.sleeping[0] ?? []).columns
1040    // As many agents as fit beside the pet; the rest are a "+N" that needs room too.
1041    // A pack with no mini pets shows its agents only by its own mood.
1042    const room = e.props.bodyColumns - petColumns - 2
1043    const fits = (count: number) => count * (slot + 1) + (count < list.length ? OVERFLOW_COLUMNS : 0) <= room
1044    let shownAgents = pack.mini === null ? 0 : Math.min(list.length, MAX_AGENTS)
1045    while (shownAgents > 0 && !fits(shownAgents)) shownAgents -= 1
1046    const visible = list.slice(0, shownAgents)
1047    const hidden = pack.mini === null ? 0 : list.length - visible.length
1048    const agentWords = (one: AgentPet) =>
1049      one.leaving === undefined ? words(one.label) : say(locale, one.leaving.mood === 'sad' ? 'wentWrong' : 'done')
1050
1051    // Every frame is one size, so the sleeping one tells whether the stage fits, tall and wide.
1052    // A line of text has no stage, and must not move the pet on the one that has.
1053    const mainSize = sizeOf(pack.moods.sleeping[0] ?? [])
1054    if (e.surface !== 'terminal' || e.props.maxRows < mainSize.rows + (showsLine ? 1 : 0) || e.props.bodyColumns < mainSize.columns) {
1055      letGo()
1056      const { Text } = $.ui.resolve(e)
1057      const others = list.map(one => ` · ${one.type}: ${agentWords(one)}`).join('')
1058      return <Text dimColor>🐾 Claude: {words(shown.label)}{extra}{others}</Text>
1059    }
1060
1061    // It only strolls alone; with agents around they gather on both sides, and when
1062    // they do not fit where it stands it hurries off to make room.
1063    // A proud pet struts about too; a sleepy, tired, worried or grumpy one stays put.
1064    const isRestless = shown.mood === 'idle' || shown.mood === 'proud'
1065    const width = slot + 1
1066    const extraColumns = hidden > 0 ? OVERFLOW_COLUMNS : 0
1067    // A pet that draws no walking but a teleport gets about by vanishing and appearing.
1068    const teleport = pack.walks ? null : pack.teleport
1069    const pace = paceOf(drives)
1070    const urge = urgeOf(drives)
1071    // A line it says takes Claude's line for a moment, unless a reaction or a mood that
1072    // must show is on it.
1073    // With no line there is nowhere to say it.
1074    const isQuoting = showsLine && saying !== null && saying.until > now && busy === null && !(flash !== null && flash.until > now)
1075
1076    // Moves the pet and its agents one tick on from where the last draw or tick left
1077    // them. Safe to call again on the same tick: it shows the same.
1078    const play = () => {
1079      const onStage = moveOnStage(stage, {
1080        tick: frame,
1081        room,
1082        fps: pack.fps,
1083        random: Math.random,
1084        pace,
1085        walks: pack.walks,
1086        teleport: teleport === null ? null : { vanish: teleport.vanish.length, appear: teleport.appear.length },
1087        agents: visible.map(one => one.id),
1088        width,
1089        extra: extraColumns,
1090        // Busy with an activity it stays put: a step would cut it short.
1091        wants: placed =>
1092          visible.length > 0 ? { go: placed.x } : list.length === 0 && isRestless && activityIn(motion, frame) === undefined ? 'wander' : 'stay',
1093      })
1094      stage = onStage.stage
1095      const { drawn, drawnCount, standX, blinking } = onStage
1096      const blinkFrame = teleport === null || blinking === undefined ? undefined : teleport[blinking.phase][blinking.at]
1097      const showsMore = standX === onStage.placed.x && hidden > 0
1098      const isOnTheMove = onStage.moving || blinkFrame !== undefined
1099      const isStrolling = isOnTheMove && onStage.wants === 'wander'
1100      // A teleport is its walk: what falls due meanwhile waits for it to land.
1101      const mood: Mood = (pack.walks && onStage.moving) || blinkFrame !== undefined ? 'walking' : shown.mood
1102      const labelShown = isStrolling ? label('strolling') : shown.label
1103
1104      // On a lively day it picks the activity by its whims and what earned pets at this time of day.
1105      const known = learning
1106      const arm = known === undefined ? undefined : isLively(now) ? 'learned' : 'hand'
1107      const daypart = daypartOf(hourOf(now))
1108      const choose =
1109        known !== undefined && arm === 'learned'
1110          ? (activities: string[]) =>
1111              (lastPick = pickFor({ bandit: known.bandit, seed: known.seed, pet: pack.name, daypart, activities, lately }, now, Math.random)).activity
1112          : undefined
1113      const before = motion?.once
1114      const moved = step(pack, motion, mood, frame, Math.random, urge, choose)
1115      const begun = moved.motion.once
1116      if (arm !== undefined && begun !== before && begun?.activity !== undefined) {
1117        const propensity = arm === 'learned' && lastPick?.activity === begun.activity ? lastPick.propensity : null
1118        recent = [...recent, { at: now, arm, daypart, pet: pack.name, activity: begun.activity, propensity, petted: 0, annoyed: false }]
1119        lately = [begun.activity, ...lately].slice(0, 5)
1120      }
1121      motion = moved.motion
1122      // Busy with an activity, the line says what, in its language or else in English.
1123      const pastime = pack.actions.find(one => one.name === activityIn(moved.motion, frame))?.activity?.label
1124      const said = isQuoting ? `“${saying?.text}”` : (pastime?.[locale.code] ?? pastime?.en ?? words(labelShown))
1125      // It faces the way it walks, else the agent finishing as it says goodbye, else the
1126      // first; through an action, the way it faced as the action began.
1127      const finishing = visible.slice(0, drawnCount).findLastIndex(one => one.leaving !== undefined)
1128      const facesNow = faceFor(isOnTheMove, stage.walk?.facing ?? 1, drawn, Math.max(finishing, 0))
1129      const once = moved.motion.once
1130      const held = holdFacing(heldFacing, once?.isAction ? once : undefined, facesNow, isOnTheMove)
1131      heldFacing = held.held
1132      const facing = held.side
1133      const body = facingFrame(blinkFrame ?? moved.frame, facing, pack.mirrors)
1134
1135      const art: Art = { ...mainSize, fps: pack.fps, art: artOf(body, pack.colors) }
1136      const rasters: Record<string, string> = {}
1137      for (const index of [...drawn.left, ...drawn.right]) {
1138        const one = visible[index]
1139        if (one === undefined) continue
1140        // The ones still at work on the side it faces jump while it startles them, their
1141        // jump played from its first frame as it does, not with the clock.
1142        const startledAt = sideIn(drawn, index) === facing && one.leaving === undefined ? moved.startled : undefined
1143        const miniFrames = pack.mini?.[one.leaving?.mood ?? (startledAt === undefined ? 'working' : 'startled')] ?? []
1144        const mini = miniFrames[(startledAt ?? frame) % miniFrames.length] ?? []
1145        rasters[`mini-${one.id}`] = encode(mini, { ...pack.colors, [pack.tint]: one.color })
1146      }
1147      const leftColumns = drawn.left.length * width + (showsMore && drawn.more === -1 ? extraColumns : 0)
1148      const marginLeft = standX - leftColumns
1149      const layout = JSON.stringify([said, marginLeft, drawn.left, drawn.right, drawn.more, showsMore])
1150      return { shot: { layout, main: JSON.stringify(art.art), art, rasters }, said, marginLeft, drawn, showsMore }
1151    }
1152
1153    const { shot, said, marginLeft, drawn, showsMore } = play()
1154    sentMain = shot.main
1155    // What it shows that runs out on its own: a reaction, a line it says, a look at
1156    // the prompt, an agent saying goodbye. The rest that changes with time alone
1157    // waits for the clock's redraw now and then.
1158    const soonest = Math.min(
1159      ...[flash?.until, saying?.until, typedAt === null ? undefined : typedAt + TYPING_MS, ...list.map(one => one.leaving?.until)].filter(
1160        (until): until is number => until !== undefined && until > now,
1161      ),
1162    )
1163    scene = {
1164      requestId: e.requestId,
1165      shot,
1166      play: () => play().shot,
1167      redrawAt: frame + Math.ceil(((soonest - now) / 1000) * pack.fps),
1168      isAsleep: lastState === 'asleep',
1169    }
1170
1171    const { Box, Client, Raster, Text } = $.ui.resolve(e)
1172    const agentPet = (index: number, side: Side) => {
1173      const one = visible[index]
1174      if (one === undefined) return null
1175      return (
1176        // On the left the slot hugs the pet too: its pet and words lean right.
1177        <Box
1178          key={one.id}
1179          flexDirection="column"
1180          width={slot}
1181          alignItems={side === 1 ? 'flex-start' : 'flex-end'}
1182          marginLeft={side === 1 ? 1 : 0}
1183          marginRight={side === 1 ? 0 : 1}
1184        >
1185          <Raster key={`mini-${one.id}`} {...miniSize} cells={shot.rasters[`mini-${one.id}`] ?? ''} />
1186          {showsAgentLabels && <Text bold>{short(one.type, slot)}</Text>}
1187          {showsAgentLabels && <Text dimColor>{short(agentWords(one), slot)}</Text>}
1188        </Box>
1189      )
1190    }
1191
1192    return (
1193      <Box flexDirection="column">
1194        {showsLine && (
1195          <Text>
1196            <Text bold>Claude</Text> <Text dimColor>· {said}{extra}</Text>
1197          </Text>
1198        )}
1199        <Box flexDirection="row" marginLeft={marginLeft}>
1200          {showsMore && drawn.more === -1 && (
hooks/drives.ts 82 lines
1import type { Traits } from '../types'
2import type { Pace } from './walk'
3
4// What the pet wants, apart from what Claude is doing: each in [0, 1], drifting
5// with time by what it was up to. Session only, like the feelings.
6export type Drives = { energy: number; boredom: number; longing: number; at: number }
7
8// What it was up to since `at`: what the band last showed.
9export type State = 'asleep' | 'awake' | 'working'
10
11const HOUR_MS = 60 * 60_000
12
13// Change per hour. Sleep fills energy in two hours; boredom fills in a quarter of
14// an hour with nothing to do; longing fills in an hour without the person, even
15// while Claude works, since it is about them.
16const RATES: Record<State, Omit<Drives, 'at'>> = {
17  asleep: { energy: 0.5, boredom: 4, longing: 1 },
18  awake: { energy: -0.1, boredom: 4, longing: 1 },
19  working: { energy: -0.25, boredom: 0, longing: 1 },
20}
21
22// Bored enough, and not too tired, to get up on its own.
23const STIR_BOREDOM = 1 / 3
24const STIR_ENERGY = 0.4
25// Below this it starts to flag.
26const LOW_ENERGY = 0.5
27// Missing the person this much, it greets their first key.
28const MISSING = 0.5
29
30export const USUAL: Traits = { energetic: 0.5, curious: 0.5, affectionate: 0.5 }
31
32export const rested = (now: number): Drives => ({ energy: 1, boredom: 0, longing: 0, at: now })
33
34const unit = (value: number) => Math.min(1, Math.max(0, value))
35
36// The drives at `now`, after spending the time since `at` in `state`, as a pet
37// made with `traits`: an energetic one tires slower, a curious one gets bored
38// sooner, an affectionate one misses the person sooner. The usual traits change nothing.
39export const drift = (drives: Drives, now: number, state: State, traits: Traits = USUAL): Drives => {
40  const hours = (now - drives.at) / HOUR_MS
41  if (hours <= 0) return drives
42  const rate = RATES[state]
43  const tiring = rate.energy < 0 ? 1.5 - traits.energetic : 1
44  return {
45    energy: unit(drives.energy + rate.energy * tiring * hours),
46    boredom: unit(drives.boredom + rate.boredom * traits.curious * 2 * hours),
47    longing: unit(drives.longing + rate.longing * traits.affectionate * 2 * hours),
48    at: now,
49  }
50}
51
52// A turn started: something to watch at last.
53export const engaged = (drives: Drives): Drives => ({ ...drives, boredom: 0 })
54
55// Up from a nap on its own: that cured its boredom.
56export const stirred = (drives: Drives): Drives => ({ ...drives, boredom: 0 })
57
58// The person typed or sent a prompt.
59export const seen = (drives: Drives): Drives => ({ ...drives, boredom: 0, longing: 0 })
60
61// How much of its usual awake time it lasts: all of it until energy runs low.
62export const alertness = (drives: Drives) => (drives.energy >= LOW_ENERGY ? 1 : Math.max(0.25, drives.energy * 2))
63
64// How it strolls: a tired pet rests longer between strolls, up to twice as long,
65// and one that misses the person keeps near the prompt.
66export const paceOf = (drives: Drives): Pace => ({
67  rest: drives.energy >= LOW_ENERGY ? 1 : 2 - drives.energy * 2,
68  lean: drives.longing,
69})
70
71// Whether it has missed the person enough to greet them.
72export const misses = (drives: Drives) => drives.longing >= MISSING
73
74export type Urge = 'tired' | 'longing' | 'bored'
75
76// What a pet at work drifts off to when it does: a tired one flags, one that misses
77// the person looks for them, else it finds something to do.
78export const urgeOf = (drives: Drives): Urge => (drives.energy < LOW_ENERGY ? 'tired' : misses(drives) ? 'longing' : 'bored')
79
80// Whether a dozing pet gets up on its own.
81export const stirs = (drives: Drives) => drives.boredom >= STIR_BOREDOM && drives.energy >= STIR_ENERGY
82
hooks/feelings.ts 72 lines
1import type { Feelings, Mood } from '../types'
2
3export type Feeling = 'toolFailed' | 'turnFailed' | 'turnOk'
4
5const FADE_MS = 5 * 60_000
6const WORRIED = 3
7const GRUMPY = 6
8const PROUD = 3
9// Hours of work since its last long break that make it tired.
10const TIRED_MS = 3 * 60 * 60_000
11
12export const calm: Feelings = { worry: 0, pride: 0, at: 0 }
13
14// The feelings as they stand at `now`, the points faded since `at` taken off.
15export const settle = (feelings: Feelings, now: number): Feelings => {
16  const faded = Math.max(0, Math.floor((now - feelings.at) / FADE_MS))
17  if (faded === 0) return feelings
18  return {
19    worry: Math.max(0, feelings.worry - faded),
20    pride: Math.max(0, feelings.pride - faded),
21    at: feelings.at + faded * FADE_MS,
22  }
23}
24
25export const feel = (feelings: Feelings, what: Feeling, now: number): Feelings => {
26  const { worry, pride } = settle(feelings, now)
27  switch (what) {
28    case 'toolFailed':
29      return { worry: worry + 1, pride, at: now }
30    // Pride is for a streak: a turn that fails ends it.
31    case 'turnFailed':
32      return { worry: worry + 2, pride: 0, at: now }
33    case 'turnOk':
34      return { worry: Math.max(0, worry - 1), pride: pride + 1, at: now }
35  }
36}
37
38// A turn of work that went well cheers it only now and then, or it would cheer at every step.
39const CHEER_CHANCE = 0.6
40
41type Turn = { tookLong: boolean; tools: number; agentsDone: boolean; agentsLeft: number }
42
43// How a turn that went well ends. It waits for the last agent before cheering;
44// a long turn is celebrated, the last agent done is cheered, other work only now
45// and then, and a turn that only talked earns nothing.
46export const cheer = (turn: Turn, random: () => number): 'celebrating' | 'happy' | null => {
47  if (turn.agentsLeft > 0) return null
48  if (turn.tookLong) return 'celebrating'
49  if (turn.agentsDone) return 'happy'
50  if (turn.tools === 0) return null
51  return random() < CHEER_CHANCE ? 'happy' : null
52}
53
54export const isNight = (hour: number) => hour >= 22 || hour < 6
55export const isMorning = (hour: number) => hour >= 5 && hour < 11
56// The night `now` falls in, named by its evening's date: 2 a.m. belongs to the night before.
57export const nightOf = (now: number) => new Date(now - 6 * 60 * 60_000).toDateString()
58
59// The moods that stand in for plain `idle`; each is also the key of its words.
60export type Felt = Extract<Mood, 'grumpy' | 'worried' | 'tired' | 'proud' | 'sleepy'>
61
62// What it shows instead of plain `idle`, if anything: the strongest feeling wins.
63export const idleMood = (feelings: Feelings, now: number, restedAt: number | null, hour: number): Felt | undefined => {
64  const { worry, pride } = settle(feelings, now)
65  if (worry >= GRUMPY) return 'grumpy'
66  if (worry >= WORRIED) return 'worried'
67  if (restedAt !== null && now - restedAt >= TIRED_MS) return 'tired'
68  if (pride >= PROUD && worry === 0) return 'proud'
69  if (isNight(hour)) return 'sleepy'
70  return undefined
71}
72
hooks/i18n.ts 28 lines
1import type { Text } from '../types'
2import { en } from '../locales/en'
3import type { Locale } from '../locales/en'
4import { ptBR } from '../locales/pt-BR'
5
6export type { Locale, Text }
7
8export const LOCALES: readonly Locale[] = [en, ptBR]
9
10const byName = (wanted: string | undefined) => {
11  if (!wanted) return undefined
12  // "pt_BR.UTF-8" → "pt-br"
13  const name = wanted.trim().toLowerCase().split('.')[0]?.replace('_', '-') ?? ''
14  return (
15    LOCALES.find(locale => locale.names.includes(name)) ??
16    LOCALES.find(locale => locale.names.includes(name.split('-')[0] ?? ''))
17  )
18}
19
20// `auto` follows Claude Code's own `language` setting, then $LANG, then English.
21export const pickLocale = (choice: string, setting: unknown, lang: string | undefined): Locale =>
22  (choice !== 'auto' ? byName(choice) : undefined) ??
23  byName(typeof setting === 'string' ? setting : undefined) ??
24  byName(lang) ??
25  en
26
27export const say = (locale: Locale, text: Text, detail = '') => locale.strings[text].replace('{detail}', detail)
28
learn/bandit.ts 37 lines
1import { beta, type Random } from './random'
2
3// Thompson sampling that forgets by time, so a changed habit wins back in days.
4// Keys are free-form: prefix them with a context bucket (`evening:juggle`) to
5// learn one preference per bucket.
6export type Tally = { wins: number; losses: number; at: number }
7export type Bandit = Record<string, Tally>
8
9const fade = (tally: Tally | undefined, now: number, halfLife: number): Tally => {
10  if (tally === undefined) return { wins: 0, losses: 0, at: now }
11  const kept = 0.5 ** (Math.max(0, now - tally.at) / halfLife)
12  // An older event folds in without moving the clock back.
13  return { wins: tally.wins * kept, losses: tally.losses * kept, at: Math.max(now, tally.at) }
14}
15
16export const choose = (bandit: Bandit, keys: string[], now: number, halfLife: number, random: Random) => {
17  let best = keys[0] ?? ''
18  let top = -1
19  for (const key of keys) {
20    const { wins, losses } = fade(bandit[key], now, halfLife)
21    const draw = beta(wins + 1, losses + 1, random)
22    if (draw > top) [best, top] = [key, draw]
23  }
24  return best
25}
26
27// `value` in [0, 1]: a pet is 1, an annoyed poke 0, anything between is partial.
28export const reward = (bandit: Bandit, key: string, value: number, now: number, halfLife: number): Bandit => {
29  const { wins, losses } = fade(bandit[key], now, halfLife)
30  return { ...bandit, [key]: { wins: wins + value, losses: losses + 1 - value, at: now } }
31}
32
33export const mean = (bandit: Bandit, key: string, now: number, halfLife: number) => {
34  const { wins, losses } = fade(bandit[key], now, halfLife)
35  return (wins + 1) / (wins + losses + 2)
36}
37
learn/recall.ts 91 lines
1import { beta, type Random } from './random'
2
3// Similar moments get overlapping sparse codes: each cell sums a few random
4// inputs and only the strongest `active` cells fire. What followed a moment is
5// then stored on its cells, so a new moment recalls what followed the ones it
6// overlaps, and learning one moment barely disturbs the unrelated ones.
7export type Coder = { cells: number[][]; active: number }
8
9export const coder = (inputs: number, size: number, active: number, perCell: number, random: Random): Coder => ({
10  cells: Array.from({ length: size }, () => Array.from({ length: perCell }, () => Math.floor(random() * inputs))),
11  active,
12})
13
14export const encode = (coder: Coder, x: number[]) =>
15  coder.cells
16    .map((inputs, cell) => ({ cell, drive: inputs.reduce((sum, i) => sum + (x[i] ?? 0), 0) }))
17    .sort((a, b) => b.drive - a.drive || a.cell - b.cell)
18    .slice(0, coder.active)
19    .map(({ cell }) => cell)
20
21// A value in [min, max] as `n` overlapping bumps, so nearby values share inputs.
22// `circular` wraps the ends, for hours of the day.
23export const bumps = (value: number, min: number, max: number, n: number, circular = false) => {
24  const span = max - min
25  const width = span / (circular ? n : n - 1)
26  return Array.from({ length: n }, (_, i) => {
27    let d = Math.abs(value - (min + i * width))
28    if (circular) d = Math.min(d, span - d)
29    return Math.exp(-((d / width) ** 2))
30  })
31}
32
33// Reward summed and moments seen, per action and cell.
34// ponytail: no forgetting yet; add per-cell timestamps if Recall earns its place.
35export type Memory = Record<string, { sum: Record<number, number>; seen: Record<number, number> }>
36
37const tally = (memory: Memory, action: string, code: number[]) => {
38  const slot = memory[action]
39  let sum = 0
40  let seen = 0
41  for (const cell of code) {
42    sum += slot?.sum[cell] ?? 0
43    seen += slot?.seen[cell] ?? 0
44  }
45  return { wins: sum / code.length, trials: seen / code.length }
46}
47
48export const recall = (memory: Memory, action: string, code: number[]) => {
49  const { wins, trials } = tally(memory, action, code)
50  return (wins + 1) / (trials + 2)
51}
52
53export const pick = (memory: Memory, actions: string[], code: number[], random: Random) => {
54  let best = actions[0] ?? ''
55  let top = -1
56  for (const action of actions) {
57    const { wins, trials } = tally(memory, action, code)
58    const draw = beta(wins + 1, trials - wins + 1, random)
59    if (draw > top) [best, top] = [action, draw]
60  }
61  return best
62}
63
64// Mutates: the memory can hold thousands of cells, copying it per event costs more than it buys.
65export const remember = (memory: Memory, action: string, code: number[], value: number) => {
66  const slot = (memory[action] ??= { sum: {}, seen: {} })
67  for (const cell of code) {
68    slot.sum[cell] = (slot.sum[cell] ?? 0) + value
69    slot.seen[cell] = (slot.seen[cell] ?? 0) + 1
70  }
71}
72
73// How unfamiliar a moment is, 0 to 1. Seeing it makes its cells familiar, and
74// familiarity fades with `halfLife`, so a rare moment is news again later.
75export type Familiar = Record<number, { level: number; at: number }>
76
77const level = (familiar: Familiar, cell: number, now: number, halfLife: number) => {
78  const f = familiar[cell]
79  return f === undefined ? 0 : f.level * 0.5 ** (Math.max(0, now - f.at) / halfLife)
80}
81
82export const novelty = (familiar: Familiar, code: number[], now: number, halfLife: number) =>
83  code.reduce((sum, cell) => sum + 1 - level(familiar, cell, now, halfLife), 0) / code.length
84
85export const see = (familiar: Familiar, code: number[], now: number, halfLife: number, gain = 0.5) => {
86  for (const cell of code) {
87    const was = level(familiar, cell, now, halfLife)
88    familiar[cell] = { level: was + gain * (1 - was), at: now }
89  }
90}
91
hooks/learning.ts 225 lines
1import type { Traits } from '../types'
2import { mean, reward, type Bandit, type Tally } from '../learn/bandit'
3import { credit } from '../learn/credit'
4import { seeded, type Random } from '../learn/random'
5import { bumps, coder, encode, type Familiar } from '../learn/recall'
6import { daysBetween } from './memory'
7
8// A pet that feels alive: it lives by what it learned of the person and by whims
9// of its own, and what it learns of their taste only tips its choices: it never
10// settles on one. In the experiment it does so only on its `learned` days, as it
11// always did on the `hand` ones, and every activity shown is logged with the pets it got.
12
13export type Arm = 'learned' | 'hand'
14export type Daypart = 'night' | 'morning' | 'afternoon' | 'evening'
15
16// An activity shown, waiting the minute a pet may take to land.
17export type Shown = {
18  at: number
19  arm: Arm
20  daypart: Daypart
21  // The pet that showed it: a taste for one pet's nap says nothing of another's.
22  pet: string
23  activity: string
24  // The chance the learned pick had of naming it; null when picked by hand.
25  propensity: number | null
26  petted: number
27  annoyed: boolean
28}
29
30const DAY_MS = 24 * 60 * 60_000
31// Old enough evidence counts half: a changed taste wins back within days.
32export const HALF_LIFE_MS = 7 * DAY_MS
33// How long after an activity began a pet still counts for it.
34export const CREDIT_MS = 60_000
35// How a pick on a learning day weighs what the person likes, its own whims and
36// its weariness of what it just did; and how loosely it follows the sum.
37const TASTE = 1
38const WHIM = 0.8
39const WEARINESS = 0.9
40const TEMPERATURE = 0.8
41// The most the person's taste tips a pick, either way.
42const MOST_TASTE = 1
43// Whims drift from one to the next over this many days.
44const WHIM_DAYS = 3
45// Days are counted from here, in local time, so blocks of two line up anywhere.
46const EPOCH = new Date(2026, 0, 1).getTime()
47
48export const daypartOf = (hour: number): Daypart =>
49  hour < 6 ? 'night' : hour < 12 ? 'morning' : hour < 18 ? 'afternoon' : 'evening'
50
51// What the bandit learns per daypart and pet.
52const scopeOf = (daypart: Daypart, pet: string) => `${daypart}:${pet}:`
53const keyOf = (one: Shown) => scopeOf(one.daypart, one.pet) + one.activity
54
55// FNV-1a, then MurmurHash3's finalizer: FNV alone barely moves the high bits, nor
56// the low one, when only a string's last digit changes, as from one day to the next.
57const hash = (text: string) => {
58  let h = 0x811c9dc5
59  for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193)
60  h ^= h >>> 16
61  h = Math.imul(h, 0x85ebca6b)
62  h ^= h >>> 13
63  h = Math.imul(h, 0xc2b2ae35)
64  h ^= h >>> 16
65  return h >>> 0
66}
67
68// A number in [-1, 1] fixed by `text`.
69const unit = (text: string) => (hash(text) / 2 ** 32) * 2 - 1
70
71// Days go in pairs, one of each arm in a random order fixed by `seed`, so every
72// session on a day agrees and the arms stay even week to week.
73export const armOf = (seed: number, now: number): Arm => {
74  const day = daysBetween(EPOCH, now)
75  const block = Math.floor(day / 2)
76  const learnedFirst = hash(`${seed}:${block}`) % 2 === 0
77  return (day - block * 2 === 0) === learnedFirst ? 'learned' : 'hand'
78}
79
80// How much the pet feels like `activity` these days, in [-1, 1], whatever the
81// person likes: a smooth drift between values fixed every few days by `seed`, so
82// it takes to something for a while, then to something else.
83export const whimOf = (seed: number, pet: string, activity: string, now: number) => {
84  const x = (now - EPOCH) / DAY_MS / WHIM_DAYS
85  const k = Math.floor(x)
86  const t = x - k
87  const s = t * t * (3 - 2 * t)
88  return unit(`${seed}:${pet}:${activity}:${k}`) * (1 - s) + unit(`${seed}:${pet}:${activity}:${k + 1}`) * s
89}
90
91export type Pick = {
92  bandit: Bandit
93  seed: number
94  pet: string
95  daypart: Daypart
96  activities: string[]
97  // What it did lately, the latest first.
98  lately: string[]
99}
100
101// The pick among `activities` on a learning day, and the chance it had. Each one
102// scores by how much more than the others the person pets it for at this time
103// of day, by the pet's whim of the moment, and down for each time it did it
104// lately, the latest counting most; the pick is drawn by those scores.
105export const pickFor = (pick: Pick, now: number, random: Random) => {
106  const { bandit, seed, pet, daypart, activities, lately } = pick
107  const means = activities.map(name => mean(bandit, scopeOf(daypart, pet) + name, now, HALF_LIFE_MS))
108  const usual = means.reduce((a, b) => a + b, 0) / Math.max(1, means.length)
109  const scores = activities.map((name, i) => {
110    const taste = Math.max(-MOST_TASTE, Math.min(MOST_TASTE, Math.log((means[i] ?? usual) / usual)))
111    const weary = lately.reduce((sum, one, ago) => sum + (one === name ? 0.5 ** ago : 0), 0)
112    return TASTE * taste + WHIM * whimOf(seed, pet, name, now) - WEARINESS * weary
113  })
114  const top = Math.max(...scores)
115  const weights = scores.map(score => Math.exp((score - top) / TEMPERATURE))
116  const total = weights.reduce((a, b) => a + b, 0)
117  let left = random() * total
118  let index = weights.length - 1
119  for (let i = 0; i < weights.length; i++) {
120    left -= weights[i] ?? 0
121    if (left < 0) {
122      index = i
123      break
124    }
125  }
126  return { activity: activities[index] ?? '', propensity: (weights[index] ?? 0) / total }
127}
128
129// The temper it wakes up in on a learning day, fixed for the day by `seed`: most
130// days its usual self, else a little more playful, lazy, clingy or curious.
131export type Temper = 'usual' | 'playful' | 'lazy' | 'clingy' | 'curious'
132const TEMPERS: readonly Temper[] = ['usual', 'usual', 'playful', 'lazy', 'clingy', 'curious']
133// How far a temper moves the trait it touches.
134const NUDGE = 0.25
135
136export const temperOf = (seed: number, now: number): Temper =>
137  TEMPERS[hash(`${seed}:temper:${daysBetween(EPOCH, now)}`) % TEMPERS.length] ?? 'usual'
138
139const nudged = (value: number, by: number) => Math.min(1, Math.max(0, value + by))
140
141// The pet's traits for the day: an energetic one tires slower, a curious one gets
142// bored sooner, an affectionate one misses the person sooner.
143export const tempered = (traits: Traits, temper: Temper): Traits => {
144  switch (temper) {
145    case 'usual':
146      return traits
147    case 'playful':
148      return { ...traits, energetic: nudged(traits.energetic, NUDGE) }
149    case 'lazy':
150      return { ...traits, energetic: nudged(traits.energetic, -NUDGE) }
151    case 'clingy':
152      return { ...traits, affectionate: nudged(traits.affectionate, NUDGE) }
153    case 'curious':
154      return { ...traits, curious: nudged(traits.curious, NUDGE) }
155  }
156}
157
158// A pet shares itself evenly among the activities begun in the minute before it.
159export const petted = (shown: Shown[], now: number): Shown[] => {
160  const shares = credit(shown.map((one, i) => ({ action: String(i), at: one.at })), now, Infinity, CREDIT_MS)
161  return shown.map((one, i) => ({ ...one, petted: one.petted + (shares[String(i)] ?? 0) }))
162}
163
164export const annoyed = (shown: Shown[], now: number): Shown[] =>
165  shown.map(one => (now >= one.at && now - one.at <= CREDIT_MS ? { ...one, annoyed: true } : one))
166
167// What is past its minute counts for the bandit, a pet as 1 and nothing or an
168// annoyance as 0, whichever arm picked it; the rest keeps waiting.
169export const settle = (bandit: Bandit, shown: Shown[], now: number) => {
170  const done = shown.filter(one => now - one.at > CREDIT_MS)
171  let next = bandit
172  for (const one of done) next = reward(next, keyOf(one), Math.min(1, one.petted), one.at, HALF_LIFE_MS)
173  return { bandit: next, done, waiting: shown.filter(one => now - one.at <= CREDIT_MS) }
174}
175
176// One line of the log: what was shown and how it went, never what the person wrote.
177export const logLine = (one: Shown) =>
178  JSON.stringify({ kind: 'shown', ...one, reward: Math.min(1, one.petted) })
179
180// The store holds what anyone could have written: only well-formed tallies count.
181export const asBandit = (value: unknown): Bandit => {
182  if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}
183  const bandit: Bandit = {}
184  const count = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0
185  for (const [key, tally] of Object.entries(value)) {
186    const { wins, losses, at } = (tally ?? {}) as Partial<Record<keyof Tally, unknown>>
187    if (count(wins) && count(losses) && count(at)) bandit[key] = { wins, losses, at }
188  }
189  return bandit
190}
191
192// How unusual a prompt's moment is: its hour, how long the person was away and how
193// many tools the last turn ran. A moment seen fades back to news in a few days.
194export const FAMILIAR_HALF_LIFE_MS = 2 * DAY_MS
195// Fixed by its seed, never stored: every session codes a moment the same.
196const MOMENTS = coder(20, 1000, 50, 3, seeded(7))
197// It finds a moment odd from this novelty on, once it knows this many of the
198// person's moments, and not again for an hour.
199export const ODD = 0.75
200export const KNOWS = 50
201export const ODD_GAP_MS = 60 * 60_000
202
203export const momentCode = (hour: number, awayMinutes: number, tools: number) =>
204  encode(MOMENTS, [
205    ...bumps(hour, 0, 24, 8, true),
206    ...bumps(Math.min(awayMinutes, 120), 0, 120, 6),
207    ...bumps(Math.min(tools, 30), 0, 30, 6),
208  ])
209
210// The moments it has seen, and how familiar each cell is.
211export type Familiarity = { seen: number; cells: Familiar }
212
213export const asFamiliarity = (value: unknown): Familiarity => {
214  const { seen, cells } = (typeof value === 'object' && value !== null ? value : {}) as { seen?: unknown; cells?: unknown }
215  const familiar: Familiar = {}
216  if (typeof cells === 'object' && cells !== null && !Array.isArray(cells)) {
217    for (const [cell, kept] of Object.entries(cells)) {
218      const { level, at } = (kept ?? {}) as { level?: unknown; at?: unknown }
219      if (typeof level === 'number' && level >= 0 && level <= 1 && typeof at === 'number' && Number.isFinite(at))
220        familiar[Number(cell)] = { level, at }
221    }
222  }
223  return { seen: typeof seen === 'number' && seen >= 0 ? seen : 0, cells: familiar }
224}
225
hooks/memory.ts 38 lines
1import { isMorning } from './feelings'
2
3// What the pet remembers of the person across sessions, kept in `$.store`.
4export type Visit = { metAt: number; lastSeenAt: number }
5
6// How a session opens, at most one: the first that applies wins.
7export type Welcome = { kind: 'anniversary'; days: number } | { kind: 'missedYou' } | { kind: 'goodMorning' }
8
9const DAY_MS = 24 * 60 * 60_000
10const MILESTONES = [7, 30, 100]
11const MISSED_DAYS = 2
12
13const midnight = (time: number) => new Date(time).setHours(0, 0, 0, 0)
14
15// Calendar days from `from` to `to`, in local time.
16export const daysBetween = (from: number, to: number) => Math.round((midnight(to) - midnight(from)) / DAY_MS)
17
18export const isAnniversary = (days: number) => MILESTONES.includes(days) || (days > 0 && days % 365 === 0)
19
20export const welcome = (visit: Visit | undefined, now: number, hour: number): Welcome | undefined => {
21  if (visit !== undefined) {
22    const away = daysBetween(visit.lastSeenAt, now)
23    // Seen already today: the day's welcome is spent.
24    if (away === 0) return undefined
25    const age = daysBetween(visit.metAt, now)
26    if (isAnniversary(age)) return { kind: 'anniversary', days: age }
27    if (away >= MISSED_DAYS) return { kind: 'missedYou' }
28  }
29  return isMorning(hour) ? { kind: 'goodMorning' } : undefined
30}
31
32// The store holds what anyone could have written: only a well-formed visit counts.
33export const asVisit = (value: unknown): Visit | undefined => {
34  if (typeof value !== 'object' || value === null) return undefined
35  const { metAt, lastSeenAt } = value as Record<string, unknown>
36  return typeof metAt === 'number' && typeof lastSeenAt === 'number' ? { metAt, lastSeenAt } : undefined
37}
38
hooks/motion.ts 231 lines
1import type { Frame, Mood } from '../types'
2import type { Urge } from './drives'
3import { WORK } from './pack'
4import type { Action, Pack } from './pack'
5
6// What the main pet is playing. Kept between draws so a loop runs from its own
7// start and a one-off finishes before the loop picks up again.
8export type Motion = {
9  // The pack its frames are from: another pet's motion starts over.
10  pack: Pack
11  mood: Mood
12  loop: Frame[]
13  // The tick the mood started on, before its transition.
14  began: number
15  // The tick the loop's first frame plays on.
16  since: number
17  // A transition or an action, played once from `start`; an action that startles
18  // the agents does so from its frame `startles` on. `activity` names the activity it is.
19  once?: { frames: Frame[]; start: number; isAction: boolean; startles?: number; activity?: string }
20  // The tick from which each action may play again.
21  next: Record<string, number>
22  // At work, the tick it next drifts off to something else.
23  distractAt?: number
24}
25
26// A number in [0, 1): Math.random in the plugin, a fixed sequence in tests.
27export type Random = () => number
28
29// How long a work mood shows before another work mood may take over.
30const DWELL_SECONDS = 1
31// An action this close to its end finishes before the mood changes.
32const FOLLOW_THROUGH_TICKS = 2
33// Moods of a pet strolling about: going between them is one stretch, so their
34// actions keep their timers rather than start over at every stop.
35const ROAMING: ReadonlySet<Mood> = new Set(['idle', 'proud', 'walking'])
36const ASLEEP: ReadonlySet<Mood> = new Set(['sleeping', 'deepSleep'])
37// A long stretch in one work mood: after this long it drifts off now and then, for
38// a few seconds at most, and comes back to it.
39const SETTLE_SECONDS = 20
40const DISTRACT_EVERY: [number, number] = [15, 40]
41const DISTRACT_MAX_SECONDS = 8
42// How long it looks for the person when it misses them.
43const GLANCE_SECONDS = 2
44
45const ticks = (seconds: number, fps: number) => Math.max(1, Math.round(seconds * fps))
46
47const someTime = ([min, max]: [number, number], fps: number, random: Random) => ticks(min + (max - min) * random(), fps)
48
49// What one play of `action` shows: for an activity, its start, its loop for its
50// seconds drawn at random rounded up to whole loops, and its end.
51export const playOf = (action: Action, fps: number, random: Random): Frame[] => {
52  if (action.activity === undefined) return action.frames
53  const { loop, seconds, end } = action.activity
54  const loops = Math.ceil(someTime(seconds, fps, random) / loop.length)
55  return [...action.frames, ...Array.from({ length: loops }, () => loop).flat(), ...end]
56}
57
58// The activity the pet is in the middle of on `tick`, if any.
59export const activityIn = (motion: Motion | undefined, tick: number) => {
60  const once = motion?.once
61  return once !== undefined && tick < once.start + once.frames.length ? once.activity : undefined
62}
63
64export const transitionFor = (pack: Pack, from: Mood, to: Mood) =>
65  pack.transitions[`${from}>${to}`] ?? pack.transitions[`${from}>*`] ?? pack.transitions[`*>${to}`]
66
67const start = (pack: Pack, previous: Motion | undefined, mood: Mood, tick: number, random: Random): Motion => {
68  const loops = [pack.moods[mood], ...pack.variants[mood]]
69  const loop = loops[Math.floor(random() * loops.length)] ?? pack.moods[mood]
70  const transition = previous === undefined ? undefined : transitionFor(pack, previous.mood, mood)
71  const roams = previous !== undefined && ROAMING.has(previous.mood) && ROAMING.has(mood)
72  const next: Record<string, number> = roams ? { ...previous.next } : {}
73  for (const action of pack.actions) {
74    // An activity at work waits for it to drift off: it never plays on its own timer.
75    const isDistraction = action.activity !== undefined && WORK.has(mood)
76    if (action.moods.includes(mood) && !isDistraction && next[action.name] === undefined) next[action.name] = tick + someTime(action.every, pack.fps, random)
77  }
78  // Up from a nap, it soon goes off to do something: one activity of the stroll is due
79  // as soon as it is up, and waits through a walk for it to stop.
80  if (previous !== undefined && ASLEEP.has(previous.mood) && ROAMING.has(mood)) {
81    const ready = pack.actions.filter(one => one.activity !== undefined && one.moods.some(m => ROAMING.has(m)))
82    const picked = ready.length === 0 ? undefined : ready[Math.floor(random() * ready.length)]
83    if (picked !== undefined) next[picked.name] = tick + (transition?.length ?? 0)
84  }
85  return {
86    pack,
87    mood,
88    loop,
89    began: tick,
90    since: tick + (transition?.length ?? 0),
91    once: transition === undefined ? undefined : { frames: transition, start: tick, isAction: false },
92    next,
93    ...(WORK.has(mood) ? { distractAt: tick + ticks(SETTLE_SECONDS, pack.fps) } : {}),
94  }
95}
96
97// The wait until it drifts off again: a curious pet does sooner.
98const distractAgain = (pack: Pack, random: Random) =>
99  Math.round(someTime(DISTRACT_EVERY, pack.fps, random) / (0.5 + pack.personality.curious))
100
101const pickFrom = <T>(list: T[], random: Random) => list[Math.floor(random() * list.length)]
102
103// What a pet at work in `mood` drifts off to, by what it feels like: what its pack
104// draws for that mood first, else borrowed from where it would do it anyway. What
105// already plays in `mood`, a blink, is no change of scene. A tired pet with nothing
106// tired to do, or one that does not draw looking for the person, finds something else.
107const distractionFor = (pack: Pack, mood: Mood, urge: Urge, random: Random): Action | undefined => {
108  const own = pack.actions.filter(one => one.activity !== undefined && one.moods.includes(mood))
109  if (own.length > 0) return pickFrom(own, random)
110  const elsewhere = pack.actions.filter(one => !one.moods.includes(mood))
111  const doneIn = (moods: Mood[]) => elsewhere.filter(one => one.moods.some(m => moods.includes(m)))
112  if (urge === 'tired') {
113    const tired = doneIn(['tired', 'sleepy'])
114    if (tired.length > 0) return pickFrom(tired, random)
115  }
116  if (urge === 'longing' && pack.drawn.has('watching')) {
117    const loop = pack.moods.watching
118    const length = ticks(GLANCE_SECONDS, pack.fps)
119    return { name: 'watching', frames: Array.from({ length }, (_, i) => loop[i % loop.length] ?? []), moods: [mood], every: DISTRACT_EVERY }
120  }
121  const idle = doneIn(['idle'])
122  const activities = idle.filter(one => one.activity !== undefined)
123  return pickFrom(activities.length > 0 ? activities : idle, random)
124}
125
126// One play of a distraction: an activity cut down to the whole loops that fit a few
127// seconds, its start and end included, and one loop at least.
128const briefly = (action: Action, fps: number): Action => {
129  if (action.activity === undefined) return action
130  const { loop, end } = action.activity
131  const room = ticks(DISTRACT_MAX_SECONDS, fps) - action.frames.length - end.length
132  const most = (Math.max(1, Math.floor(room / loop.length)) * loop.length) / fps
133  const [min, max] = action.activity.seconds
134  return { ...action, activity: { ...action.activity, seconds: [Math.min(min, most), Math.min(max, most)] } }
135}
136
137// Whether it keeps playing `motion` on `tick` though the mood is now `mood`: a work
138// mood shows a moment before the next one, and an action about to end finishes.
139// Anything else, a reaction or sleep, takes over at once.
140const holds = (pack: Pack, motion: Motion, mood: Mood, tick: number) => {
141  if (WORK.has(motion.mood) && WORK.has(mood) && tick - motion.began < ticks(DWELL_SECONDS, pack.fps)) return true
142  const left = motion.once === undefined ? 0 : motion.once.start + motion.once.frames.length - tick
143  return motion.once?.isAction === true && left > 0 && left <= FOLLOW_THROUGH_TICKS
144}
145
146// The frame to draw on `tick`, and how many ticks ago it began to startle the
147// agents, if it does. Safe to call more than once per tick: the same tick gives
148// the same frame.
149// `urge`, what the pet feels like, lets it drift off at work; without it, it never does.
150// `choose`, given the activities of the mood when one falls due, names the one to play
151// instead; without it, the one due plays.
152export const step = (
153  pack: Pack,
154  given: Motion | undefined,
155  mood: Mood,
156  tick: number,
157  random: Random,
158  urge?: Urge,
159  choose?: (activities: string[]) => string,
160) => {
161  const previous = given?.pack === pack ? given : undefined
162  let motion =
163    previous !== undefined && (previous.mood === mood || holds(pack, previous, mood, tick))
164      ? previous
165      : start(pack, previous, mood, tick, random)
166
167  if (motion.once !== undefined) {
168    const at = tick - motion.once.start
169    const frame = motion.once.frames[at]
170    const { startles } = motion.once
171    const startled = startles !== undefined && at >= startles ? at - startles : undefined
172    if (frame !== undefined) return { motion, frame, startled }
173    motion = { ...motion, once: undefined }
174  }
175
176  // A mood on its way out starts no new action.
177  const isLeaving = motion.mood !== mood
178  // Kept timers may belong to another mood of the stroll: only its own actions play.
179  const mine = pack.actions.filter(action => action.moods.includes(motion.mood))
180  const isDue = (action: Action) => (motion.next[action.name] ?? Infinity) <= tick
181
182  // Drifting off goes before its own actions: a blink due with it would put it off.
183  if (!isLeaving && urge !== undefined && (motion.distractAt ?? Infinity) <= tick) {
184    const picked = distractionFor(pack, motion.mood, urge, random)
185    if (picked === undefined) {
186      motion = { ...motion, distractAt: undefined }
187    } else {
188      const frames = playOf(briefly(picked, pack.fps), pack.fps, random)
189      const ends = tick + frames.length
190      const next = { ...motion.next }
191      for (const other of mine) {
192        if ((next[other.name] ?? Infinity) <= ends) next[other.name] = ends + someTime(other.every, pack.fps, random)
193      }
194      // Not its pastime: the line keeps saying what Claude is doing.
195      const once = { frames, start: tick, isAction: true }
196      motion = { ...motion, once, next, distractAt: ends + distractAgain(pack, random) }
197      return { motion, frame: frames[0] ?? [], startled: undefined }
198    }
199  }
200  // An activity due goes first: a blink due with it would otherwise put it off.
201  let due = isLeaving ? undefined : (mine.find(one => one.activity !== undefined && isDue(one)) ?? mine.find(isDue))
202  if (due?.activity !== undefined && choose !== undefined) {
203    const activities = mine.filter(one => one.activity !== undefined)
204    const name = choose(activities.map(one => one.name))
205    // The one due waits its own time again below, as anything due meanwhile does.
206    due = activities.find(one => one.name === name) ?? due
207  }
208  if (due !== undefined) {
209    const frames = playOf(due, pack.fps, random)
210    const ends = tick + frames.length
211    // One thing at a time: what falls due meanwhile waits its own time again from the
212    // end, rather than all of it playing back to back after.
213    const next = { ...motion.next, [due.name]: ends + someTime(due.every, pack.fps, random) }
214    for (const other of mine) {
215      if (other !== due && (next[other.name] ?? Infinity) <= ends) next[other.name] = ends + someTime(other.every, pack.fps, random)
216    }
217    const once = {
218      frames,
219      start: tick,
220      isAction: true,
221      startles: due.startles,
222      ...(due.activity === undefined ? {} : { activity: due.name }),
223    }
224    motion = { ...motion, once, next }
225    return { motion, frame: frames[0] ?? [], startled: due.startles === 0 ? 0 : undefined }
226  }
227
228  const at = (((tick - motion.since) % motion.loop.length) + motion.loop.length) % motion.loop.length
229  return { motion, frame: motion.loop[at] ?? [], startled: undefined }
230}
231
hooks/gestures.ts 33 lines
1// What the person does to the pet with the pointer: a click pets it, one over a
2// sleeping pet wakes it, too many in a row annoy it, and a pointer resting on it
3// a moment gets a look back. Session only.
4export type Touch = { clicks: readonly number[]; grumpyUntil: number; hoverSince: number | null }
5
6export const untouched: Touch = { clicks: [], grumpyUntil: 0, hoverSince: null }
7
8// How it takes a click: awake it is petted, dozing it wakes glad, fast asleep it is
9// woken rudely; annoyed by many, it ignores the rest for a while.
10export type Poke = 'pet' | 'wake' | 'rouse' | 'annoy' | 'ignore'
11export type Sleep = 'awake' | 'dozing' | 'deep'
12
13// This many clicks within the window annoy it, for ANNOY_MS.
14const ANNOY_CLICKS = 4
15const ANNOY_WINDOW_MS = 3000
16export const ANNOY_MS = 3000
17// How long the pointer rests on it before it looks back.
18const GAZE_MS = 500
19
20export const press = (touch: Touch, now: number, sleep: Sleep): { touch: Touch; poke: Poke } => {
21  if (now < touch.grumpyUntil) return { touch, poke: 'ignore' }
22  const clicks = [...touch.clicks.filter(at => now - at < ANNOY_WINDOW_MS), now]
23  if (clicks.length >= ANNOY_CLICKS) return { touch: { ...touch, clicks: [], grumpyUntil: now + ANNOY_MS }, poke: 'annoy' }
24  return { touch: { ...touch, clicks }, poke: sleep === 'deep' ? 'rouse' : sleep === 'dozing' ? 'wake' : 'pet' }
25}
26
27// The pointer is over it: from the first move, as an `enter` does not always come.
28export const hover = (touch: Touch, now: number): Touch => (touch.hoverSince === null ? { ...touch, hoverSince: now } : touch)
29
30export const leave = (touch: Touch): Touch => ({ ...touch, hoverSince: null })
31
32export const gazes = (touch: Touch, now: number) => touch.hoverSince !== null && now - touch.hoverSince >= GAZE_MS
33
hooks/pack.ts 445 lines
1import type { Frame, MiniMood, Mood, PackFile, Situation, Traits } from '../types'
2import { USUAL } from './drives'
3import { hexColor, rowsOf, widthOf } from './render'
4import { SITUATIONS } from './speech'
5import type { Colors } from './render'
6
7// Each mood a pack leaves out borrows from its parent, so an old or small pack
8// still shows something close. `sleeping` is the root every pack must draw.
9export const PARENT: Record<Mood, Mood | null> = {
10  sleeping: null,
11  deepSleep: 'sleeping',
12  idle: 'thinking',
13  sleepy: 'idle',
14  tired: 'sleepy',
15  walking: 'idle',
16  watching: 'reading',
17  thinking: 'sleeping',
18  waking: 'thinking',
19  typing: 'thinking',
20  running: 'typing',
21  writing: 'typing',
22  reading: 'thinking',
23  searching: 'reading',
24  supervising: 'thinking',
25  compacting: 'thinking',
26  sweating: 'thinking',
27  worried: 'sweating',
28  grumpy: 'sad',
29  proud: 'happy',
30  happy: 'sleeping',
31  celebrating: 'happy',
32  sad: 'sleeping',
33}
34
35export const MOODS = Object.keys(PARENT) as Mood[]
36
37// Moods of a turn at work.
38export const WORK: ReadonlySet<Mood> = new Set(['thinking', 'typing', 'running', 'writing', 'reading', 'searching', 'supervising'])
39
40export const MINI_MOODS: readonly MiniMood[] = ['working', 'happy', 'sad', 'startled']
41
42export const DEFAULT_PET = 'cat'
43
44const LIMITS = {
45  main: { columns: 48, pixelRows: 32 },
46  mini: { columns: 12, pixelRows: 12 },
47  framesPerMood: 16,
48  variantsPerMood: 4,
49  transitions: 32,
50  actions: 32,
51  activities: 8,
52  activitySeconds: { min: 5, max: 300 },
53  everySeconds: { min: 1, max: 600 },
54  linesPerSituation: 8,
55  lineLength: 40,
56  paletteSize: 16,
57  fps: { min: 1, max: 12 },
58}
59
60// A longer scene: `frames` (its start) once, `loop` for `seconds`, `end` once.
61export type Activity = { loop: Frame[]; seconds: [number, number]; end: Frame[]; label: Record<string, string> }
62
63export type Action = { name: string; frames: Frame[]; moods: Mood[]; every: [number, number]; startles?: number; activity?: Activity }
64
65export type Pack = {
66  name: string
67  colors: Colors
68  fps: number
69  // The loop each mood plays, borrowed from a parent when the pack leaves it out.
70  moods: Record<Mood, Frame[]>
71  // More loops for a mood, following the same borrowing as `moods`.
72  variants: Record<Mood, Frame[][]>
73  transitions: Record<string, Frame[]>
74  actions: Action[]
75  // null when the pack draws no mini pets: its agents show only as its own `supervising`.
76  mini: Record<MiniMood, Frame[]> | null
77  tint: string
78  // false: the pet never flips, facing you whichever way it goes.
79  mirrors: boolean
80  // Only a pack that draws `walking` leaves its spot by walking; one that draws
81  // `teleport` and no `walking` gets about by vanishing and appearing.
82  walks: boolean
83  // The moods it draws itself, rather than borrows.
84  drawn: ReadonlySet<Mood>
85  teleport: { vanish: Frame[]; appear: Frame[] } | null
86  speech: Record<string, Partial<Record<Situation, string[]>>>
87  personality: Traits
88}
89
90const isRecord = (value: unknown): value is Record<string, unknown> =>
91  typeof value === 'object' && value !== null && !Array.isArray(value)
92
93type Limit = { columns: number; pixelRows: number }
94type CheckFrames = (frames: unknown, where: string, limit: Limit) => Frame[]
95
96const isRows = (value: unknown): value is string[] =>
97  Array.isArray(value) && value.length > 0 && value.every(row => typeof row === 'string')
98
99// What a terminal does not draw one cell wide: wide (CJK, Hangul, fullwidth, emoji),
100// zero-width and control characters.
101const NOT_ONE_CELL =
102  /[\p{Cc}\p{Cf}\p{M}\p{Emoji_Presentation}\u1100-\u115f\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua000-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{20000}-\u{3fffd}]/u
103
104// An ascii frame is its art, or its art and a mask of palette letters ('.' the ink).
105const toGlyphs = (frame: unknown, where: string, colors: Colors): Frame => {
106  const given = Array.isArray(frame) ? { art: frame } : isRecord(frame) ? frame : {}
107  if (!isRows(given.art)) throw new Error(`${where}: a frame is a list of strings, or { art, color }`)
108  const art = given.art
109  const wide = NOT_ONE_CELL.exec(art.join(''))
110  if (wide !== null) throw new Error(`${where}: ${JSON.stringify(wide[0])} does not draw one cell wide`)
111  const { color } = given
112  if (color === undefined) return { art, color: art.map(row => '.'.repeat(widthOf(row))) }
113  if (!isRows(color) || color.length !== art.length || color.some((row, r) => widthOf(row) !== widthOf(art[r]))) {
114    throw new Error(`${where}.color: same rows and widths as art`)
115  }
116  const stray = [...color.join('')].find(letter => colors[letter] === undefined)
117  if (stray !== undefined) throw new Error(`${where}.color: "${stray}" is not in the palette, use "." for ink`)
118  return { art, color }
119}
120
121const framesChecker =
122  (ascii: boolean, colors: Colors): CheckFrames =>
123  (frames, where, limit) => {
124    if (!Array.isArray(frames) || frames.length === 0) throw new Error(`${where}: needs at least one frame`)
125    if (frames.length > LIMITS.framesPerMood) throw new Error(`${where}: at most ${LIMITS.framesPerMood} frames`)
126    return frames.map((raw, i) => {
127      const at = `${where}[${i}]`
128      if (!ascii && !isRows(raw)) throw new Error(`${at}: a frame is a list of strings`)
129      const frame = ascii ? toGlyphs(raw, at, colors) : (raw as string[])
130      const rows = rowsOf(frame)
131      const width = widthOf(rows[0])
132      if (width === 0 || rows.some(row => widthOf(row) !== width)) throw new Error(`${at}: every row needs the same length`)
133      // An ascii row is a whole cell, two pixel rows: the same room on the terminal.
134      const height = ascii ? limit.pixelRows / 2 : limit.pixelRows
135      if (width > limit.columns || rows.length > height) {
136        throw new Error(`${at}: at most ${limit.columns}x${height} ${ascii ? 'cells' : 'pixels'}`)
137      }
138      return frame
139    })
140  }
141
142const sameSize = (frames: Frame[], where: string) => {
143  const [first] = frames
144  const size = (frame: Frame | undefined) => {
145    const rows = frame === undefined ? [] : rowsOf(frame)
146    return `${widthOf(rows[0])}x${rows.length}`
147  }
148  if (frames.some(f => size(f) !== size(first))) {
149    throw new Error(`${where}: every frame needs the same size`)
150  }
151}
152
153const isMood = (value: unknown): value is Mood => typeof value === 'string' && MOODS.includes(value as Mood)
154
155// Variants hang off a mood the pack draws: one on a borrowed mood would never show.
156const parseVariants = (checkFrames: CheckFrames, raw: unknown, drawn: Map<Mood, Frame[]>) => {
157  const out = new Map<Mood, Frame[][]>()
158  if (raw === undefined) return out
159  if (!isRecord(raw)) throw new Error('main.variants: an object of mood to loops')
160  for (const [mood, loops] of Object.entries(raw)) {
161    if (!isMood(mood)) throw new Error(`main.variants: unknown mood ${mood}`)
162    if (!drawn.has(mood)) throw new Error(`main.variants.${mood}: draw main.moods.${mood} first`)
163    if (!Array.isArray(loops) || loops.length === 0 || loops.length > LIMITS.variantsPerMood) {
164      throw new Error(`main.variants.${mood}: 1 to ${LIMITS.variantsPerMood} loops`)
165    }
166    out.set(mood, loops.map((loop, i) => checkFrames(loop, `main.variants.${mood}[${i}]`, LIMITS.main)))
167  }
168  return out
169}
170
171const TRANSITION = /^(\*|[a-zA-Z]+)>(\*|[a-zA-Z]+)$/
172
173const parseTransitions = (checkFrames: CheckFrames, raw: unknown) => {
174  const out: Record<string, Frame[]> = {}
175  if (raw === undefined) return out
176  if (!isRecord(raw)) throw new Error('main.transitions: an object of "from>to" to frames')
177  const entries = Object.entries(raw)
178  if (entries.length > LIMITS.transitions) throw new Error(`main.transitions: at most ${LIMITS.transitions}`)
179  for (const [key, frames] of entries) {
180    const [, from, to] = TRANSITION.exec(key) ?? []
181    const known = (side: string | undefined) => side === '*' || isMood(side)
182    if (!known(from) || !known(to) || key === '*>*') {
183      throw new Error(`main.transitions: "${key}" must be "from>to" with moods or one "*"`)
184    }
185    out[key] = checkFrames(frames, `main.transitions.${key}`, LIMITS.main)
186  }
187  return out
188}
189
190const ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,31}$/
191
192const LANGUAGE = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})?$/
193
194// Plain one-line text, short enough for the band.
195const isLine = (line: unknown): line is string =>
196  typeof line === 'string' && line.trim() !== '' && line.length <= LIMITS.lineLength && !/[\u0000-\u001f\u007f]/.test(line)
197
198const checkMoods = (moods: unknown, where: string): Mood[] => {
199  if (!Array.isArray(moods) || moods.length === 0 || !moods.every(isMood)) throw new Error(`${where}.moods: a list of moods`)
200  return moods
201}
202
203const checkRange = (range: unknown, where: string, { min, max }: { min: number; max: number }): [number, number] => {
204  if (
205    !Array.isArray(range) ||
206    range.length !== 2 ||
207    !range.every(n => typeof n === 'number' && n >= min && n <= max) ||
208    range[0] > range[1]
209  ) {
210    throw new Error(`${where}: [min, max] seconds, ${min} to ${max}`)
211  }
212  return [range[0], range[1]]
213}
214
215const parseActions = (checkFrames: CheckFrames, raw: unknown): Action[] => {
216  if (raw === undefined) return []
217  if (!isRecord(raw)) throw new Error('main.actions: an object of name to action')
218  const entries = Object.entries(raw)
219  if (entries.length > LIMITS.actions) throw new Error(`main.actions: at most ${LIMITS.actions}`)
220  return entries.map(([name, action]) => {
221    const where = `main.actions.${name}`
222    if (!ACTION_NAME.test(name)) throw new Error(`${where}: name with letters, digits, - or _ (up to 32)`)
223    if (!isRecord(action)) throw new Error(`${where}: needs frames, moods and every`)
224    const moods = checkMoods(action.moods, where)
225    const every = checkRange(action.every, `${where}.every`, LIMITS.everySeconds)
226    const frames = checkFrames(action.frames, `${where}.frames`, LIMITS.main)
227    const { startles } = action
228    if (startles === undefined) return { name, frames, moods, every }
229    if (typeof startles !== 'number' || !Number.isInteger(startles) || startles < 0 || startles >= frames.length) {
230      throw new Error(`${where}.startles: one of its frames, 0 to ${frames.length - 1}`)
231    }
232    return { name, frames, moods, every, startles }
233  })
234}
235
236// Where an activity can play: idle, or what stands in for it, and at work, where it
237// is something the pet drifts off to now and then. Walking would cut it at once, and
238// sleep would fight it.
239const PASTIMES: ReadonlySet<Mood> = new Set(['idle', 'proud', 'sleepy', 'tired', 'worried', 'grumpy', ...WORK])
240
241const parseActivities = (checkFrames: CheckFrames, raw: unknown, taken: ReadonlySet<string>): Action[] => {
242  if (raw === undefined) return []
243  if (!isRecord(raw)) throw new Error('main.activities: an object of name to activity')
244  const entries = Object.entries(raw)
245  if (entries.length > LIMITS.activities) throw new Error(`main.activities: at most ${LIMITS.activities}`)
246  return entries.map(([name, activity]) => {
247    const where = `main.activities.${name}`
248    if (!ACTION_NAME.test(name)) throw new Error(`${where}: name with letters, digits, - or _ (up to 32)`)
249    // Actions and activities keep their timers side by side, by name.
250    if (taken.has(name)) throw new Error(`${where}: an action has this name already`)
251    if (!isRecord(activity)) throw new Error(`${where}: needs loop, seconds, moods and every`)
252    const optional = (frames: unknown, part: string) => (frames === undefined ? [] : checkFrames(frames, `${where}.${part}`, LIMITS.main))
253    const label: Record<string, string> = {}
254    if (activity.label !== undefined) {
255      if (!isRecord(activity.label)) throw new Error(`${where}.label: an object of language to words`)
256      for (const [code, words] of Object.entries(activity.label)) {
257        if (!LANGUAGE.test(code)) throw new Error(`${where}.label: "${code}" is not a language code like "en" or "pt-BR"`)
258        if (!isLine(words)) throw new Error(`${where}.label.${code}: one line, up to ${LIMITS.lineLength} characters`)
259        label[code] = words
260      }
261    }
262    const moods = checkMoods(activity.moods, where)
263    const restless = moods.find(mood => !PASTIMES.has(mood))
264    if (restless !== undefined) throw new Error(`${where}.moods: "${restless}" is not a mood it can pass the time in (${new Intl.ListFormat('en', { type: 'disjunction' }).format([...PASTIMES])})`)
265    return {
266      name,
267      frames: optional(activity.start, 'start'),
268      moods,
269      every: checkRange(activity.every, `${where}.every`, LIMITS.everySeconds),
270      activity: {
271        loop: checkFrames(activity.loop, `${where}.loop`, LIMITS.main),
272        seconds: checkRange(activity.seconds, `${where}.seconds`, LIMITS.activitySeconds),
273        end: optional(activity.end, 'end'),
274        label,
275      },
276    }
277  })
278}
279
280const parseTeleport = (checkFrames: CheckFrames, raw: unknown) => {
281  if (raw === undefined) return null
282  if (!isRecord(raw)) throw new Error('main.teleport: an object with vanish and appear frames')
283  return {
284    vanish: checkFrames(raw.vanish, 'main.teleport.vanish', LIMITS.main),
285    appear: checkFrames(raw.appear, 'main.teleport.appear', LIMITS.main),
286  }
287}
288
289// Each trait a number from 0 to 1; one left out is the usual.
290const parsePersonality = (raw: unknown): Traits => {
291  if (raw === undefined) return USUAL
292  if (!isRecord(raw)) throw new Error('personality: an object of trait to a number from 0 to 1')
293  const traits = { ...USUAL }
294  for (const [trait, value] of Object.entries(raw)) {
295    if (!Object.hasOwn(USUAL, trait)) throw new Error(`personality.${trait}: unknown trait, use ${Object.keys(USUAL).join(', ')}`)
296    if (typeof value !== 'number' || !(value >= 0 && value <= 1)) throw new Error(`personality.${trait}: a number from 0 to 1`)
297    traits[trait as keyof Traits] = value
298  }
299  return traits
300}
301
302// Lines are shown as they are: plain one-line text, short enough for the band.
303const parseSpeech = (raw: unknown) => {
304  const out: Record<string, Partial<Record<Situation, string[]>>> = {}
305  if (raw === undefined) return out
306  if (!isRecord(raw)) throw new Error('speech: an object of language to situations')
307  for (const [code, situations] of Object.entries(raw)) {
308    if (!LANGUAGE.test(code)) throw new Error(`speech: "${code}" is not a language code like "en" or "pt-BR"`)
309    if (!isRecord(situations)) throw new Error(`speech.${code}: an object of situation to lines`)
310    const lines: Partial<Record<Situation, string[]>> = {}
311    for (const [situation, list] of Object.entries(situations)) {
312      const where = `speech.${code}.${situation}`
313      if (!SITUATIONS.includes(situation as Situation)) throw new Error(`${where}: unknown situation, use ${SITUATIONS.join(', ')}`)
314      const { linesPerSituation: most, lineLength: longest } = LIMITS
315      if (!Array.isArray(list) || list.length === 0 || list.length > most || !list.every(isLine)) {
316        throw new Error(`${where}: 1 to ${most} lines of one line each, up to ${longest} characters`)
317      }
318      lines[situation as Situation] = list
319    }
320    out[code] = lines
321  }
322  return out
323}
324
325// Packs come from anyone, so everything is checked before it reaches the renderer.
326export const parsePack = (raw: unknown): Pack => {
327  if (!isRecord(raw)) throw new Error('a pack is a JSON object')
328  const file = raw as Partial<PackFile>
329
330  if (typeof file.name !== 'string' || file.name === '') throw new Error('name: required')
331
332  const style = file.style ?? 'pixel'
333  if (style !== 'pixel' && style !== 'ascii') throw new Error('style: "pixel" or "ascii"')
334  const ascii = style === 'ascii'
335
336  if (!isRecord(file.palette) && !(ascii && file.palette === undefined)) throw new Error('palette: required')
337  const entries = Object.entries(file.palette ?? {})
338  if (entries.length > LIMITS.paletteSize) throw new Error(`palette: at most ${LIMITS.paletteSize} colors`)
339  const colors: Colors = {}
340  for (const [letter, hex] of entries) {
341    if (letter.length !== 1 || letter === '.') throw new Error(`palette: "${letter}" must be one character other than "."`)
342    if (typeof hex !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(hex)) throw new Error(`palette.${letter}: use #rrggbb`)
343    colors[letter] = hexColor(hex)
344  }
345  // The ink takes '.', which a pixel pack keeps see-through.
346  if (ascii) {
347    if (typeof file.ink !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(file.ink)) throw new Error('ink: required for an ascii pack, use #rrggbb')
348    colors['.'] = hexColor(file.ink)
349  } else if (file.ink !== undefined) {
350    throw new Error('ink: only for an ascii pack')
351  }
352  const mirrors = file.mirror ?? true
353  if (typeof mirrors !== 'boolean') throw new Error('mirror: true or false')
354  const checkFrames = framesChecker(ascii, colors)
355
356  const fps = file.fps ?? 4
357  if (typeof fps !== 'number' || fps < LIMITS.fps.min || fps > LIMITS.fps.max) {
358    throw new Error(`fps: between ${LIMITS.fps.min} and ${LIMITS.fps.max}`)
359  }
360
361  if (!isRecord(file.main) || !isRecord(file.main.moods)) throw new Error('main.moods: required')
362  const given = file.main.moods as Record<string, unknown>
363  if (given.sleeping === undefined) throw new Error('main.moods.sleeping: required, other moods fall back to it')
364  const unknown = Object.keys(given).filter(key => !MOODS.includes(key as Mood))
365  if (unknown.length > 0) throw new Error(`main.moods: unknown mood ${unknown.join(', ')}`)
366
367  const drawn = new Map<Mood, Frame[]>()
368  for (const mood of MOODS) {
369    if (given[mood] !== undefined) drawn.set(mood, checkFrames(given[mood], `main.moods.${mood}`, LIMITS.main))
370  }
371  const extra = parseVariants(checkFrames, file.main.variants, drawn)
372  const moods = {} as Record<Mood, Frame[]>
373  const variants = {} as Record<Mood, Frame[][]>
374  for (const mood of MOODS) {
375    let source: Mood | null = mood
376    while (source !== null && !drawn.has(source)) source = PARENT[source]
377    moods[mood] = drawn.get(source ?? 'sleeping') ?? []
378    variants[mood] = extra.get(source ?? 'sleeping') ?? []
379  }
380  const transitions = parseTransitions(checkFrames, file.main.transitions)
381  const own = parseActions(checkFrames, file.main.actions)
382  const actions = [...own, ...parseActivities(checkFrames, file.main.activities, new Set(own.map(one => one.name)))]
383  const teleport = parseTeleport(checkFrames, file.main.teleport)
384  sameSize(
385    [
386      ...drawn.values(),
387      ...[...extra.values()].flat(),
388      ...Object.values(transitions),
389      ...actions.flatMap(a => [a.frames, a.activity?.loop ?? [], a.activity?.end ?? []]),
390      ...(teleport === null ? [] : [teleport.vanish, teleport.appear]),
391    ].flat(),
392    'main',
393  )
394
395  const { mini, tint } = file.mini === false ? { mini: null, tint: 'b' } : parseMini(checkFrames, file.mini, colors, ascii)
396
397  const speech = parseSpeech(file.speech)
398  const personality = parsePersonality(file.personality)
399
400  return {
401    name: file.name,
402    colors,
403    fps,
404    moods,
405    variants,
406    transitions,
407    actions,
408    mini,
409    tint,
410    mirrors,
411    walks: drawn.has('walking'),
412    drawn: new Set(drawn.keys()),
413    teleport,
414    speech,
415    personality,
416  }
417}
418
419const parseMini = (checkFrames: CheckFrames, raw: unknown, colors: Colors, ascii: boolean) => {
420  if (!isRecord(raw) || !isRecord(raw.moods)) throw new Error('mini.moods: required, or mini: false for no mini pets')
421  const miniGiven = raw.moods as Record<string, unknown>
422  if (miniGiven.working === undefined) throw new Error('mini.moods.working: required, happy, sad and startled fall back to it')
423  const miniUnknown = Object.keys(miniGiven).filter(key => !MINI_MOODS.includes(key as MiniMood))
424  if (miniUnknown.length > 0) throw new Error(`mini.moods: unknown mood ${miniUnknown.join(', ')}`)
425  const working = checkFrames(miniGiven.working, 'mini.moods.working', LIMITS.mini)
426  const mini = { working } as Record<MiniMood, Frame[]>
427  for (const mood of MINI_MOODS) {
428    mini[mood] = miniGiven[mood] === undefined ? working : checkFrames(miniGiven[mood], `mini.moods.${mood}`, LIMITS.mini)
429  }
430  sameSize(MINI_MOODS.flatMap(mood => mini[mood]), 'mini')
431  // An ascii mini pet drawn all in ink is tinted whole.
432  const tint = raw.tint ?? (ascii ? '.' : 'b')
433  if (typeof tint !== 'string' || colors[tint] === undefined) throw new Error(`mini.tint: must be a palette letter${ascii ? ', or "." for the ink' : ''}`)
434  return { mini, tint }
435}
436
437const SAFE_NAME = /^[a-z0-9][a-z0-9_-]{0,40}$/
438
439// Where a pet named `name` may live, the person's own pets folder first.
440// Undefined for a name that could step outside those folders.
441export const packPaths = (name: string, home: string | undefined, root: string) =>
442  SAFE_NAME.test(name)
443    ? [...(home ? [`${home}/.claude/pets/${name}.json`] : []), `${root}/pets/${name}.json`]
444    : undefined
445
hooks/render.ts 102 lines
1import type { Frame, Glyphs } from '../types'
2
3const NONE = 0x01000000
4const HALF_TOP = 0x2580
5const HALF_BOTTOM = 0x2584
6
7export type Colors = Record<string, number>
8
9export const hexColor = (hex: string) => Number.parseInt(hex.slice(1), 16)
10
11export const isGlyphs = (frame: Frame): frame is Glyphs => !Array.isArray(frame)
12
13export const rowsOf = (frame: Frame) => (isGlyphs(frame) ? frame.art : frame)
14
15// In cells: a glyph outside the basic plane is one, not two UTF-16 units.
16export const widthOf = (row: string | undefined) => [...(row ?? '')].length
17
18export const sizeOf = (frame: Frame) => {
19  const rows = rowsOf(frame)
20  return { columns: widthOf(rows[0]), rows: isGlyphs(frame) ? rows.length : Math.ceil(rows.length / 2) }
21}
22
23// A cell: its glyph's code point, then foreground and background, NONE for none.
24type Cell = [number, number, number]
25
26// Two pixel rows share one terminal cell: '▀' takes the top as foreground
27// and the bottom as background. Letters missing from the palette are see-through.
28const pixelCells = (frame: string[], colors: Colors) => {
29  const rows: Cell[][] = []
30  for (let r = 0; r < frame.length; r += 2) {
31    // By code point, as `widthOf` measures the frame.
32    const top = [...(frame[r] ?? '')]
33    const bottom = [...(frame[r + 1] ?? '')]
34    rows.push(
35      top.map((letter, c): Cell => {
36        const up = colors[letter]
37        const down = colors[bottom[c] ?? '.']
38        if (up === undefined && down === undefined) return [0x20, NONE, NONE]
39        if (up === undefined) return [HALF_BOTTOM, down ?? NONE, NONE]
40        return [HALF_TOP, up, down ?? NONE]
41      }),
42    )
43  }
44  return rows
45}
46
47// One glyph a cell, in its mask's color; '.' in the mask is the pack's ink.
48const glyphCells = ({ art, color }: Glyphs, colors: Colors) =>
49  art.map((row, r) => {
50    const mask = [...(color[r] ?? '')]
51    return [...row].map((glyph, c): Cell =>
52      glyph === ' ' ? [0x20, NONE, NONE] : [glyph.codePointAt(0) ?? 0x20, colors[mask[c] ?? '.'] ?? NONE, NONE],
53    )
54  })
55
56const cellsOf = (frame: Frame, colors: Colors) => (isGlyphs(frame) ? glyphCells(frame, colors) : pixelCells(frame, colors))
57
58export const encode = (frame: Frame, colors: Colors) => {
59  const words = cellsOf(frame, colors).flat(2)
60  // The engine's runtime has TC39 base64; TypeScript's es2023 lib does not type it.
61  const bytes = new Uint8Array(Uint32Array.from(words).buffer) as Uint8Array & { toBase64(): string }
62  return bytes.toBase64()
63}
64
65// A stretch of a row in one look: its text, then foreground and background as
66// "#rrggbb", '' for none.
67export type Run = [text: string, fg: string, bg: string]
68
69const hexOf = (color: number) => (color === NONE ? '' : `#${color.toString(16).padStart(6, '0')}`)
70
71// The frame as styled text, for where a Raster cannot go: a row of runs a line,
72// neighbors that look alike joined.
73export const artOf = (frame: Frame, colors: Colors): Run[][] =>
74  cellsOf(frame, colors).map(row =>
75    row.reduce<Run[]>((runs, [glyph, fg, bg]) => {
76      const text = String.fromCodePoint(glyph)
77      const last = runs.at(-1)
78      if (last !== undefined && last[1] === hexOf(fg) && last[2] === hexOf(bg)) last[0] += text
79      else runs.push([text, hexOf(fg), hexOf(bg)])
80      return runs
81    }, []),
82  )
83
84// Glyphs that point one way swap for their twin when the art is flipped.
85const SWAP: Record<string, string> = {}
86for (const pair of ['/\\', '()', '<>', '[]', '{}', 'db', 'pq', '‹›', '«»', '╱╲', '┌┐', '└┘', '├┤', '╭╮', '╰╯', '▌▐', '◀▶', '◄►', '⊂⊃']) {
87  const [a = '', b = ''] = [...pair]
88  SWAP[a] = b
89  SWAP[b] = a
90}
91
92const flip = (row: string) => [...row].reverse().join('')
93
94// The same frame facing the other way. Packs draw their pet facing right.
95export const mirror = (frame: Frame): Frame =>
96  isGlyphs(frame)
97    ? { art: frame.art.map(row => [...row].reverse().map(glyph => SWAP[glyph] ?? glyph).join('')), color: frame.color.map(flip) }
98    : frame.map(flip)
99
100// The frame as drawn facing `side`; a pack that does not mirror faces you either way.
101export const facingFrame = (frame: Frame, side: 1 | -1, mirrors: boolean) => (side === 1 || !mirrors ? frame : mirror(frame))
102