SLOPSHOPPER

buddy-go

Buddy, a fan-made companion inspired by Clawd, living above the prompt: it walks, waves when it is your turn, paces while the model thinks, types along when a…

bandguardprompttimer
v0.5.0no licenseupdated 2026-10-13magiclin99/buddy-go
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · buddy-go
› 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 ⟨Claude Code's own drawing⟩ ▐▛███▛█ ▟█▙ ▝▜██████▀ ▟███▙ ▟█▙ ─▝▝───▝▝·──────────────·╨────·───────────────────·▄▆▄───────────·─────·▄▆▄────────────┴───·───────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ ▐▛███▛█ ▟█▙ ▝▜██████▀ ▟███▙ ▟█▙ ─▝▝───▝▝·──────────────·╨────·───────────────────·▄▆▄───────────·─────·▄▆▄────────────┴───·─────────
README

buddy-go

Give your Claude Code prompt a tiny coworker.

Buddy is a fan-made pixel companion, inspired by Clawd from Claude Code. It moves in right above your input box and reacts to whatever Claude is up to. It paces when Claude thinks, sprints when your commands run, plays ping pong with the APIs Claude calls, types when files change, and hurls your pull requests into orbit.

Buddy sprinting while a command runs

Install

Type this into the Claude Code prompt:

/plugin install buddy-go --marketplace magiclin99/buddy-go

That's it. Buddy shows up above the prompt and starts wandering.

What Buddy does

Paces while Claude thinks

Buddy pacing under a thought bubble

A few steps out, a few steps back, a . o O bubble beside its head, and a pause now and then to shut its eyes and really think. Five seconds in, the pacing gets quicker. Fifteen seconds in, Buddy goes red and starts to sweat. When the answer finally lands, both hands go up: !

Sprints while your commands run

Buddy running with the command on a banner

Every Bash command is a race. The ground rolls in, trees fly past, and Buddy tows your command behind it on a banner. Commands that follow each other are one long run. It ends with a green Finish! and a cheer, or a red Oops! and a stumble. Run for more than ten seconds and Buddy starts gasping.

Plays ping pong with your APIs

Buddy playing ping pong against api.github.com

A request goes out, a response comes back. Ping, pong. Whenever Claude runs curl, wget, gh api or fetches a page, a table rolls out and Buddy rallies against whoever is on the other end, their host name beside the far paddle. A call that comes back fine ends with a smash and a green Point!. One that fails sails past Buddy's paddle: Miss!

Types along when files change

Buddy typing beside a file name

Whenever Claude edits or writes a file, Buddy stops and hammers out a few lines of code, with the file's name underneath.

Launches your PR

Buddy charging a ball and throwing it

gh pr create deserves a ceremony. Buddy raises its hands, charges up a ball with your PR inside, and throws it clean off the screen.

Waves when it's your turn

Buddy waving beside a "your turn" bubble

When Claude ends on a question, Buddy vanishes, pops up at the left edge, and waves until you answer. No more staring at a prompt that was waiting for you.

Wanders the rest of the time

Buddy walking above the prompt

Back and forth, above the prompt, minding its own business.

Cheat codes

You don't have to wait for Claude. Type a cheat straight into the prompt, with no slash, and Buddy performs on demand. Buddy catches cheats before they are sent, so they never reach the model.

Type thisBuddy will
buddy:think 20pace and think for 20 seconds (8 if you leave the number out)
buddy:run npm testsprint for six seconds with npm test on the banner
buddy:ping-pong api.github.complay four rallies against api.github.com, then take the point
buddy:edit main.tstype into main.ts
buddy:send-prlaunch a PR
buddy:your-turnwave at you

Update

claude plugin marketplace update buddy-go
claude plugin update buddy-go@buddy-go

Then type /reload-plugins in any session that is already open.

Teach Buddy a new trick

Every animation is one small file, and drawing is plain math: given a frame number and where Buddy stands, return the characters and colors to draw. No timers, no engine calls.

  1. Add a file to hooks/animations/ that exports an Animation: a name, a priority, how many frames, how long each lasts, and a draw function. Export a trigger function and a cheat name if it needs them.
  2. Add it to ANIMATIONS in hooks/animations/index.ts, and its trigger to registerTriggers.

Run it from your folder while you work:

claude --plugin-dir /path/to/buddy-go
claude plugin validate .
claude plugin test .
hooks/
├── register.tsx        wiring: the clock, the published state, cheats, drawing
├── animations/         one file per animation, plus the registry in index.ts
│   ├── walk.ts
│   ├── wait.ts
│   ├── think.ts
│   ├── edit.ts
│   ├── run.ts
│   ├── pong.ts
│   └── launch.ts
└── lib/
    ├── player.ts       what is playing, what is queued, where Buddy stands
    ├── body.ts         Buddy's body parts
    ├── command.ts      reads a shell command: is it an API call, and to whom
    ├── render.tsx      turns an animation's rows into elements
    └── frame.ts        shared types
tests/
├── player.test.ts      the player's rules
├── animations.test.ts  what each animation draws, frame by frame
└── walk.test.tsx       events in, pixels out
demo/
├── record.sh           records every animation as a GIF
├── settings.json       recording only: load this folder's copy alone
└── *.gif               the GIFs on this page

The GIFs are recorded in a real Claude Code session by typing each cheat. You need vhs and ffmpeg (brew install vhs ffmpeg).

demo/record.sh          # all of them
demo/record.sh think    # just one

To record a new animation, add a line at the bottom of demo/record.sh: record <name> "<cheat>" <seconds>.


buddy-go is an unofficial fan mod. It is not affiliated with, sponsored by or endorsed by Anthropic. Claude, Claude Code and Clawd belong to Anthropic.

Source 15 files
hooks/register.tsx 117 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import { IDLE, byCheat, byName, registerTriggers } from './animations'
5import { stageAt } from './animations/walk'
6import { BLANK_ROW } from './lib/frame'
7import type { Director } from './lib/frame'
8import { createPlayer } from './lib/player'
9import { renderRows } from './lib/render'
10
11// The one value the draw reads: the player's show, published after every change.
12const show = atom({ plugin: 'buddy-go', key: 'show' } as const, null)
13
14const player = createPlayer(IDLE, byName)
15
16let timer: Timer | undefined
17let writing: Promise<void> = Promise.resolve()
18// Set once the session has a `$` to tick and publish with; until then a request only changes the player.
19let wake: (() => void) | undefined
20
21// Chained so a slow write can never land after a newer one and leave a stale frame on screen.
22const publish = ($: EngineInterface) => {
23  const snapshot = player.show()
24
25  writing = writing
26    .then(() => update($, show, () => snapshot))
27    .then(
28      () => undefined,
29      () => undefined,
30    )
31}
32
33const schedule = ($: EngineInterface) => {
34  timer?.cancel()
35  timer = $.clock.after(player.delay(), () => {
36    player.tick()
37    publish($)
38    schedule($)
39  })
40}
41
42const director: Director = {
43  play: (animation, params) => {
44    player.play(animation, params)
45    wake?.()
46  },
47  stop: animation => {
48    player.stop(animation)
49    wake?.()
50  },
51  frameOf: animation => player.frameOf(animation),
52}
53
54export const register: Register = on => {
55  on('session.start', async ($, e, next) => {
56    // Nothing draws the band without a person at a terminal, so nothing needs to tick.
57    if (!e.isInteractive) {
58      return next(e)
59    }
60
61    // A reload drops the timer and the player's memory; the show in state says where it was.
62    const kept = await read($, show)
63
64    if (kept !== null && wake === undefined) {
65      player.restore(kept)
66    }
67
68    wake = () => {
69      publish($)
70      schedule($)
71    }
72    wake()
73
74    return next(e)
75  })
76
77  registerTriggers(on, director)
78
79  on('prompt.submit', ($, e, next) => {
80    const cheat = byCheat(e.text)
81
82    if (cheat === undefined) {
83      return next(e)
84    }
85
86    director.play(cheat.animation, cheat.params)
87
88    return { drop: cheat.reply }
89  })
90
91  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
92    // The band is shared: what the other mods and the engine draw here stays, above the mascot.
93    const rest = await next(e)
94
95    if (e.props.hasSurvey) {
96      return rest
97    }
98
99    const shown = (await read($, show)) ?? player.show()
100    const animation = byName(shown.name) ?? IDLE
101    const { Box } = $.ui.resolve(e)
102
103    // A row of air over the mascot's head, whatever it is doing.
104    const mascot = renderRows($.ui.resolve(e), [
105      BLANK_ROW,
106      ...animation.draw(shown.frame, stageAt(shown.idleFrame, e.props.bodyColumns, shown.idleFrom), shown.params),
107    ])
108
109    return (
110      <Box flexDirection="column">
111        {rest}
112        {mascot}
113      </Box>
114    )
115  })
116}
117
hooks/animations/index.ts 46 lines
1import type { Animation, Triggers } from '../lib/frame'
2import { edit, editTriggers } from './edit'
3import { launch, launchTriggers } from './launch'
4import { pong, pongTriggers } from './pong'
5import { run, runTriggers } from './run'
6import { think, thinkTriggers } from './think'
7import { wait, waitTriggers } from './wait'
8import { walk } from './walk'
9
10export const IDLE = walk
11
12// An animation is a file beside these, a line here for it, and a line below for its triggers; its cheat comes with it.
13export const ANIMATIONS: readonly Animation[] = [walk, launch, wait, edit, run, pong, think]
14
15export const registerTriggers: Triggers = (on, director) => {
16  launchTriggers(on, director)
17  editTriggers(on, director)
18  runTriggers(on, director)
19  pongTriggers(on, director)
20  thinkTriggers(on, director)
21  waitTriggers(on, director)
22}
23
24export const CHEAT_PREFIX = 'buddy:'
25
26export const byName = (name: string) => ANIMATIONS.find(animation => animation.name === name)
27
28export const byCheat = (typed: string) => {
29  const text = typed.trim()
30
31  if (!text.startsWith(CHEAT_PREFIX)) {
32    return undefined
33  }
34
35  const [name = '', ...rest] = text.slice(CHEAT_PREFIX.length).split(/\s+/)
36  const animation = ANIMATIONS.find(candidate => candidate.cheat?.name === name)
37
38  if (animation?.cheat === undefined) {
39    return undefined
40  }
41
42  const params = animation.cheat.params?.(rest.join(' ')) ?? {}
43
44  return { animation, params, reply: animation.cheat.reply(params) }
45}
46
hooks/animations/walk.ts 42 lines
1import { ARMS, FEET, SPRITE_COLUMNS, mascot } from '../lib/body'
2import type { Animation, IdleFrom, Stage } from '../lib/frame'
3
4export const STEP_MS = 300
5
6// The column that puts the mascot in the middle of the band.
7export const middle = (columns: number) => Math.max(0, Math.floor((columns - SPRITE_COLUMNS) / 2))
8
9export const STRIDE = [FEET.both, FEET.left, FEET.both, FEET.right] as const
10
11// The band's width is known only while drawing, so the idle show counts steps and the draw folds them into a there-and-back walk.
12export const stageAt = (idleFrame: number, columns: number, from: IdleFrom = 'left-edge'): Stage => {
13  const range = Math.max(0, columns - SPRITE_COLUMNS)
14
15  if (range === 0) {
16    return { columns, x: 0, facing: 'right' }
17  }
18
19  const position = (idleFrame + (from === 'center' ? middle(columns) : 0)) % (range * 2)
20
21  return position < range
22    ? { columns, x: position, facing: 'right' }
23    : { columns, x: range * 2 - position, facing: 'left' }
24}
25
26// Where the walk would be `steps` on from a stage it drew.
27export const ahead = (stage: Stage, steps: number): Stage => {
28  const range = Math.max(0, stage.columns - SPRITE_COLUMNS)
29
30  return stageAt((stage.facing === 'right' ? stage.x : range * 2 - stage.x) + steps, stage.columns)
31}
32
33// What plays whenever nothing else does.
34export const walk: Animation = {
35  name: 'walk',
36  priority: 0,
37  frames: null,
38  frameMs: () => STEP_MS,
39
40  draw: (frame, stage) => mascot(stage.x, ARMS.down, stage.facing, STRIDE[frame % STRIDE.length] ?? FEET.both),
41}
42
hooks/lib/frame.ts 93 lines
1import type { On } from 'claude-code'
2
3export type Span = {
4  text: string
5  color?: string
6  backgroundColor?: string
7  dimColor?: true
8  bold?: true
9  // Blank columns before the span; a Text's own leading spaces are not kept everywhere.
10  gap?: number
11}
12
13export type Row = { indent: number; spans: readonly Span[] }
14
15export type Stage = { columns: number; x: number; facing: 'left' | 'right' }
16
17// Where the walk starts counting its steps from.
18export type IdleFrom = 'left-edge' | 'center'
19
20export type Params = Readonly<Record<string, string>>
21
22// What an animation's triggers hold: they say what to play and never touch timers, state or `$`.
23export type Director = {
24  play: (animation: Animation, params?: Params) => void
25  stop: (animation: Animation) => void
26  // The frame it is on, when it is the one on stage.
27  frameOf: (animation: Animation) => number | undefined
28}
29
30export type Animation = {
31  name: string
32  // The higher one plays first; a looping one that gets pushed aside comes back afterwards.
33  priority: number
34  // null loops until something stops it.
35  frames: number | null
36  // How long this play of it is, where that depends on what it was asked to play; without it, `frames`.
37  framesFor?: (params: Params) => number | null
38  frameMs: (frame: number) => number
39  // Where it leaves the mascot when it ends at `frame`: where it stood (as when absent), where the walk
40  // starts over from, or that many steps further along the walk.
41  exit?: (frame: number, params: Params) => 'in-place' | IdleFrom | { steps: number }
42  cheat?: { name: string; reply: (params: Params) => string; params?: (typed: string) => Params }
43  draw: (frame: number, stage: Stage, params: Params) => Row[]
44}
45
46// The events that start and stop an animation: a named function its file exports, since the engine only lets `on` be handed to one.
47export type Triggers = (on: On, director: Director) => void
48
49// A frame number an animation was handed in its params.
50export const frameIn = (params: Params, key: string) => {
51  const frame = Number(params[key] ?? Number.NaN)
52
53  return Number.isFinite(frame) ? frame : undefined
54}
55
56export const BLANK_ROW: Row = { indent: 0, spans: [] }
57
58export const width = (spans: readonly Span[]) =>
59  spans.reduce((sum, span) => sum + (span.gap ?? 0) + span.text.length, 0)
60
61// Moves a run of spans right by `gap` columns: the blank goes before its first span.
62export const withGap = (spans: readonly Span[], gap: number): Span[] =>
63  gap === 0 ? [...spans] : spans.map((span, index) => (index === 0 ? { ...span, gap: (span.gap ?? 0) + gap } : span))
64
65export type Piece = { at: number; spans: readonly Span[] }
66
67// One row from pieces that each say which column they start at; they must not overlap.
68export const layRow = (pieces: readonly Piece[]): Row => {
69  const laid = pieces.filter(piece => piece.spans.length > 0).sort((a, b) => a.at - b.at)
70  const indent = laid[0]?.at ?? 0
71  const spans: Span[] = []
72  let end = indent
73
74  for (const piece of laid) {
75    spans.push(...withGap(piece.spans, piece.at - end))
76    end = piece.at + width(piece.spans)
77  }
78
79  return { indent, spans }
80}
81
82// Something drawn beside the mascot: which of its rows, and the column it starts at.
83export type Extra = { row: number; at: number; span: Span }
84
85// The mascot's rows with what goes beside them; nothing of it may overlap.
86export const withExtras = (body: readonly Row[], extras: readonly Extra[]): Row[] =>
87  body.map((row, index) =>
88    layRow([
89      { at: row.indent, spans: row.spans },
90      ...extras.filter(extra => extra.row === index).map(extra => ({ at: extra.at, spans: [extra.span] })),
91    ]),
92  )
93
hooks/lib/player.ts 147 lines
1import type { Animation, IdleFrom, Params } from './frame'
2
3export type Show = {
4  name: string
5  frame: number
6  params: Record<string, string>
7  idleFrame: number
8  idleFrom?: IdleFrom
9}
10
11type Act = { animation: Animation; params: Params }
12
13// What is on stage, what waits behind it, and where the mascot stands. No timers, no state, no `$`:
14// the caller ticks it and draws what `show()` says.
15export const createPlayer = (idle: Animation, find: (name: string) => Animation | undefined) => {
16  let act: Act | undefined
17  let frame = 0
18  let idleFrame = 0
19  let idleFrom: IdleFrom = 'left-edge'
20  let waiting: Act[] = []
21
22  const framesOf = (held: Act) =>
23    held.animation.framesFor === undefined ? held.animation.frames : held.animation.framesFor(held.params)
24
25  const begin = (next: Act) => {
26    act = next
27    frame = 0
28  }
29
30  const leave = () => {
31    const left = act?.animation.exit?.(frame, act.params) ?? 'in-place'
32
33    if (left === 'in-place') {
34      return
35    }
36
37    if (typeof left === 'object') {
38      idleFrame += left.steps
39
40      return
41    }
42
43    idleFrame = 0
44    idleFrom = left
45  }
46
47  const enqueue = (next: Act) => {
48    waiting = [...waiting.filter(held => held.animation.name !== next.animation.name), next]
49  }
50
51  const finish = () => {
52    leave()
53    act = undefined
54    frame = 0
55
56    // The highest priority goes next; among equals, the one that has waited longest.
57    const next = waiting.reduce<Act | undefined>(
58      (best, held) => (best === undefined || held.animation.priority > best.animation.priority ? held : best),
59      undefined,
60    )
61
62    if (next !== undefined) {
63      waiting = waiting.filter(held => held !== next)
64      begin(next)
65    }
66  }
67
68  return {
69    play: (animation: Animation, params: Params = {}) => {
70      if (animation.name === idle.name) {
71        return
72      }
73
74      if (act === undefined) {
75        begin({ animation, params })
76
77        return
78      }
79
80      if (act.animation.name === animation.name) {
81        // Asked again while playing: it carries on from where it is with the new params.
82        act = { animation, params }
83
84        return
85      }
86
87      if (act.animation.priority > animation.priority) {
88        enqueue({ animation, params })
89
90        return
91      }
92
93      if (framesOf(act) === null) {
94        enqueue(act)
95      }
96
97      leave()
98      begin({ animation, params })
99    },
100
101    stop: (animation: Animation) => {
102      waiting = waiting.filter(held => held.animation.name !== animation.name)
103
104      if (act?.animation.name === animation.name) {
105        finish()
106      }
107    },
108
109    frameOf: (animation: Animation) => (act?.animation.name === animation.name ? frame : undefined),
110
111    tick: () => {
112      if (act === undefined) {
113        idleFrame += 1
114
115        return
116      }
117
118      frame += 1
119
120      const frames = framesOf(act)
121
122      if (frames !== null && frame >= frames) {
123        finish()
124      }
125    },
126
127    delay: () => (act === undefined ? idle.frameMs(idleFrame) : act.animation.frameMs(frame)),
128
129    show: (): Show =>
130      act === undefined
131        ? { name: idle.name, frame: idleFrame, params: {}, idleFrame, idleFrom }
132        : { name: act.animation.name, frame, params: { ...act.params }, idleFrame, idleFrom },
133
134    // Picks up a show a reload left in state; what was waiting behind it is gone.
135    restore: (kept: Show) => {
136      const animation = find(kept.name)
137      idleFrame = kept.idleFrame
138      idleFrom = kept.idleFrom ?? 'left-edge'
139      waiting = []
140      act = animation === undefined || animation.name === idle.name ? undefined : { animation, params: kept.params }
141      frame = act === undefined ? 0 : kept.frame
142    },
143  }
144}
145
146export type Player = ReturnType<typeof createPlayer>
147
hooks/lib/render.tsx 49 lines
1import type { Elements, RenderElement } from 'claude-code'
2
3import type { Row, Span } from './frame'
4
5type Table = Pick<Elements['terminal'], 'Box' | 'Text'> | Pick<Elements['desktop'], 'Box' | 'Text'>
6
7const textProps = (span: Span) => {
8  const props: Record<string, unknown> = {}
9
10  if (span.color !== undefined) {
11    props.color = span.color
12  }
13
14  if (span.backgroundColor !== undefined) {
15    props.backgroundColor = span.backgroundColor
16  }
17
18  if (span.dimColor) {
19    props.dimColor = true
20  }
21
22  if (span.bold) {
23    props.bold = true
24  }
25
26  return props
27}
28
29// The one place frame data becomes elements: every animation draws through it.
30export const renderRows = ({ Box, Text }: Table, rows: readonly Row[]) =>
31  // `h` is typed for any node; a Box with children is always an element.
32  h(
33    Box,
34    { flexDirection: 'column' },
35    ...rows.map(row =>
36      h(
37        Box,
38        { height: 1, marginLeft: row.indent },
39        ...(row.spans.length === 0
40          ? [h(Text, null, ' ')]
41          : row.spans.map(span => {
42              const text = h(Text, textProps(span), span.text)
43
44              return span.gap === undefined ? text : h(Box, { marginLeft: span.gap }, text)
45            })),
46      ),
47    ),
48  ) as RenderElement
49
hooks/animations/edit.ts 132 lines
1import { ARMS, FEET, SPRITE_COLUMNS, mascot } from '../lib/body'
2import type { Gaze } from '../lib/body'
3import { width, withGap } from '../lib/frame'
4import type { Animation, Params, Row, Span, Triggers } from '../lib/frame'
5
6const FRAME_MS = 120
7const LINE_FRAMES = 8
8const REST_FRAMES = 4
9const LOOK_AWAY_FRAMES = 2
10
11const LINE_COLOR = 'success'
12const CURSOR = '▌'
13const FILE_MARK = '✎ '
14const PAGE_GAP = 3
15
16const LINES = ['▬▬▬ ▬▬▬▬▬ ▬▬ ▬▬▬▬', '▬▬ ▬▬▬ ▬▬▬▬▬▬ ▬'] as const
17
18const TYPING_FRAMES = LINE_FRAMES * LINES.length
19const PAGE_COLUMNS = Math.max(...LINES.map(line => line.length + CURSOR.length))
20
21type Side = 'left' | 'right'
22
23const nameOf = (file: string | undefined) => file?.split(/[\\/]/).pop() ?? ''
24
25// The file's name, whole when there is room for it and cut where there is not.
26const fileLabel = (name: string, room: number): Span[] => {
27  const columns = room - FILE_MARK.length
28
29  if (name === '' || columns < 1) {
30    return []
31  }
32
33  const shown = name.length > columns ? `${name.slice(0, columns - 1)}…` : name
34
35  return [{ text: `${FILE_MARK}${shown}`, color: 'inactive' }]
36}
37
38// The page goes where the whole name fits, to the right for choice; failing that, on the roomier side.
39const sideFor = (rooms: Record<Side, number>, name: string): Side | 'none' => {
40  const wanted = Math.max(PAGE_COLUMNS, FILE_MARK.length + name.length)
41  const roomier: Side = rooms.right >= rooms.left ? 'right' : 'left'
42  const whole = (['right', 'left'] as const).find(side => rooms[side] >= wanted)
43
44  return whole ?? (rooms[roomier] >= PAGE_COLUMNS ? roomier : 'none')
45}
46
47// The page's three rows: the line before, the line being typed, and the file's name.
48const page = (frame: number, label: Span[]): Span[][] => {
49  const isTyping = frame < TYPING_FRAMES
50  const lineIndex = isTyping ? Math.floor(frame / LINE_FRAMES) : LINES.length - 1
51  const line = LINES[lineIndex] ?? LINES[0]
52  const typed = isTyping ? Math.round((line.length * (frame % LINE_FRAMES)) / (LINE_FRAMES - 1)) : line.length
53  const before = LINES[lineIndex - 1]
54  const current: Span[] = typed === 0 ? [] : [{ text: line.slice(0, typed), color: LINE_COLOR }]
55
56  if (isTyping) {
57    current.push({ text: CURSOR, color: 'text' })
58  }
59
60  return [
61    before === undefined ? [] : [{ text: before, color: LINE_COLOR, dimColor: true }],
62    current,
63    label,
64  ]
65}
66
67export const edit: Animation = {
68  name: 'edit',
69  priority: 2,
70  frames: TYPING_FRAMES + REST_FRAMES,
71  frameMs: () => FRAME_MS,
72  cheat: {
73    name: 'edit',
74    params: (typed): Params => (typed === '' ? {} : { file: typed }),
75    reply: params => (params.file === undefined ? 'Buddy: editing.' : `Buddy: editing ${params.file}.`),
76  },
77
78  draw: (frame, { columns, x }, params) => {
79    const isTyping = frame < TYPING_FRAMES
80    const name = nameOf(params.file)
81    const rightOf = x + SPRITE_COLUMNS + PAGE_GAP
82    const rooms = { right: columns - rightOf, left: x - PAGE_GAP }
83    const side = sideFor(rooms, name)
84    const isLookingAway = frame < TYPING_FRAMES + REST_FRAMES - LOOK_AWAY_FRAMES
85    const gaze: Gaze = side === 'none' || !isLookingAway ? 'ahead' : side
86    const arms = !isTyping ? ARMS.down : frame % 2 === 0 ? ARMS.oneUp : ARMS.otherUp
87    const body = mascot(x, arms, gaze, FEET.both)
88
89    if (side === 'none') {
90      return body
91    }
92
93    const pageRows = page(frame, fileLabel(name, rooms[side]))
94
95    return body.map((row, index): Row => {
96      const beside = pageRows[index] ?? []
97
98      if (beside.length === 0) {
99        return row
100      }
101
102      // On the left the lines keep their column, and a name longer than them reaches further out.
103      const leftOf = x - PAGE_GAP - Math.max(PAGE_COLUMNS, width(beside))
104
105      // A Text's own leading and trailing spaces are not kept everywhere, so every blank column is a gap.
106      return side === 'right'
107        ? { indent: row.indent, spans: [...row.spans, ...withGap(beside, rightOf - row.indent - width(row.spans))] }
108        : { indent: leftOf, spans: [...beside, ...withGap(row.spans, row.indent - leftOf - width(beside))] }
109    })
110  },
111}
112
113export const editTriggers: Triggers = (on, director) => {
114  on('tool.call', { tool: 'Edit' }, ($, e, next) => {
115    director.play(edit, { file: e.file_path })
116
117    return next(e)
118  })
119
120  on('tool.call', { tool: 'Write' }, ($, e, next) => {
121    director.play(edit, { file: e.file_path })
122
123    return next(e)
124  })
125
126  on('tool.call', { tool: 'NotebookEdit' }, ($, e, next) => {
127    director.play(edit, { file: e.notebook_path })
128
129    return next(e)
130  })
131}
132
hooks/animations/launch.ts 131 lines
1import { ARMS, FEET, SPRITE_COLUMNS, mascot } from '../lib/body'
2import { BLANK_ROW } from '../lib/frame'
3import type { Animation, Row, Triggers } from '../lib/frame'
4
5const FRAME_MS = 100
6const CHARGE_STAGE_FRAMES = 5
7const WIND_UP_FRAMES = 5
8const FLIGHT_FRAMES = 12
9
10const BALL_COLOR = '#9be7ff'
11const BALL_COLUMNS = 12
12const BALL_ROWS = 5
13const BALL_MIDDLE_ROW = 2
14const SPARK_REACH = 3
15const TRAIL = '─ ═ ━━━'
16
17// Smallest first, each bottom-aligned in the ball's 12 by 5 box so it grows upward, away from the head.
18const BALLS = [
19  [{ row: 4, indent: 6, glyphs: '∘' }],
20  [
21    { row: 3, indent: 4, glyphs: '╭──╮' },
22    { row: 4, indent: 4, glyphs: '╰──╯' },
23  ],
24  [
25    { row: 2, indent: 3, glyphs: '╭────╮' },
26    { row: 3, indent: 2, glyphs: '│  PR  │' },
27    { row: 4, indent: 3, glyphs: '╰────╯' },
28  ],
29  [
30    { row: 0, indent: 2, glyphs: '╭──────╮' },
31    { row: 1, indent: 1, glyphs: '╱        ╲' },
32    { row: 2, indent: 0, glyphs: '│    PR    │' },
33    { row: 3, indent: 1, glyphs: '╲        ╱' },
34    { row: 4, indent: 2, glyphs: '╰──────╯' },
35  ],
36] as const
37
38const CHARGE_FRAMES = CHARGE_STAGE_FRAMES * BALLS.length
39
40const PR_CREATE = /\bgh\s+pr\s+create\b/
41
42export const opensPr = (command: string) => PR_CREATE.test(command)
43
44export const launch: Animation = {
45  name: 'launch',
46  priority: 3,
47  frames: CHARGE_FRAMES + WIND_UP_FRAMES + FLIGHT_FRAMES,
48  frameMs: () => FRAME_MS,
49  cheat: { name: 'send-pr', reply: () => 'Buddy: PR launched.' },
50
51  draw: (frame, { columns, x }) => {
52    const flightFrame = frame - CHARGE_FRAMES - WIND_UP_FRAMES
53    const isFlying = flightFrame >= 0
54    const isCharging = frame < CHARGE_FRAMES
55    const flown = isFlying ? (flightFrame + 1) / FLIGHT_FRAMES : 0
56    const restX = Math.max(0, Math.min(x - 2, columns - BALL_COLUMNS))
57    // Thrown across the longer stretch of the band, so it always has room to fly.
58    const isThrownLeft = x + SPRITE_COLUMNS / 2 > columns / 2
59    const travel = isThrownLeft ? -(restX + BALL_COLUMNS) : columns - restX
60    // Squared so the ball leaves slowly and is fully past the edge on the last frame.
61    const ballX = restX + Math.round(travel * flown * flown)
62    const ball = BALLS[Math.min(BALLS.length - 1, Math.floor(frame / CHARGE_STAGE_FRAMES))] ?? BALLS[0]
63
64    // Drawn on a grid of the band's width so whatever passes an edge is simply not there.
65    const grid = Array.from({ length: BALL_ROWS }, () => Array.from({ length: columns }, () => ' '))
66    const put = (row: number, from: number, glyphs: string) => {
67      const cells = grid[row]
68
69      if (cells === undefined) {
70        return
71      }
72
73      for (const [offset, glyph] of [...glyphs].entries()) {
74        if (from + offset >= 0 && from + offset < columns) {
75          cells[from + offset] = glyph
76        }
77      }
78    }
79
80    if (isCharging) {
81      const reach = SPARK_REACH - (frame % SPARK_REACH)
82      put(frame % BALL_ROWS, restX - reach, '·')
83      put((frame + 2) % BALL_ROWS, restX + BALL_COLUMNS - 1 + reach, '·')
84    }
85
86    for (const line of ball) {
87      put(line.row, ballX + line.indent, line.glyphs)
88    }
89
90    if (isFlying) {
91      const length = Math.min(TRAIL.length, Math.abs(ballX - restX))
92
93      if (isThrownLeft) {
94        put(BALL_MIDDLE_ROW, ballX + BALL_COLUMNS, [...TRAIL].reverse().join('').slice(0, length))
95      } else {
96        put(BALL_MIDDLE_ROW, ballX - length, TRAIL.slice(TRAIL.length - length))
97      }
98    }
99
100    const sky = grid.map((cells): Row => {
101      const drawn = cells.join('').trimEnd()
102      const glyphs = drawn.trimStart()
103
104      return glyphs === ''
105        ? BLANK_ROW
106        : { indent: drawn.length - glyphs.length, spans: [{ text: glyphs, color: BALL_COLOR }] }
107    })
108
109    return [
110      ...sky,
111      BLANK_ROW,
112      ...mascot(
113        x,
114        isFlying ? ARMS.down : ARMS.up,
115        isCharging ? 'ahead' : isThrownLeft ? 'left' : 'right',
116        FEET.both,
117      ),
118    ]
119  },
120}
121
122export const launchTriggers: Triggers = (on, director) => {
123  on('tool.call', { tool: 'Bash' }, ($, e, next) => {
124    if (opensPr(e.command)) {
125      director.play(launch)
126    }
127
128    return next(e)
129  })
130}
131
hooks/animations/pong.ts 298 lines
1import { ARMS, FEET, SPRITE_COLUMNS, mascot } from '../lib/body'
2import type { Gaze } from '../lib/body'
3import { callsApi, hostOf } from '../lib/command'
4import { frameIn, withExtras } from '../lib/frame'
5import type { Animation, Director, Extra, Params, Row, Span, Stage, Triggers } from '../lib/frame'
6
7const FRAME_MS = 70
8// How long the ball takes from one paddle to the other; a rally is there and back.
9const FLIGHT_FRAMES = 10
10const RALLY_FRAMES = FLIGHT_FRAMES * 2
11// A paddle comes down a frame before its hit, and is back up this many frames after it.
12const SWING_FRAMES = 2
13const WORD_FRAMES = 4
14// Once the last call is back it plays on this long: a call that comes in the meantime finds the rally going.
15const LINGER_FRAMES = RALLY_FRAMES
16const SMASH_FRAMES = 5
17const SMASH_PAST = 7
18const GONE_FRAMES = 3
19const END_FRAMES = FLIGHT_FRAMES + 8
20// Four rallies from the cheat to its point.
21const CHEAT_FRAMES = RALLY_FRAMES * 4
22
23const SHORTEST_COURT = 12
24const LONGEST_COURT = 26
25// Room kept past the far paddle for the name of who is on it.
26const NAME_COLUMNS = 14
27const SHORTEST_NAME = 4
28const LONGEST_NAME = 24
29const NAME_GAP = 2
30const WORD_GAP = 1
31
32const BALL = 'o'
33const TABLE_COLOR = '#3f8f6b'
34const OURS_COLOR = '#e5533d'
35const THEIRS_COLOR = '#5aa9e6'
36const POINT: Span = { text: 'Point!', color: 'success', bold: true }
37const MISS: Span = { text: 'Miss!', color: 'error', bold: true }
38
39type Side = 1 | -1
40// The court runs from the mascot's paddle at 0 to the far one at `length`, toward `side`.
41type Court = { side: Side; origin: number; length: number; columns: number }
42type Pose = 'ready' | 'swing' | 'cheer' | 'miss'
43type Moment = {
44  pose: Pose
45  farPaddleRow: number
46  ball?: { at: number; row: number }
47  word?: 'ping' | 'pong'
48  mark?: Span
49}
50
51// It plays across the longer stretch of the band.
52const sideAt = ({ columns, x }: Stage): Side => (x + SPRITE_COLUMNS / 2 > columns / 2 ? -1 : 1)
53
54const courtAt = (stage: Stage): Court | undefined => {
55  const side = sideAt(stage)
56  const room = side === 1 ? stage.columns - stage.x - SPRITE_COLUMNS : stage.x
57  const wanted = Math.max(SHORTEST_COURT, Math.min(LONGEST_COURT, room - 1 - NAME_COLUMNS))
58  // An even length puts the net on a column of its own.
59  const length = wanted - (wanted % 2)
60
61  return length > room - 1
62    ? undefined
63    : { side, origin: side === 1 ? stage.x + SPRITE_COLUMNS : stage.x - 1, length, columns: stage.columns }
64}
65
66const columnAt = (court: Court, at: number) => court.origin + court.side * at
67
68// Where a word starts that reads outward from a place on the court.
69const wordAt = (court: Court, at: number, text: string) =>
70  court.side === 1 ? columnAt(court, at) : columnAt(court, at) - text.length + 1
71
72// A paddle hugs the court, whichever end it is at.
73const paddle = (side: Side) => (side === 1 ? '▐' : '▌')
74
75// Whether a paddle is down for a hit it makes on `beat`.
76const swings = (beat: number, hitOn: number) => (beat - hitOn + 1 + RALLY_FRAMES) % RALLY_FRAMES <= SWING_FRAMES
77
78// The ball rises over the net and comes down to the paddle; `flown` is 0 at the mascot's and 1 at the far one.
79const ballAt = (court: Court, flown: number) => ({
80  at: 1 + Math.round((court.length - 2) * flown),
81  row: Math.sin(Math.PI * flown) > 0.45 ? 0 : 1,
82})
83
84const rallyAt = (frame: number, court: Court): Moment => {
85  const beat = frame % RALLY_FRAMES
86  const flown = (beat < FLIGHT_FRAMES ? beat : RALLY_FRAMES - beat) / FLIGHT_FRAMES
87
88  return {
89    pose: swings(beat, 0) ? 'swing' : 'ready',
90    farPaddleRow: swings(beat, FLIGHT_FRAMES) ? 1 : 0,
91    ball: ballAt(court, flown),
92    ...(beat < WORD_FRAMES
93      ? { word: 'ping' as const }
94      : beat >= FLIGHT_FRAMES && beat < FLIGHT_FRAMES + WORD_FRAMES
95        ? { word: 'pong' as const }
96        : {}),
97  }
98}
99
100// A point: the mascot smashes the ball past the far paddle and off the court.
101const pointAt = (frame: number, court: Court): Moment => {
102  if (frame >= SMASH_FRAMES) {
103    return { pose: 'cheer', farPaddleRow: 1, mark: POINT }
104  }
105
106  const at = 1 + Math.round(((court.length + SMASH_PAST) * frame) / (SMASH_FRAMES - 1))
107
108  return { pose: 'swing', farPaddleRow: 1, ball: { at, row: at < court.length / 2 ? 1 : 0 } }
109}
110
111// A miss: the ball comes back as ever, and goes by under a paddle that stays up.
112const missAt = (frame: number, court: Court): Moment => {
113  if (frame < FLIGHT_FRAMES) {
114    return {
115      pose: 'ready',
116      farPaddleRow: frame < SWING_FRAMES ? 1 : 0,
117      ball: ballAt(court, 1 - frame / FLIGHT_FRAMES),
118    }
119  }
120
121  const gone = frame - FLIGHT_FRAMES
122
123  return {
124    pose: 'miss',
125    farPaddleRow: 0,
126    mark: MISS,
127    ...(gone < GONE_FRAMES ? { ball: { at: -(SPRITE_COLUMNS + 2 + gone * 2), row: 1 } } : {}),
128  }
129}
130
131const buddy = (x: number, side: Side, pose: Pose): Row[] => {
132  const toward: Gaze = side === 1 ? 'right' : 'left'
133  const raised = side === 1 ? ARMS.oneUp : ARMS.otherUp
134
135  return mascot(
136    x,
137    pose === 'cheer' ? ARMS.up : pose === 'ready' ? raised : ARMS.down,
138    pose === 'cheer' ? 'ahead' : pose === 'miss' ? 'closed' : toward,
139    FEET.both,
140  )
141}
142
143// Who is on the far paddle, as much of the name as there is room for.
144const named = (court: Court, name: string): Extra[] => {
145  const from = court.length + NAME_GAP
146  const room = court.side === 1 ? court.columns - columnAt(court, from) : columnAt(court, from) + 1
147
148  if (name === '' || room < SHORTEST_NAME) {
149    return []
150  }
151
152  const text = name.length > room ? `${name.slice(0, room - 1)}…` : name
153
154  return [{ row: 1, at: wordAt(court, from, text), span: { text, color: 'inactive' } }]
155}
156
157const scene = (x: number, court: Court, moment: Moment, name: string): Row[] => {
158  const { side, length, columns } = court
159  const ourPaddleRow = moment.pose === 'swing' || moment.pose === 'miss' ? 1 : 0
160  const behind = side === 1 ? x - WORD_GAP - 'ping'.length : x + SPRITE_COLUMNS + WORD_GAP
161
162  const extras: Extra[] = [
163    { row: 2, at: Math.min(columnAt(court, 2), columnAt(court, length - 2)), span: { text: '▀'.repeat(length - 3), color: TABLE_COLOR } },
164    { row: 1, at: columnAt(court, length / 2), span: { text: '│', color: 'inactive' } },
165    { row: ourPaddleRow, at: columnAt(court, 0), span: { text: paddle(side), color: OURS_COLOR } },
166    { row: moment.farPaddleRow, at: columnAt(court, length), span: { text: paddle(side === 1 ? -1 : 1), color: THEIRS_COLOR } },
167    ...named(court, name),
168    ...(moment.ball === undefined
169      ? []
170      : [{ row: moment.ball.row, at: columnAt(court, moment.ball.at), span: { text: BALL, color: 'text' } }]),
171    ...(moment.word === 'ping' ? [{ row: 0, at: behind, span: { text: 'ping', color: 'inactive' } }] : []),
172    ...(moment.word === 'pong'
173      ? [{ row: 0, at: wordAt(court, length + NAME_GAP, 'pong'), span: { text: 'pong', color: 'inactive' } }]
174      : []),
175    ...(moment.mark === undefined ? [] : [{ row: 0, at: wordAt(court, 2, moment.mark.text), span: moment.mark }]),
176  ]
177
178  return withExtras(
179    buddy(x, side, moment.pose),
180    extras.filter(extra => extra.at >= 0 && extra.at + extra.span.text.length <= columns),
181  )
182}
183
184// The last rally ends where its result starts: on the mascot's paddle for a point, on the far one for a miss.
185const endsAt = (reached: number, hasWon: boolean) => {
186  const from = Math.max(reached, RALLY_FRAMES) + LINGER_FRAMES
187  const beat = hasWon ? 0 : FLIGHT_FRAMES
188
189  return from + ((beat - (from % RALLY_FRAMES) + RALLY_FRAMES) % RALLY_FRAMES)
190}
191
192// One printable word, short enough for the far end of the band.
193const nameOf = (host: string | undefined) => (/^[\x21-\x7e]*/.exec(host ?? '')?.[0] ?? '').slice(0, LONGEST_NAME)
194
195// One game covers every call that starts before it is over. While a call is out it rallies; `until` is set
196// once the last one is back, and from there the rally plays out and ends on a point or a miss.
197//   host   who is on the far paddle        until  the frame the rally stops at
198//   ok     how the last call went
199export const pong: Animation = {
200  name: 'pong',
201  priority: 2,
202  frames: null,
203  framesFor: params => {
204    const until = frameIn(params, 'until')
205
206    return until === undefined ? null : until + END_FRAMES
207  },
208  frameMs: () => FRAME_MS,
209  cheat: {
210    name: 'ping-pong',
211    params: (typed): Params => {
212      const host = nameOf(typed)
213
214      return { ...(host === '' ? {} : { host }), ok: 'true', until: String(CHEAT_FRAMES) }
215    },
216    reply: params => (params.host === undefined ? 'Buddy: ping pong.' : `Buddy: ping pong with ${params.host}.`),
217  },
218
219  draw: (frame, stage, params) => {
220    const until = frameIn(params, 'until')
221    const hasWon = params.ok === 'true'
222    const isOver = until !== undefined && frame >= until
223    const court = courtAt(stage)
224
225    // With no room for a table it swings at the air, and the result is all in how it stands.
226    if (court === undefined) {
227      const pose: Pose = isOver ? (hasWon ? 'cheer' : 'miss') : swings(frame % RALLY_FRAMES, 0) ? 'swing' : 'ready'
228
229      return buddy(stage.x, sideAt(stage), pose)
230    }
231
232    const moment = !isOver
233      ? rallyAt(frame, court)
234      : hasWon
235        ? pointAt(frame - until, court)
236        : missAt(frame - until, court)
237
238    return scene(stage.x, court, moment, nameOf(params.host))
239  },
240}
241
242// Calls can be out side by side; the game is over only once the last of them is back.
243let calling = 0
244let latest: Params = {}
245
246const serve = (director: Director, host: string | undefined) => {
247  calling += 1
248  // Asked again while it plays, it carries on from the frame it is on, with this host on the far paddle.
249  latest = host === undefined ? {} : { host }
250  director.play(pong, latest)
251}
252
253const settle = (director: Director, hasWon: boolean) => {
254  calling -= 1
255
256  if (calling === 0) {
257    director.play(pong, {
258      ...latest,
259      ok: String(hasWon),
260      until: String(endsAt(director.frameOf(pong) ?? 0, hasWon)),
261    })
262  }
263}
264
265export const pongTriggers: Triggers = (on, director) => {
266  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
267    if (!callsApi(e.command)) {
268      return next(e)
269    }
270
271    let hasWon = false
272    serve(director, hostOf(e.command))
273
274    try {
275      const ran = await next(e)
276      hasWon = ran.deny === undefined && ran.isError !== true
277
278      return ran
279    } finally {
280      settle(director, hasWon)
281    }
282  })
283
284  on('tool.call', { tool: 'WebFetch' }, async ($, e, next) => {
285    let hasWon = false
286    serve(director, hostOf(e.url))
287
288    try {
289      const ran = await next(e)
290      hasWon = ran.deny === undefined && ran.isError !== true
291
292      return ran
293    } finally {
294      settle(director, hasWon)
295    }
296  })
297}
298
hooks/animations/run.ts 443 lines
1import { ARMS, FEET, GHOSTS, SPRITE_COLUMNS, SWEAT, SWEAT_COLOR, ghost, mascot } from '../lib/body'
2import { PREAMBLE, callsApi } from '../lib/command'
3import { frameIn, layRow } from '../lib/frame'
4import type { Animation, Params, Piece, Row, Span, Stage, Triggers } from '../lib/frame'
5import { opensPr } from './launch'
6import { middle } from './walk'
7
8const INTRO_FRAME_MS = 100
9const FRAME_MS = 80
10
11// The opening, in order: the world appears, the mascot fades out where it walked and in at the middle of the
12// band, sets itself, pulls back, and only then runs.
13const WORLD_FRAMES = 2
14const VANISH_FRAMES = 3
15const GAP_FRAMES = 2
16const APPEAR_FRAMES = 3
17const SET_FRAMES = 3
18const WIND_UP_FRAMES = 3
19const REAPPEAR_FRAME = WORLD_FRAMES + VANISH_FRAMES + GAP_FRAMES
20const SET_FRAME = REAPPEAR_FRAME + APPEAR_FRAMES
21const WIND_UP_FRAME = SET_FRAME + SET_FRAMES
22const INTRO_FRAMES = WIND_UP_FRAME + WIND_UP_FRAMES
23
24const STEP_FRAMES = 2
25const TIRED_AFTER_FRAMES = 125
26const GASP_EVERY = 8
27const GASP_FRAMES = 2
28// Once the last command is back it runs on this long: a command that comes in the meantime finds it running.
29const LINGER_FRAMES = 38
30// How long a command's result shows beside the head while it runs on.
31const MARK_FRAMES = 10
32const END_FRAMES = 16
33const STUMBLE_FRAMES = 2
34// Six seconds from the cheat to its cheer.
35const CHEAT_FRAMES = INTRO_FRAMES + 55
36
37const ROWS = 3
38// The feet share their row with the ground.
39const GROUND_ROW = 2
40const GROUND_COLOR = 'inactive'
41// Drawn through the middle of the row; the pebbles are what shows it moving.
42const GROUND = '────────·──────────────·─────·───────────'
43const COMMAND_COLUMNS = 24
44const BANNER_COLOR = '#f2c94c'
45const BANNER_INK = '#000000'
46const ROPE_COLUMNS = 7
47// The tail, and the cloth's two edges.
48const BANNER_TRIM_COLUMNS = 3
49const SHORTEST_BANNER = 4
50const UNFURL_FRAMES = 6
51const FLUTTER_FRAMES = 2
52const MARK_GAP = 2
53const PASSED: Span = { text: 'Finish!', color: 'success', bold: true }
54const FAILED: Span = { text: 'Oops!', color: 'error', bold: true }
55
56const LEAF = '#6aa84f'
57const TRUNK = '#a47148'
58
59type Thing = readonly { row: number; indent: number; glyphs: string; color: string }[]
60
61// What stands on the ground and goes by at its speed. A trunk is a stem rising out of the ground's own line.
62const THINGS: readonly Thing[] = [
63  [
64    { row: 0, indent: 1, glyphs: '▟█▙', color: LEAF },
65    { row: 1, indent: 0, glyphs: '▟███▙', color: LEAF },
66    { row: GROUND_ROW, indent: 2, glyphs: '╨', color: TRUNK },
67  ],
68  [
69    { row: 1, indent: 0, glyphs: '▟█▙', color: LEAF },
70    { row: GROUND_ROW, indent: 1, glyphs: '┴', color: TRUNK },
71  ],
72  [{ row: GROUND_ROW, indent: 0, glyphs: '▄▆▄', color: LEAF }],
73]
74const THING_SLOT = 14
75const WIDEST_THING = 5
76
77// Kicked up behind the feet as it sets off, by frames run.
78const DUST = [
79  { until: 2, behind: 2, glyph: '∘' },
80  { until: 4, behind: 4, glyph: '·' },
81] as const
82
83type Cell = { glyph: string; color?: string; dimColor?: true } | undefined
84type Extra = { row: number; at: number; span: Span }
85// A stretch of a row the world is kept out of, beyond the mascot's own box.
86type Cover = { row: number; at: number; columns: number }
87type Actor = { box: number | null; rows: readonly Row[]; extras: readonly Extra[]; covers?: readonly Cover[] }
88
89// The same answer for the same number every time it is drawn, and no pattern a person would notice.
90const noise = (seed: number) => Math.imul(seed + 1, 0x9e3779b1) >>> 16
91
92// A blank in what is stamped clears the cell: the command keeps a column of air on each side.
93const stamp = (cells: Cell[] | undefined, column: number, glyphs: string, color: string) => {
94  for (const [index, glyph] of [...glyphs].entries()) {
95    const at = column + index
96
97    if (cells !== undefined && at >= 0 && at < cells.length) {
98      cells[at] = glyph === ' ' ? undefined : { glyph, color }
99    }
100  }
101}
102
103// Lays spans over what is there, a blank in them leaving it be: the ground shows between the feet.
104const overlay = (cells: Cell[], column: number, spans: readonly Span[]) => {
105  let at = column
106
107  for (const span of spans) {
108    at += span.gap ?? 0
109
110    for (const glyph of span.text) {
111      if (glyph !== ' ' && at >= 0 && at < cells.length) {
112        cells[at] = {
113          glyph,
114          ...(span.color === undefined ? {} : { color: span.color }),
115          ...(span.dimColor === true ? { dimColor: true } : {}),
116        }
117      }
118
119      at += 1
120    }
121  }
122}
123
124// Every other slot of a tape holds one thing, somewhere inside the slot; `scroll` is the column the band starts at.
125const scatter = (rows: Cell[][], columns: number, scroll: number, slot: number, things: readonly Thing[]) => {
126  for (let index = Math.floor(scroll / slot); index * slot < scroll + columns; index += 1) {
127    const thing = things[noise(index * 2) % (things.length * 2)]
128    const column = index * slot + (noise(index * 2 + 1) % (slot - WIDEST_THING)) - scroll
129
130    for (const part of thing ?? []) {
131      stamp(rows[part.row], column + part.indent, part.glyphs, part.color)
132    }
133  }
134}
135
136// A Text's own leading and trailing spaces are not kept everywhere, so a row is runs of one look with gaps between.
137const piecesOf = (cells: readonly Cell[]): Piece[] => {
138  const pieces: { at: number; text: string; color?: string; dimColor?: true }[] = []
139
140  for (const [column, cell] of cells.entries()) {
141    const last = pieces.at(-1)
142
143    if (cell === undefined) {
144      continue
145    }
146
147    if (
148      last !== undefined &&
149      last.color === cell.color &&
150      last.dimColor === cell.dimColor &&
151      last.at + last.text.length === column
152    ) {
153      last.text += cell.glyph
154    } else {
155      pieces.push({ ...cell, at: column, text: cell.glyph })
156    }
157  }
158
159  return pieces.map(({ at, text, color, dimColor }) => ({
160    at,
161    spans: [{ text, ...(color === undefined ? {} : { color }), ...(dimColor === true ? { dimColor } : {}) }],
162  }))
163}
164
165// One line of plain characters: anything wider than a column would push the banner out of shape. The
166// preamble is left off, or every command run from the same folder would read the same.
167const brief = (command: string | undefined) => {
168  const first = (command ?? '').trim().split('\n')[0] ?? ''
169  const line = first.replace(PREAMBLE, '') || first
170  const plain = /^[\x20-\x7e]*/.exec(line)?.[0] ?? ''
171  const text = plain.replace(/ +/g, ' ').trim()
172
173  return text.length > COMMAND_COLUMNS || plain.length < line.length
174    ? `${text.slice(0, COMMAND_COLUMNS - 1)}…`
175    : text
176}
177
178// The ground is one long tape the band looks at through a window that moves a column a frame.
179const ground = (columns: number, scroll: number): Cell[] =>
180  Array.from({ length: columns }, (_, column) => ({
181    glyph: GROUND[(scroll + column) % GROUND.length] ?? '─',
182    color: GROUND_COLOR,
183  }))
184
185// The whole picture: what goes by, with the mascot in front of it. Only the world scrolls. The ground runs
186// along the row the feet are on, and gives way only to the feet themselves.
187const scene = ({ columns }: Stage, scroll: number, actor: Actor): Row[] => {
188  const world: Cell[][] = Array.from({ length: ROWS }, () => Array.from({ length: columns }, () => undefined))
189
190  scatter(world, columns, scroll, THING_SLOT, THINGS)
191
192  const extras = actor.extras.filter(extra => extra.at >= 0 && extra.at + extra.span.text.length <= columns)
193
194  // Nothing of the world shows through the mascot, or through what is drawn around it.
195  for (const cells of world) {
196    if (actor.box !== null) {
197      stamp(cells, actor.box, ' '.repeat(SPRITE_COLUMNS), '')
198    }
199  }
200
201  for (const extra of extras) {
202    stamp(world[extra.row], extra.at, ' '.repeat(extra.span.text.length), '')
203  }
204
205  for (const cover of actor.covers ?? []) {
206    stamp(world[cover.row], cover.at, ' '.repeat(cover.columns), '')
207  }
208
209  return world.map((cells, index) => {
210    const body = actor.rows[index]
211    const beside = extras.filter(extra => extra.row === index)
212
213    if (index !== GROUND_ROW) {
214      return layRow([
215        ...piecesOf(cells),
216        ...(body === undefined ? [] : [{ at: body.indent, spans: body.spans }]),
217        ...beside.map(extra => ({ at: extra.at, spans: [extra.span] })),
218      ])
219    }
220
221    const floor = ground(columns, scroll)
222
223    for (const [column, cell] of cells.entries()) {
224      if (cell !== undefined) {
225        floor[column] = cell
226      }
227    }
228
229    if (body !== undefined) {
230      overlay(floor, body.indent, body.spans)
231    }
232
233    for (const extra of beside) {
234      overlay(floor, extra.at, [extra.span])
235    }
236
237    return layRow(piecesOf(floor))
238  })
239}
240
241// What it tows: the command on a strip of cloth, on a rope from its waist. The rope and the cloth's tail
242// flutter; the cloth itself holds still, so it can be read. Nothing of the world shows between the two.
243const banner = (ran: number, at: number, command: string): { extras: Extra[]; covers: Cover[] } => {
244  const room = at - ROPE_COLUMNS - BANNER_TRIM_COLUMNS
245
246  if (command === '' || room < SHORTEST_BANNER) {
247    return { extras: [], covers: [] }
248  }
249
250  const text = command.length > room ? `${command.slice(0, room - 1)}…` : command
251  // It unrolls from the rope's end, so its last letters are out first.
252  const out = Math.ceil((text.length * Math.min(UNFURL_FRAMES, ran + 1)) / UNFURL_FRAMES)
253  const shown = text.slice(text.length - out).trimStart()
254  const end = at - ROPE_COLUMNS
255  const start = end - shown.length - BANNER_TRIM_COLUMNS
256  const isFlapping = Math.floor(ran / FLUTTER_FRAMES) % 2 === 0
257  const rope = Array.from({ length: ROPE_COLUMNS }, (_, column) => column)
258    .filter(column => column % 2 === (isFlapping ? 0 : 1))
259    .map(column => ({ row: 1, at: end + column, span: { text: '─', color: GROUND_COLOR } }))
260
261  return {
262    extras: [
263      { row: 1, at: start, span: { text: isFlapping ? '≈' : '~', color: BANNER_COLOR } },
264      { row: 1, at: start + 1, span: { text: '▐', color: BANNER_COLOR } },
265      { row: 1, at: start + 2, span: { text: shown, color: BANNER_INK, backgroundColor: BANNER_COLOR } },
266      { row: 1, at: end - 1, span: { text: '▌', color: BANNER_COLOR } },
267      ...rope,
268    ],
269    covers: [{ row: 1, at: start, columns: at - start }],
270  }
271}
272
273const runner = (ran: number, at: number, command: string): Actor => {
274  const isTired = ran >= TIRED_AFTER_FRAMES
275  const isLeftStep = Math.floor(ran / STEP_FRAMES) % 2 === 0
276  const isGasping = isTired && ran % GASP_EVERY >= GASP_EVERY - GASP_FRAMES
277  const sweat = SWEAT[Math.floor(ran / STEP_FRAMES) % SWEAT.length] ?? SWEAT[0]
278  const dust = DUST.find(puff => ran < puff.until)
279  const towed = banner(ran, at, command)
280
281  return {
282    covers: towed.covers,
283    box: at,
284    rows: mascot(
285      at,
286      isLeftStep ? ARMS.oneUp : ARMS.otherUp,
287      isGasping ? 'closed' : 'right',
288      isLeftStep ? FEET.left : FEET.right,
289    ),
290    extras: [
291      ...towed.extras,
292      ...(isTired ? [{ row: sweat.row, at: at + SPRITE_COLUMNS + 1, span: { text: sweat.glyph, color: SWEAT_COLOR } }] : []),
293      ...(dust === undefined ? [] : [{ row: GROUND_ROW, at: at - dust.behind, span: { text: dust.glyph, color: GROUND_COLOR } }]),
294    ],
295  }
296}
297
298const actorAt = (frame: number, { columns, x }: Stage, command: string): Actor => {
299  const center = middle(columns)
300
301  // Already in the middle, it has nowhere to fade to.
302  if (frame < WORLD_FRAMES || (x === center && frame < SET_FRAME)) {
303    return { box: x, rows: mascot(x, ARMS.down, 'ahead', FEET.both), extras: [] }
304  }
305
306  if (frame < WORLD_FRAMES + VANISH_FRAMES) {
307    return { box: x, rows: ghost(x, GHOSTS[frame - WORLD_FRAMES] ?? GHOSTS[0]), extras: [] }
308  }
309
310  if (frame < REAPPEAR_FRAME) {
311    return { box: null, rows: [], extras: [] }
312  }
313
314  if (frame < SET_FRAME - 1) {
315    return { box: center, rows: ghost(center, GHOSTS[GHOSTS.length - 1 - (frame - REAPPEAR_FRAME)] ?? GHOSTS[0]), extras: [] }
316  }
317
318  if (frame < SET_FRAME) {
319    return { box: center, rows: mascot(center, ARMS.down, 'ahead', FEET.both, { tint: 'text' }), extras: [] }
320  }
321
322  if (frame < WIND_UP_FRAME) {
323    return { box: center, rows: mascot(center, ARMS.down, 'right', FEET.both), extras: [] }
324  }
325
326  if (frame < INTRO_FRAMES) {
327    const back = Math.max(0, center - 1)
328
329    return { box: back, rows: mascot(back, ARMS.otherUp, 'right', FEET.left), extras: [] }
330  }
331
332  return runner(frame - INTRO_FRAMES, center, command)
333}
334
335// How a run ends, in the middle of a world that has stopped: a cheer, or a stumble a column on.
336const finisher = (frame: number, hasPassed: boolean, { columns }: Stage): Actor => {
337  const center = middle(columns)
338  const isStumbling = !hasPassed && frame < STUMBLE_FRAMES
339  const at = isStumbling ? Math.min(center + 1, Math.max(0, columns - SPRITE_COLUMNS)) : center
340
341  return {
342    box: at,
343    rows: hasPassed
344      ? mascot(at, ARMS.up, 'ahead', FEET.both)
345      : mascot(at, ARMS.down, 'closed', isStumbling ? FEET.left : FEET.both),
346    extras: [],
347  }
348}
349
350// Before it has reappeared the mascot never left; after, the middle is where it is.
351const leftAt = (frame: number) => (frame < REAPPEAR_FRAME ? 'in-place' : 'center')
352
353// One run covers every command that starts before it is over. While a command is out it loops; `until` is
354// set once the last one is back, and from there it runs on a while, then stops the world and ends.
355//   command  what its banner says           until  the frame the run stops at
356//   ok       how the last command went      ended  the frame that one came back at
357export const run: Animation = {
358  name: 'run',
359  priority: 2,
360  frames: null,
361  framesFor: params => {
362    const until = frameIn(params, 'until')
363
364    return until === undefined ? null : until + END_FRAMES
365  },
366  frameMs: frame => (frame < INTRO_FRAMES ? INTRO_FRAME_MS : FRAME_MS),
367  exit: leftAt,
368  cheat: {
369    name: 'run',
370    params: (typed): Params => ({
371      ...(typed === '' ? {} : { command: typed }),
372      ok: 'true',
373      ended: String(CHEAT_FRAMES),
374      until: String(CHEAT_FRAMES),
375    }),
376    reply: params => (params.command === undefined ? 'Buddy: running.' : `Buddy: running ${params.command}.`),
377  },
378
379  draw: (frame, stage, params) => {
380    const until = frameIn(params, 'until')
381    const ended = frameIn(params, 'ended')
382    const hasPassed = params.ok === 'true'
383    const isOver = until !== undefined && frame >= until
384    const scroll = Math.max(0, (isOver ? until : frame) - INTRO_FRAMES)
385    const actor = isOver ? finisher(frame - until, hasPassed, stage) : actorAt(frame, stage, brief(params.command))
386    const markedFrom = Math.max(ended ?? Number.POSITIVE_INFINITY, INTRO_FRAMES)
387    const isMarked = isOver || (frame >= markedFrom && frame < markedFrom + MARK_FRAMES)
388    const mark = hasPassed ? PASSED : FAILED
389
390    const beside = middle(stage.columns) + SPRITE_COLUMNS
391
392    return scene(stage, scroll, {
393      ...actor,
394      extras: [...actor.extras, ...(isMarked ? [{ row: 0, at: beside + MARK_GAP, span: mark }] : [])],
395      // A blank on each side of the word, so nothing going by runs into it.
396      covers: [
397        ...(actor.covers ?? []),
398        ...(isMarked ? [{ row: 0, at: beside, columns: MARK_GAP + mark.text.length + 1 }] : []),
399      ],
400    })
401  },
402}
403
404// Commands can run side by side; the run is over only once the last of them is back.
405let running = 0
406let latest: Params = {}
407
408export const runTriggers: Triggers = (on, director) => {
409  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
410    // Opening a PR and calling an API have animations of their own.
411    if (opensPr(e.command) || callsApi(e.command)) {
412      return next(e)
413    }
414
415    let hasPassed = false
416    running += 1
417    // Asked again while it runs, it carries on from the frame it is on, with this command on its banner.
418    latest = { command: e.command }
419    director.play(run, latest)
420
421    try {
422      const ran = await next(e)
423      hasPassed = ran.deny === undefined && ran.isError !== true
424
425      return ran
426    } finally {
427      running -= 1
428
429      if (running === 0) {
430        const reached = director.frameOf(run) ?? 0
431
432        director.play(run, {
433          ...latest,
434          ok: String(hasPassed),
435          ended: String(reached),
436          // A command that is back before the opening is over still gets all of it.
437          until: String(Math.max(reached, INTRO_FRAMES) + LINGER_FRAMES),
438        })
439      }
440    }
441  })
442}
443
hooks/animations/think.ts 218 lines
1import { ARMS, FEET, SPRITE_COLUMNS, SWEAT, SWEAT_COLOR, mascot } from '../lib/body'
2import type { Gaze } from '../lib/body'
3import { frameIn, withExtras } from '../lib/frame'
4import type { Animation, Director, Extra, Params, Row, Span, Stage, Triggers } from '../lib/frame'
5import { STRIDE, ahead } from './walk'
6
7const FRAME_MS = 125
8
9// It paces slowly at first, picks up after five seconds, and is sweating after fifteen.
10const HURRIED_AFTER_FRAMES = 40
11const WORRIED_AFTER_FRAMES = 120
12const CALM_STEP_FRAMES = 3
13const HURRIED_STEP_FRAMES = 2
14
15// A lap: a few steps out, a stop to ponder, the same steps back, another stop.
16const PACE_STEPS = 6
17const PONDER_STEPS = 3
18const LEG_STEPS = PACE_STEPS + PONDER_STEPS
19const GLANCE_STEP = 3
20const BLINK_EVERY = 16
21
22const THOUGHTS = ['.', '. o', '. o O', '. o O'] as const
23const THOUGHT_FRAMES = 3
24const THOUGHT_COLUMNS = Math.max(...THOUGHTS.map(thought => thought.length))
25const THOUGHT_COLOR = 'inactive'
26const BESIDE_GAP = 2
27const FLUSHED = '#e5533d'
28
29// The idea: it stops where it is, hands up, a mark where the thought was.
30const AHA_FRAMES = 8
31const FLASH_FRAMES = 2
32const AHA = '!'
33// A thought shorter than two seconds ends without one.
34const AHA_AFTER_FRAMES = 16
35const CHEAT_SECONDS = 8
36const LONGEST_CHEAT_SECONDS = 60
37
38type Spot = { at: number; side: 'left' | 'right' }
39
40// How many steps it has taken by `frame`.
41const stepsAt = (frame: number) => {
42  const calm = Math.min(frame, HURRIED_AFTER_FRAMES)
43
44  return Math.floor(calm / CALM_STEP_FRAMES) + Math.floor((frame - calm) / HURRIED_STEP_FRAMES)
45}
46
47// Where a step count puts it in its lap: how far out along the walk, which leg, and which beat of a stop.
48const paceAt = (steps: number) => {
49  const lap = steps % (LEG_STEPS * 2)
50  const isSecondLeg = lap >= LEG_STEPS
51  const leg = lap % LEG_STEPS
52  const walked = Math.min(leg, PACE_STEPS)
53
54  return {
55    out: isSecondLeg ? PACE_STEPS - walked : walked,
56    isSecondLeg,
57    leg,
58    pondering: leg < PACE_STEPS ? undefined : leg - PACE_STEPS,
59  }
60}
61
62// A thought that has been told when to stop holds the pace it had reached.
63const pacedAt = (frame: number, params: Params) =>
64  paceAt(stepsAt(Math.min(frame, frameIn(params, 'until') ?? frame)))
65
66const flip = (facing: Stage['facing']) => (facing === 'right' ? 'left' : 'right')
67
68// Room for a thought beside the head: to the right while there is some, else to the left.
69const spotAt = (x: number, columns: number): Spot | undefined => {
70  const right = x + SPRITE_COLUMNS + BESIDE_GAP
71  const left = x - BESIDE_GAP - THOUGHT_COLUMNS
72
73  if (right + THOUGHT_COLUMNS <= columns) {
74    return { at: right, side: 'right' }
75  }
76
77  return left >= 0 ? { at: left, side: 'left' } : undefined
78}
79
80// Whatever sits in the spot starts at the head and trails away from it.
81const inSpot = (spot: Spot | undefined, text: string, look: Omit<Span, 'text'>): Extra[] => {
82  if (spot === undefined) {
83    return []
84  }
85
86  return spot.side === 'right'
87    ? [{ row: 0, at: spot.at, span: { ...look, text } }]
88    : [{ row: 0, at: spot.at + THOUGHT_COLUMNS - text.length, span: { ...look, text: [...text].reverse().join('') } }]
89}
90
91// The drop goes on the side the thought is not.
92const sweatAt = (frame: number, x: number, columns: number, spot: Spot | undefined): Extra[] => {
93  const drop = SWEAT[Math.floor(frame / HURRIED_STEP_FRAMES) % SWEAT.length] ?? SWEAT[0]
94  const at = spot?.side === 'right' ? x - BESIDE_GAP : x + SPRITE_COLUMNS + 1
95
96  return at >= 0 && at < columns ? [{ row: drop.row, at, span: { text: drop.glyph, color: SWEAT_COLOR } }] : []
97}
98
99const aha = (frame: number, x: number, columns: number): Row[] =>
100  withExtras(
101    mascot(x, ARMS.up, 'ahead', FEET.both, frame < FLASH_FRAMES ? { tint: 'text' } : {}),
102    inSpot(spotAt(x, columns), AHA, { color: 'warning', bold: true }),
103  )
104
105// While the model thinks it loops; `until` is set once the thought is over, and from there it has its idea and ends.
106//   until  the frame the thought ended at
107export const think: Animation = {
108  name: 'think',
109  priority: 1,
110  frames: null,
111  framesFor: params => {
112    const until = frameIn(params, 'until')
113
114    return until === undefined ? null : until + AHA_FRAMES
115  },
116  frameMs: () => FRAME_MS,
117  // It has paced away from where it stood, and the walk carries on from there.
118  exit: (frame, params) => ({ steps: pacedAt(frame, params).out }),
119  cheat: {
120    name: 'think',
121    params: (typed): Params => {
122      const asked = Number(typed)
123      const seconds =
124        typed !== '' && Number.isFinite(asked) ? Math.min(Math.max(asked, 1), LONGEST_CHEAT_SECONDS) : CHEAT_SECONDS
125
126      return { until: String(Math.round((seconds * 1000) / FRAME_MS)) }
127    },
128    reply: () => 'Buddy: thinking.',
129  },
130
131  draw: (frame, stage, params) => {
132    const until = frameIn(params, 'until')
133    const { out, isSecondLeg, leg, pondering } = pacedAt(frame, params)
134    const { x } = ahead(stage, out)
135
136    if (until !== undefined && frame >= until) {
137      return aha(frame - until, x, stage.columns)
138    }
139
140    const isPondering = pondering !== undefined
141    // The second leg retraces the first, and a stop looks the way the next leg goes.
142    const way =
143      isSecondLeg === isPondering ? ahead(stage, out).facing : flip(ahead(stage, Math.max(0, out - 1)).facing)
144    const isBlinking = frame % BLINK_EVERY === BLINK_EVERY - 1
145    const gaze: Gaze = isPondering
146      ? pondering === PONDER_STEPS - 1
147        ? way
148        : 'closed'
149      : isBlinking
150        ? 'closed'
151        : leg === GLANCE_STEP
152          ? 'ahead'
153          : way
154    const isWorried = frame >= WORRIED_AFTER_FRAMES
155    const spot = spotAt(x, stage.columns)
156    const thought = THOUGHTS[Math.floor(frame / THOUGHT_FRAMES) % THOUGHTS.length] ?? THOUGHTS[0]
157
158    return withExtras(
159      mascot(
160        x,
161        isPondering ? ARMS.oneUp : ARMS.down,
162        gaze,
163        isPondering ? FEET.both : (STRIDE[stepsAt(frame) % STRIDE.length] ?? FEET.both),
164        isWorried ? { tint: FLUSHED } : {},
165      ),
166      [
167        ...inSpot(spot, thought, { color: THOUGHT_COLOR }),
168        ...(isWorried ? sweatAt(frame, x, stage.columns, spot) : []),
169      ],
170    )
171  },
172}
173
174// A thought that was long enough ends on its idea; a short one just stops.
175const conclude = (director: Director) => {
176  const reached = director.frameOf(think)
177
178  if (reached === undefined || reached < AHA_AFTER_FRAMES) {
179    director.stop(think)
180
181    return
182  }
183
184  director.play(think, { until: String(reached) })
185}
186
187export const thinkTriggers: Triggers = (on, director) => {
188  on('turn.step', async function* ($, e, next) {
189    // A subagent thinks out of sight.
190    if (e.agentId !== undefined) {
191      return yield* next(e)
192    }
193
194    let isThinking = false
195
196    try {
197      for await (const chunk of next(e)) {
198        if (chunk.kind === 'thinking' && !isThinking) {
199          isThinking = true
200          // One that follows another starts over, from where the last one left the mascot.
201          director.stop(think)
202          director.play(think)
203        } else if (isThinking && (chunk.kind === 'text' || chunk.kind === 'tool' || chunk.kind === 'stop')) {
204          isThinking = false
205          conclude(director)
206        }
207
208        yield chunk
209      }
210    } finally {
211      // Interrupted mid-thought, nothing came of it.
212      if (isThinking) {
213        director.stop(think)
214      }
215    }
216  })
217}
218
hooks/animations/wait.ts 95 lines
1import { ARMS, FEET, GHOSTS, bubbleFits, ghost, mascot } from '../lib/body'
2import { BLANK_ROW } from '../lib/frame'
3import type { Animation, Triggers } from '../lib/frame'
4import { STEP_MS } from './walk'
5
6const CLOSING_LINES = 3
7const QUESTION_END = /[??][\s*_`"'”」))]*$/
8
9// A reply often asks its question and then adds a closing line, so the last few lines count, not just the last.
10export const asksThePerson = (answer: string) =>
11  answer
12    .split('\n')
13    .filter(line => line.trim() !== '')
14    .slice(-CLOSING_LINES)
15    .some(line => QUESTION_END.test(line))
16
17const TELEPORT_FRAME_MS = 150
18const VANISH_FRAMES = 3
19const GAP_FRAMES = 2
20const APPEAR_FRAMES = 3
21const TELEPORT_FRAMES = VANISH_FRAMES + GAP_FRAMES + APPEAR_FRAMES
22const BLINK_EVERY = 12
23const BUBBLE = '< your turn'
24
25export const wait: Animation = {
26  name: 'wait',
27  priority: 2,
28  frames: null,
29  // The teleport is quick; the wave after it only needs the walk's slower beat.
30  frameMs: frame => (frame < TELEPORT_FRAMES ? TELEPORT_FRAME_MS : STEP_MS),
31  // Stopped before it reappears, the mascot never left; after, it stands at the left edge.
32  exit: frame => (frame < VANISH_FRAMES + GAP_FRAMES ? 'in-place' : 'left-edge'),
33  cheat: { name: 'your-turn', reply: () => 'Buddy: your turn.' },
34
35  draw: (frame, { columns, x }) => {
36    if (frame < VANISH_FRAMES) {
37      return ghost(x, GHOSTS[frame] ?? GHOSTS[0])
38    }
39
40    const appearing = frame - VANISH_FRAMES - GAP_FRAMES
41
42    if (appearing < 0) {
43      return [BLANK_ROW, BLANK_ROW, BLANK_ROW]
44    }
45
46    if (appearing < APPEAR_FRAMES - 1) {
47      return ghost(0, GHOSTS[GHOSTS.length - 1 - appearing] ?? GHOSTS[0])
48    }
49
50    if (appearing === APPEAR_FRAMES - 1) {
51      return mascot(0, ARMS.down, 'ahead', FEET.both, { tint: 'text' })
52    }
53
54    const beat = frame - TELEPORT_FRAMES
55
56    return mascot(
57      0,
58      beat % 2 === 1 ? ARMS.oneUp : ARMS.down,
59      beat % BLINK_EVERY === BLINK_EVERY - 2 ? 'closed' : 'ahead',
60      FEET.both,
61      bubbleFits(columns, BUBBLE) ? { says: BUBBLE } : {},
62    )
63  },
64}
65
66export const waitTriggers: Triggers = (on, director) => {
67  on('turn.complete', ($, e, next) => {
68    if (e.agentId === undefined && asksThePerson(e.answer)) {
69      director.play(wait)
70    }
71
72    return next(e)
73  })
74
75  on('turn.start', ($, e, next) => {
76    director.stop(wait)
77
78    return next(e)
79  })
80
81  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
82    if (e.agentId !== undefined) {
83      return next(e)
84    }
85
86    director.play(wait)
87
88    try {
89      return await next(e)
90    } finally {
91      director.stop(wait)
92    }
93  })
94}
95