SLOPSHOPPER

tea-egg

Tea Egg: raise a pet egg that slowly marinates while you code

panebandguardcommandtoastprompt
★ 4v0.9.3MITupdated 2026-10-21helenlin0621/tea-egg
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · tea-egg
│ ┃ Tea Egg ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ │ tea-egg │ │ ┃ ⏺ Read(src/auth.ts) │ 🥚 You got your first egg! Marinate it │ │ ┃ ▄▄ ⎿ Read 6 lines │ into a tea egg. Type /egg to take a look │ │ ┃ ▄▀▀ ▄ ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ ▀▄ ▀▀▀ ▄▀▀ ⎿ Added 2 lines, removed 1 line ╭───────────────────────╮ │ ┃ ⏺ Bash(bun test) │ tea-egg │ │ ┃ ⎿ 3 pass, 1 fail │ (New in the Eggdex!) │ │ ┃ ╰───────────────────────╯ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /egg │ ┃ ⎿ tea-egg: Tea egg panel opened │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ Eggy #2 (✧ᴗ✧) 🥚(✧ᴗ✧) Eggy #2 | Flavor ░░░░░░░░░░ 1% | Broth █████ Panel x ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
🥚(✧ᴗ✧) Eggy #2 | Flavor ░░░░░░░░░░ 1% | Broth █████ Panel x
Pane · Tea Egg
▄▄ ▄▀▀ ▄ ▀▄ ▀▀▀ ▄▀▀ Eggy #2 (✧ᴗ✧) Flavor ░░░░░░░░░░ 1% Broth ██████████ 100 Mood ███████░░░ 70 [ Refill ][ Flip ][ Dex ][ Hide band ]
README

🥚 Tea Egg (tea-egg)

繁體中文

Raise an egg soaking in tea broth inside Claude Code while you code. Every task you finish lets the flavor sink in a little more; in about a week it's done marinating.

 🥚(•ᴗ•)  Eggy #3 | Flavor ██████░░░░ 62% | Broth ███░░ | Smells of tea…

Install

In Claude Code, run:

/plugin marketplace add helenlin0621/tea-egg
/plugin install tea-egg@tea-egg

Requires Claude Code 2.1.289 or later (update with claude update).

Claude keeps a separate save for each way a plugin is loaded (an install, --plugin-dir). If Tea Egg finds a different save from another way of loading it, it asks before anything changes: type /egg sync to compare the two and copy the other one over. Copying asks once more, then overwrites this save for good.

Update

/plugin marketplace update tea-egg
/plugin update tea-egg@tea-egg

Then restart Claude Code.

Commands

CommandWhat it does
/eggOpen/close the panel
/egg refillTop up the broth
/egg flipFlip the egg
/egg dexShow the Eggdex
/egg bandHide/show the band above the prompt (stays that way until you run it again; the × on the band hides it too)
/egg syncCompare with a save left by another way of loading Tea Egg; /egg sync yes then /egg sync confirm copies it over, /egg sync no keeps yours
/egg name <name>Name the current egg
/egg helpHelp

How your egg turns out depends on your coding habits. Collect them all!

Language

The UI follows your system language: Chinese locales get Traditional Chinese, everything else gets English. To choose one yourself, set TEA_EGG_LANG to en or zh-TW before starting Claude Code:

ShellCommand
macOS / LinuxTEA_EGG_LANG=en claude
Windows cmdset TEA_EGG_LANG=en then claude
Windows PowerShell$env:TEA_EGG_LANG = "en" then claude

The language is picked when a session starts. Eggs you already have keep their names.

Security

NetworkRuns programsReads/writes filesCalls AISends dataBlocks or changes commands
NoNoNoNoNoNo
  • The Mod only "looks at" the text of Bash/PowerShell commands and whether they succeeded, to tell whether you ran tests or a dangerous command. The full list of patterns is public in hooks/detect.ts.
  • All data stays in the local storage Claude Code sets aside for this Mod.
  • The dex contents are encoded to avoid spoilers; see the note at the top of hooks/spoilers.ts.

License

MIT. See LICENSE.

Source 21 files
hooks/register.tsx 718 lines
1import { update, type EngineInterface, type Register, type Timer } from 'claude-code'
2import { localTime, parseFakeDate, systemOffset, type ClockConfig, type LocalTime } from './clock'
3import { observe, OBSERVED_TOOLS } from './detect'
4import { dateAction, paneRefillLabel, remainingMs, setRestOverride, timedNow, timedTick } from './dates'
5import { dexTitle, onCommand, onObserved, onPrompt, onSessionOpen, onTick, onTurn } from './flow'
6import { BAND_STORE_KEY, FAKE_STORE_KEY, STORE_KEY, SYNC_DISMISSED_KEY } from './model'
7import { compareLines, offerFor, type SyncOffer } from './sync'
8import { dexArt, eggArt, nextPreview, panelLines, PREVIEW_KEYS, PREVIEW_LABELS, previewArt, SVG_PX, type Art } from './panel'
9import { dexCaption, dexHeader } from './rules'
10import { decodeSpoilers } from './spoilers'
11import { loadSave, mutate, type StoreIo } from './store'
12import { parseUse, usePrompt, useStale, useTurn, type SessionUse, type UseStep, type Wait } from './usage'
13import type { Step } from './engine'
14import type { Save } from '../types'
15import { detectLang, setLang } from './i18n'
16import { T, fill } from './text'
17import { RASTER_ROWS, SIZE } from './pixels'
18import { bandSegments, fitSegments, strWidth } from './view'
19
20// state refs' plugin / key must be literals, written in this file (the one that uses $.state)
21const SAVE_REF = { plugin: 'tea-egg', key: 'save' } as const
22const SHOW_DEX_REF = { plugin: 'tea-egg', key: 'showDex' } as const
23const COUNTED_REF = { plugin: 'tea-egg', key: 'sessionCounted' } as const
24const PREVIEW_REF = { plugin: 'tea-egg', key: 'preview' } as const
25const BAND_REF = { plugin: 'tea-egg', key: 'bandHidden' } as const
26const SYNC_REF = { plugin: 'tea-egg', key: 'syncOffer' } as const
27const SYNC_CONFIRM_REF = { plugin: 'tea-egg', key: 'syncConfirming' } as const
28
29export const PANE = 'tea-egg'
30const TICK_MS = 60_000
31const rng = Math.random
32
33let clock: ClockConfig = { offsetMinutes: systemOffset, fake: null, loadedAt: 0 }
34export const localNow = (now: number): LocalTime => localTime(now, clock)
35// Sessions nobody is watching (claude -p, SDK scripts, schedules) don't raise the egg; becomes true once a surface attaches
36let interactive = false
37// Read and write a separate save while a fake date is in effect
38const storeKey = () => (clock.fake ? FAKE_STORE_KEY : STORE_KEY)
39
40// "Preview n/total: label" in the current language
41function previewText(template: string, key: string): string {
42  const n = PREVIEW_KEYS.indexOf(key) + 1
43  return fill(template, { n: String(n), total: String(PREVIEW_KEYS.length), label: PREVIEW_LABELS[key] ?? key })
44}
45
46function commandOf(e: { tool: string }): string {
47  const command = (e as { command?: unknown }).command
48  return typeof command === 'string' ? command : ''
49}
50
51// The loader doesn't follow $ across imports: every $.xxx call is written in this file
52const ioOf = ($: EngineInterface): StoreIo => ({
53  now: () => $.clock.now(),
54  read: () => $.store.get(storeKey()),
55  write: async save => {
56    await $.store.set(storeKey(), save)
57    await $.state.set(SAVE_REF, save)
58  },
59  toast: (text, order) => toastAt($, text, order),
60})
61
62// The desktop app shows only the first of several toasts sent at once: an event's later toasts wait their turn
63const TOAST_GAP_MS = 3_000
64
65function toastAt($: EngineInterface, text: string, order: number): void {
66  if (order === 0) $.ui.toast(text)
67  else $.clock.after(order * TOAST_GAP_MS, () => $.ui.toast(text))
68}
69
70// Time spent waiting for the person within the current turn (usage.ts leaves it out). A permission prompt counts
71// from when it is shown until its tool call ends (a command run after approval rides along, usually seconds);
72// these tools wait for an answer the whole time they run
73const WAIT_TOOLS = ['AskUserQuestion', 'ExitPlanMode'] as const
74let askedAt: number | null = null
75let waits: Wait[] = []
76
77// Each session's usage record (usage.ts) sits under its own key, so sessions never overwrite each other's
78const usePrefix = () => `${storeKey()}/session/`
79
80async function sessionIdOf($: EngineInterface): Promise<string | null> {
81  try {
82    return await $.session.id()
83  } catch {
84    return null
85  }
86}
87
88// Update this session's usage record and the save together; without a session id, run the rest alone
89async function withUse(
90  $: EngineInterface,
91  track: (s: Save, use: SessionUse, at: number, t: LocalTime, tag: string) => UseStep,
92  rest: (s: Save, at: number) => Step = s => ({ save: s, effects: [] }),
93): Promise<void> {
94  const id = await sessionIdOf($)
95  if (id === null) {
96    await mutate(ioOf($), rest)
97    return
98  }
99  const key = usePrefix() + id
100  const tag = id.slice(0, 8) // enough to tell sessions apart in the save
101  let use = parseUse(await $.store.get(key))
102  await mutate(ioOf($), (s, at) => {
103    const r = track(s, use, at, localNow(at), tag)
104    use = r.use
105    const step = rest(r.save, at)
106    return { ...step, effects: [...r.effects, ...step.effects] }
107  })
108  await $.store.set(key, use)
109}
110
111// Drop usage records of sessions unused for a long time so the store doesn't grow forever
112async function pruneUse($: EngineInterface, now: number): Promise<void> {
113  for (const key of await $.store.keys()) {
114    if (!key.startsWith(usePrefix())) continue
115    if (useStale(parseUse(await $.store.get(key)), now)) await $.store.delete(key)
116  }
117}
118
119// Toggle the side pane: shared by /egg and the band button; returns the state after toggling
120async function togglePane($: EngineInterface): Promise<boolean> {
121  if ((await $.ui.panes()).some(p => p.id === PANE)) {
122    await $.ui.close({ id: PANE })
123    return false
124  }
125  await $.ui.open({ id: PANE, title: T().title })
126  return true
127}
128
129// The band's hidden flag lives in the store (kept across sessions); state mirrors it so render can read it
130async function loadBand($: EngineInterface): Promise<void> {
131  try {
132    await $.state.set(BAND_REF, (await $.store.get(BAND_STORE_KEY)) === true)
133  } catch {
134    // Show the band when the flag can't be read
135  }
136}
137
138// Flip the band's hidden flag; returns whether it is hidden now
139async function toggleBand($: EngineInterface): Promise<boolean> {
140  const hidden = (await $.state.get(BAND_REF)).value !== true
141  await $.store.set(BAND_STORE_KEY, hidden)
142  await $.state.set(BAND_REF, hidden)
143  return hidden
144}
145
146// Claude keeps one store file per load identity (tea-egg@<marketplace> installed, tea-egg@inline by --plugin-dir).
147// This load only writes its own save; the other tea-egg store files are read so the person can choose to copy one over.
148const STORE_FILE = /^tea-egg_.+\.json$/
149
150// The real saves in every tea-egg store file (ours included; pickOther skips the one equal to ours)
151async function storeFileSaves($: EngineInterface): Promise<unknown[]> {
152  try {
153    const configDir =
154      (await $.env.get('CLAUDE_CONFIG_DIR')) ??
155      `${(await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? ''}/.claude`
156    const dir = `${configDir}/plugins/store`
157    const saves: unknown[] = []
158    for (const entry of await $.fs.list(dir)) {
159      if (entry.kind !== 'file' || !STORE_FILE.test(entry.name)) continue
160      try {
161        saves.push((JSON.parse((await $.fs.read(`${dir}/${entry.name}`)) as string) as Record<string, unknown>)[STORE_KEY])
162      } catch {
163        // A file mid-write or unreadable is skipped
164      }
165    }
166    return saves
167  } catch {
168    return []
169  }
170}
171
172// Look for another save to offer; shows the offer in state and toasts once when there is one
173async function findSyncOffer($: EngineInterface, announce: boolean): Promise<SyncOffer | null> {
174  if (clock.fake) return null
175  const offer = offerFor(await $.store.get(STORE_KEY), await storeFileSaves($), await $.store.get(SYNC_DISMISSED_KEY))
176  await $.state.set(SYNC_REF, offer)
177  if (offer && announce) $.ui.toast(T().sync.found)
178  return offer
179}
180
181const currentOffer = async ($: EngineInterface): Promise<SyncOffer | null> =>
182  (await $.state.get(SYNC_REF)).value ?? (await findSyncOffer($, false))
183
184// Step 1 of syncing: the person chose Sync; ask them to confirm the overwrite. false when there is nothing to copy
185async function askSync($: EngineInterface): Promise<boolean> {
186  if (!(await currentOffer($))) return false
187  await $.state.set(SYNC_CONFIRM_REF, true)
188  return true
189}
190
191// Step 2: overwrite ours with the offered save, no backup (the person confirmed it can't be undone)
192async function confirmSync($: EngineInterface): Promise<'done' | 'ask-first' | 'nothing'> {
193  if ((await $.state.get(SYNC_CONFIRM_REF)).value !== true) return 'ask-first'
194  await $.state.set(SYNC_CONFIRM_REF, false)
195  const offer = await currentOffer($)
196  if (!offer) return 'nothing'
197  await mutate(ioOf($), () => ({ save: offer.save, effects: [] }))
198  await $.state.set(SYNC_REF, null)
199  return 'done'
200}
201
202// Back out of the confirmation; the offer stays, so it is not a "No"
203async function cancelSync($: EngineInterface): Promise<void> {
204  await $.state.set(SYNC_CONFIRM_REF, false)
205}
206
207// Keep ours and don't ask again until the other save changes; false when there was nothing to decline
208async function declineSync($: EngineInterface): Promise<boolean> {
209  await $.state.set(SYNC_CONFIRM_REF, false)
210  const offer = await currentOffer($)
211  if (!offer) return false
212  await $.store.set(SYNC_DISMISSED_KEY, offer.fingerprint)
213  await $.state.set(SYNC_REF, null)
214  return true
215}
216
217const confirmReply = (r: 'done' | 'ask-first' | 'nothing') =>
218  r === 'done' ? T().sync.accepted : r === 'ask-first' ? T().sync.confirmFirst : T().sync.nothing
219
220// Activate only once per load; keep the timer handle and cancel it before registering again
221let tick: Timer | null = null
222
223// A timed special date's countdown (dates.ts): redraw every second so the timer moves, and settle it right on time
224// (the warning and the end) instead of waiting for the next event. Re-armed after anything that may start or end it
225let beat: Timer | null = null
226let alarms: Timer[] = []
227let armedFor: string | null = null
228
229// Each session keeps its own copy of the save (SAVE_REF), refreshed only by its own events. On a timed day an ask
230// started or answered in another session must show here too, so re-read the shared save every few seconds and pick
231// it up when it changed (read only: the store is written by events, never by this timer)
232const FOLLOW_MS = 5_000
233let follow: Timer | null = null
234
235function followDay($: EngineInterface, on: boolean): void {
236  if (!on) {
237    follow?.cancel()
238    follow = null
239    return
240  }
241  if (follow) return
242  follow = $.clock.every(FOLLOW_MS, () => {
243    void (async () => {
244      const shared = await loadSave(ioOf($))
245      const mine = (await $.state.get(SAVE_REF)).value
246      if (JSON.stringify(shared) === JSON.stringify(mine)) return
247      await $.state.set(SAVE_REF, shared)
248      await armCountdown($, shared)
249    })().catch(() => undefined)
250  })
251}
252
253async function armCountdown($: EngineInterface, save: Save): Promise<void> {
254  const now = await $.clock.now()
255  const day = timedNow(save, localNow(now))
256  followDay($, day !== null)
257  const run = day?.entry?.phase === 'run' ? day : null
258  const id = run ? `${run.key}@${run.entry!.startedAt}/${run.entry!.warned === true}` : null
259  if (id === armedFor) return
260  armedFor = id
261  beat?.cancel()
262  beat = null
263  for (const a of alarms) a.cancel()
264  alarms = []
265  try {
266    $.ui.invalidate('ui.render')
267  } catch {
268    // Nothing drawn yet
269  }
270  if (!run) return
271  beat = $.clock.every(1000, () => {
272    try {
273      $.ui.invalidate('ui.render')
274    } catch {
275      // Ignore silently
276    }
277  })
278  const settleNow = () => {
279    void mutate(ioOf($), (s, at) => timedTick(s, at))
280      .then(step => armCountdown($, step.save))
281      .catch(() => undefined)
282  }
283  const left = remainingMs(run.spec, run.entry!, now)
284  const warnIn = left - run.spec.warnSeconds * 1000
285  if (warnIn > 0 && run.entry!.warned !== true) alarms.push($.clock.after(warnIn, settleNow))
286  alarms.push($.clock.after(left + 100, settleNow))
287}
288
289// Run /egg <args> from a button (the band's or the pane's special-date button), toasting the reply
290async function pressArgs($: EngineInterface, args: string): Promise<void> {
291  const step = await mutate(ioOf($), (s, at) => onCommand(s, at, localNow(at), args, rng))
292  // After the toasts the press itself set off
293  if (step.reply) toastAt($, step.reply, step.effects.length)
294  await armCountdown($, step.save)
295}
296
297const hasTerminal = async ($: EngineInterface): Promise<boolean> => {
298  try {
299    return (await $.session.surfaces()).includes('terminal')
300  } catch {
301    return false
302  }
303}
304
305// On desktop a new session's surface often attaches after the Mod loads, so the attach signal is missed:
306// if session.start sees no surface, poll every 3 seconds for up to 10 minutes and activate once one shows up
307const WATCH_MS = 3_000
308const WATCH_LIMIT = 200
309let watch: Timer | null = null
310
311async function hasSurface($: EngineInterface): Promise<boolean> {
312  try {
313    return (await $.session.surfaces()).length > 0
314  } catch {
315    return false
316  }
317}
318
319function watchForSurface($: EngineInterface): void {
320  watch?.cancel()
321  let tries = 0
322  watch = $.clock.every(WATCH_MS, () => {
323    void (async () => {
324      tries++
325      if (interactive || tries > WATCH_LIMIT) {
326        watch?.cancel()
327        watch = null
328        return
329      }
330      if (await hasSurface($)) {
331        watch?.cancel()
332        watch = null
333        await activate($)
334      }
335    })().catch(() => undefined)
336  })
337}
338
339async function activate($: EngineInterface): Promise<void> {
340  // Claim the slot synchronously so start and attach arriving together don't activate twice
341  if (interactive) return
342  interactive = true
343  try {
344    // Also decided here in case this load never saw session.start
345    setLang(detectLang(await $.env.get('TEA_EGG_LANG')))
346    const now = await $.clock.now()
347    clock = {
348      offsetMinutes: systemOffset,
349      fake: parseFakeDate(await $.env.get('TEA_EGG_FAKE_DATE')),
350      loadedAt: now,
351    }
352    // A short rest between a timed day's asks, only with a fake date so the real save never gets one
353    const rest = Number(await $.env.get('TEA_EGG_TEST_REST'))
354    setRestOverride(clock.fake !== null && rest > 0 ? rest * 1000 : null)
355    try {
356      await findSyncOffer($, true)
357    } catch {
358      // No offer when the other saves can't be read
359    }
360    const counted = (await $.state.get(COUNTED_REF)).value === true
361    const opened = await mutate(ioOf($), (s, at) => onSessionOpen(s, at, localNow(at), !counted))
362    await armCountdown($, opened.save).catch(() => undefined)
363    if (!counted) await $.state.set(COUNTED_REF, true)
364    await pruneUse($, now).catch(() => undefined)
365    tick?.cancel()
366    tick = $.clock.every(TICK_MS, () => {
367      void mutate(ioOf($), (s, at) => onTick(s, at, localNow(at), rng))
368        .then(step => armCountdown($, step.save))
369        .catch(() => undefined)
370    })
371  } catch {
372    // An egg error must never affect the user
373  }
374}
375
376export const register: Register = on => {
377  on('session.start', async ($, e, next) => {
378    try {
379      // Pick the language first: the command description below is already localized.
380      // A failed env read must not stop /egg from being registered, so fall back to the locale.
381      let envLang: string | undefined
382      try {
383        envLang = await $.env.get('TEA_EGG_LANG')
384      } catch {
385        envLang = undefined
386      }
387      setLang(detectLang(envLang))
388      await $.command.register({ name: 'egg', description: T().commandDescription })
389      await loadBand($)
390      // Activate only if someone is watching: an interactive session, or a surface already attached (a desktop hot reload sends no new attach)
391      const seen = e.isInteractive === true || (await hasSurface($))
392      if (seen) await activate($)
393      else watchForSurface($)
394    } catch {
395      // An egg error must never affect the user
396    }
397    return next(e)
398  })
399
400  // Desktop (SDK host): no surface at session.start; it connects later
401  on('session.attach', async ($, e, next) => {
402    try {
403      await activate($)
404    } catch {
405      // Ignore silently
406    }
407    return next(e)
408  })
409
410  // If a surface is attached when the user submits a message, activate here even if earlier signals were missed (so this turn's flavor counts)
411  on('prompt.submit', async ($, e, next) => {
412    try {
413      if (!interactive && (await hasSurface($))) await activate($)
414      if (interactive) {
415        await withUse($, usePrompt)
416        const terminal = await hasTerminal($)
417        const step = await mutate(ioOf($), (s, at) => onPrompt(s, at, localNow(at), terminal, rng))
418        await armCountdown($, step.save)
419      }
420    } catch {
421      // Ignore silently
422    }
423    return next(e)
424  })
425
426  // A permission prompt is about to be shown: the wait runs until that tool call ends
427  on('classic.PermissionRequest', async ($, e, next) => {
428    try {
429      if (interactive) askedAt = await $.clock.now()
430    } catch {
431      // Ignore silently
432    }
433    return next(e)
434  })
435
436  on('turn.complete', async ($, e, next) => {
437    const ran = await next(e)
438    try {
439      if (interactive && e.agentId === undefined && e.reason !== 'error') {
440        const turnWaits = waits
441        waits = []
442        const terminal = await hasTerminal($)
443        await withUse($, (s, use, at, t, tag) => useTurn(s, use, at, t, tag, turnWaits, terminal), (s, at) => onTurn(s, at, localNow(at), rng))
444      }
445    } catch {
446      // Ignore silently
447    }
448    return ran
449  })
450
451  // Observe only: always call next(e) and return its result unchanged
452  on('tool.call', async ($, e, next) => {
453    let started: number | null = null
454    try {
455      if (interactive) started = await $.clock.now()
456    } catch {
457      // Ignore silently
458    }
459    const ran = await next(e)
460    try {
461      if (!interactive) return ran
462      const tool = String(e.tool)
463      // Waiting for the person: a tool that asks them, or a permission prompt raised during this call
464      const ended = await $.clock.now()
465      const asked = askedAt !== null && started !== null && askedAt >= started ? askedAt : null
466      if (asked !== null) askedAt = null
467      const from = (WAIT_TOOLS as readonly string[]).includes(tool) ? started : asked
468      if (from !== null && ended > from) waits.push([from, ended])
469      const command = (OBSERVED_TOOLS as readonly string[]).includes(tool) ? commandOf(e) : ''
470      const obs = observe(tool, command, ran)
471      if (obs !== null) await mutate(ioOf($), (s, at) => onObserved(s, at, localNow(at), obs, rng))
472    } catch {
473      // Ignore silently
474    }
475    return ran
476  })
477
478  // The band above the prompt; always steps aside on errors or when a survey is showing
479  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
480    try {
481      // The prompt being drawn means a surface is attached; state can't be written during render, so activate on the next tick
482      if (!interactive) $.clock.after(0, () => void activate($))
483      if (e.props.hasSurvey) return next(e)
484      if ((await $.state.get(BAND_REF)).value === true) return next(e)
485      const save = (await $.state.get(SAVE_REF)).value
486      if (!save) return next(e)
487      const now = await $.clock.now()
488      const columns = e.props.bodyColumns ?? e.viewport?.columns ?? 80
489      // Reserve room on the right for the panel and x buttons (1 space + label + 1 space + x + 1 column of margin)
490      // A special-date button (dates.ts) stays on the band; the stats give way first
491      const action = dateAction(save, localNow(now))
492      const pressable = action !== null && action.done !== true ? action : null
493      const reserve = strWidth(T().buttons.panel) + 4 + (pressable ? strWidth(pressable.label) + 5 : 0)
494      const segs = fitSegments(bandSegments(save, localNow(now), now), Math.max(10, columns - reserve))
495      const { Box, Text, Button } = $.ui.resolve(e)
496      const onPanel = async () => {
497        try {
498          await togglePane($)
499        } catch {
500          // A button error must never affect the user
501        }
502      }
503      const onHide = async () => {
504        try {
505          if (await toggleBand($)) $.ui.toast(T().bandHidden)
506        } catch {
507          // A button error must never affect the user
508        }
509      }
510      return (
511        // Stats on the left; the panel and x buttons pinned to the right edge
512        <Box justifyContent="space-between" width="100%">
513          <Box key="stats">
514            {segs.map((seg, i) => (
515              <Text key={String(i)} color={seg.color} dimColor={seg.dim}>{seg.text}</Text>
516            ))}
517          </Box>
518          <Box key="actions">
519            {pressable && <Text key="date-gap"> </Text>}
520            {pressable && (
521              <Button
522                key="date-action"
523                label={`[ ${pressable.label} ]`}
524                hotkey={pressable.hotkey || undefined}
525                plain
526                onPress={async () => {
527                  try {
528                    await pressArgs($, pressable.args)
529                  } catch {
530                    // A button error must never affect the user
531                  }
532                }}
533              />
534            )}
535            <Text key="gap"> </Text>
536            <Button key="panel" label={T().buttons.panel} plain dimColor onPress={onPanel} />
537            <Text key="gap2"> </Text>
538            <Button key="hide" label="x" plain dimColor onPress={onHide} />
539          </Box>
540        </Box>
541      )
542    } catch {
543      return next(e)
544    }
545  })
546
547  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
548    try {
549      const { Box, Text, Button } = $.ui.resolve(e)
550      const save = (await $.state.get(SAVE_REF)).value
551      const showDex = (await $.state.get(SHOW_DEX_REF)).value === true
552      const bandHidden = (await $.state.get(BAND_REF)).value === true
553      if (!save) return <Text dimColor>{T().waiting}</Text>
554      const now = await $.clock.now()
555      const t = localNow(now)
556      const columns = e.props.bodyColumns ?? e.viewport?.columns ?? SIZE
557      // Only terminal has Raster; other surfaces only have Svg
558      const draw = (art: Art | null, key: string) => {
559        if (art === null) return null
560        if (art.kind === 'raster' && e.surface === 'terminal') {
561          const { Raster } = $.ui.resolve(e)
562          return <Raster key={key} columns={SIZE} rows={RASTER_ROWS} cells={art.cells} />
563        }
564        if (art.kind === 'svg' && e.surface !== 'terminal') {
565          const { Svg } = $.ui.resolve(e)
566          return <Svg key={key} source={art.source} alt={T().eggAlt} width={SVG_PX} height={SVG_PX} />
567        }
568        return art.kind === 'ascii' ? (
569          <Box key={key} flexDirection="column">{art.lines.map((l, i) => <Text key={String(i)}>{l}</Text>)}</Box>
570        ) : null
571      }
572      const press = (args: string) => async () => {
573        try {
574          await pressArgs($, args)
575        } catch {
576          // A button error must never affect the user
577        }
578      }
579      const syncPress = (choice: 'yes' | 'no' | 'overwrite' | 'cancel') => async () => {
580        try {
581          if (choice === 'yes') {
582            if (!(await askSync($))) $.ui.toast(T().sync.nothing)
583          } else if (choice === 'overwrite') $.ui.toast(confirmReply(await confirmSync($)))
584          else if (choice === 'cancel') await cancelSync($)
585          else $.ui.toast((await declineSync($)) ? T().sync.declined : T().sync.nothing)
586        } catch {
587          // A button error must never affect the user
588        }
589      }
590      const offer = (await $.state.get(SYNC_REF)).value ?? null
591      const confirming = (await $.state.get(SYNC_CONFIRM_REF)).value === true
592      const slots = decodeSpoilers().dexSlots
593      const preview = (await $.state.get(PREVIEW_REF)).value ?? null
594      const art = preview !== null ? previewArt(preview, e.surface, columns) : eggArt(save, t, now, e.surface, columns)
595      const paneAction = dateAction(save, t)
596      return (
597        <Box flexDirection="column">
598          {preview !== null && (
599            <Text key="preview" dimColor>
600              {previewText(T().previewBanner, preview)}
601            </Text>
602          )}
603          {offer !== null && (
604            <Box key="sync" flexDirection="column" marginBottom={1}>
605              {compareLines(save, offer.save, localNow).map((line, i) => (
606                <Text key={`sync-line-${i}`} color={i === 0 ? 'yellow' : undefined}>{line}</Text>
607              ))}
608              {confirming ? (
609                <Box key="sync-confirm" flexDirection="column">
610                  <Text key="sync-confirm-text" color="red">{T().sync.confirm}</Text>
611                  <Box key="sync-confirm-buttons">
612                    <Button key="sync-overwrite" label={T().sync.overwrite} onPress={syncPress('overwrite')} />
613                    <Button key="sync-cancel" label={T().sync.cancel} onPress={syncPress('cancel')} />
614                  </Box>
615                </Box>
616              ) : (
617                <Box key="sync-buttons">
618                  <Button key="sync-yes" label={T().sync.yes} onPress={syncPress('yes')} />
619                  <Button key="sync-no" label={T().sync.no} onPress={syncPress('no')} />
620                </Box>
621              )}
622            </Box>
623          )}
624          {draw(art, 'egg')}
625          {panelLines(save, t, now).map((line, i) => <Text key={String(i)}>{line}</Text>)}
626          <Box>
627            <Button
628              key="refill"
629              label={paneRefillLabel(save, t) ?? T().buttons.refill}
630              hotkey={paneAction?.args === 'refill' ? paneAction.hotkey : undefined}
631              onPress={press('refill')}
632            />
633            <Button key="flip" label={T().buttons.flip} onPress={press('flip')} />
634            <Button key="dex" label={T().buttons.dex} onPress={() => update($, SHOW_DEX_REF, v => !v)} />
635            <Button
636              key="band"
637              label={bandHidden ? T().buttons.showBand : T().buttons.hideBand}
638              onPress={async () => {
639                try {
640                  await toggleBand($)
641                } catch {
642                  // A button error must never affect the user
643                }
644              }}
645            />
646            {paneAction && paneAction.args !== 'refill' && paneAction.done !== true && (
647              <Button key="date-action" label={paneAction.paneLabel} hotkey={paneAction.hotkey || undefined} onPress={press(paneAction.args)} />
648            )}
649            {paneAction?.done === true && <Text key="date-done" dimColor> {paneAction.paneLabel}</Text>}
650          </Box>
651          {showDex && <Text>{dexHeader(save, dexTitle(t))}</Text>}
652          {showDex && (
653            <Box flexWrap="wrap">
654              {slots.map(id => {
655                const cap = dexCaption(save, id)
656                const owned = (save.dex[id] ?? 0) > 0
657                return (
658                  <Box key={`dex-${id}`} flexDirection="column" alignItems="center" marginRight={1}>
659                    {draw(dexArt(id, owned, e.surface), `dex-art-${id}`)}
660                    <Text key={`dex-name-${id}`} dimColor={!owned}>{cap.name}</Text>
661                    <Text key={`dex-count-${id}`} dimColor>{cap.count}</Text>
662                  </Box>
663                )
664              })}
665            </Box>
666          )}
667        </Box>
668      )
669    } catch {
670      return next(e)
671    }
672  })
673
674  on('command.run', { command: 'egg' }, async ($, e) => {
675    try {
676      // Someone typed /egg by hand, so someone is watching (on desktop the attach signal may come before the Mod loads and be missed)
677      if (!interactive && e.origin.kind !== 'plugin') await activate($)
678      if (!interactive) return { text: T().help }
679      const args = e.args.trim()
680      if (args === '') return { text: (await togglePane($)) ? T().paneOpened : T().paneClosed }
681      if (args === 'band') return { text: (await toggleBand($)) ? T().bandHidden : T().bandShown }
682      // Another load identity's save: compare, copy it over ours, or keep ours
683      if (args === 'sync yes') {
684        if (!(await askSync($))) return { text: T().sync.nothing }
685        return { text: [T().sync.confirm, T().sync.confirmUsage].join('\n') }
686      }
687      if (args === 'sync confirm') return { text: confirmReply(await confirmSync($)) }
688      if (args === 'sync cancel') {
689        await cancelSync($)
690        return { text: T().sync.cancelled }
691      }
692      if (args === 'sync no') return { text: (await declineSync($)) ? T().sync.declined : T().sync.nothing }
693      if (args === 'sync') {
694        // Always look again: the other save may have moved on since this session started
695        const offer = await findSyncOffer($, false)
696        if (!offer) return { text: T().sync.nothing }
697        const lines = compareLines(await $.store.get(STORE_KEY), offer.save, localNow)
698        return { text: [...lines, T().sync.usage].join('\n') }
699      }
700      // Dev preview: only switches the displayed sprite; never reads or changes the save
701      if (args === 'preview' || args.startsWith('preview ')) {
702        const current = (await $.state.get(PREVIEW_REF)).value ?? null
703        const chosen = nextPreview(current, args.slice('preview'.length))
704        if (chosen === undefined) return { text: fill(T().previewUsage, { total: String(PREVIEW_KEYS.length) }) }
705        await $.state.set(PREVIEW_REF, chosen)
706        if (chosen === null) return { text: T().previewOff }
707        if (!(await $.ui.panes()).some(p => p.id === PANE)) await $.ui.open({ id: PANE, title: T().title })
708        return { text: previewText(T().previewReply, chosen) }
709      }
710      const step = await mutate(ioOf($), (s, at) => onCommand(s, at, localNow(at), args, rng))
711      await armCountdown($, step.save).catch(() => undefined)
712      return { text: step.reply ?? '' }
713    } catch {
714      return { text: T().error }
715    }
716  })
717}
718
hooks/clock.ts 45 lines
1import type { DateKey } from '../types'
2
3export type LocalTime = { date: DateKey; year: number; month: number; day: number; hour: number; minute: number }
4export type FakeDate = { wallMs: number; keepTimeOfDay: boolean }
5export type ClockConfig = { offsetMinutes: (nowMs: number) => number; fake: FakeDate | null; loadedAt: number }
6
7const DAY_MS = 86_400_000
8const pad = (n: number) => String(n).padStart(2, '0')
9
10// TEA_EGG_FAKE_DATE: 'YYYY-MM-DD' or 'YYYY-MM-DDTHH:mm' (for development and testing)
11export function parseFakeDate(raw: string | undefined): FakeDate | null {
12  const m = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?$/.exec((raw ?? '').trim())
13  if (!m) return null
14  const [, y, mo, d, h, mi] = m
15  return {
16    wallMs: Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h ?? 0), Number(mi ?? 0)),
17    keepTimeOfDay: h === undefined,
18  }
19}
20
21// Always use the time zone of the Claude Code runtime itself (user's decision; not configurable)
22export function systemOffset(nowMs: number): number {
23  return -new Date(nowMs).getTimezoneOffset()
24}
25
26// "Wall time" is kept in the UTC fields so the runtime time zone doesn't convert it a second time
27export function localTime(nowMs: number, cfg: ClockConfig): LocalTime {
28  const realWall = nowMs + cfg.offsetMinutes(nowMs) * 60_000
29  let wall = realWall
30  if (cfg.fake) {
31    wall = cfg.fake.keepTimeOfDay
32      ? cfg.fake.wallMs + (((realWall % DAY_MS) + DAY_MS) % DAY_MS)
33      : cfg.fake.wallMs + (nowMs - cfg.loadedAt)
34  }
35  const d = new Date(wall)
36  const year = d.getUTCFullYear()
37  const month = d.getUTCMonth() + 1
38  const day = d.getUTCDate()
39  return { date: `${year}-${pad(month)}-${pad(day)}`, year, month, day, hour: d.getUTCHours(), minute: d.getUTCMinutes() }
40}
41
42export function daysBetween(a: DateKey, b: DateKey): number {
43  return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / DAY_MS)
44}
45
hooks/detect.ts 327 lines
1// Which of your commands this Mod looks at: only the text and success/failure of Bash / PowerShell commands,
2// used to tell "ran tests" and "ran a dangerous command". It only observes; it never blocks or modifies anything.
3// Only real execution counts: quoted strings, heredoc bodies and grep patterns are just "mentions" and don't count.
4
5export const OBSERVED_TOOLS = ['Bash', 'PowerShell'] as const
6
7// Test commands: the test runner must be the command word (first word) of a segment, or directly follow one of these launchers
8// - npm / pnpm / yarn [run] test (including test:unit and the like)
9// - npx jest, npx vitest
10// - vitest, jest, pytest, rspec, phpunit
11// - python -m pytest, python3 -m pytest, py -m pytest
12// - go / cargo / mvn / gradle / dotnet test
13// - gradlew test (including ./gradlew, .\gradlew, gradlew.bat)
14// - claude plugin test (including a full or quoted path to claude / claude.exe, or one held in a variable)
15export const TEST_COMMANDS: readonly RegExp[] = [
16  /^(?:\S*claude(?:\.exe)?|""|\$\{?[A-Za-z_][A-Za-z0-9_]*\}?)\s+plugin\s+test\b/i,
17  /^(?:npm|pnpm|yarn)\s+(?:run\s+)?test\b/,
18  /^npx\s+(?:jest|vitest)\b/,
19  /^(?:vitest|jest|pytest|rspec|phpunit)(?=\s|$)/,
20  /^(?:python3?|py)\s+-m\s+pytest\b/,
21  /^(?:go|cargo|mvn|gradle|dotnet)\s+test\b/,
22  /^(?:\.(?:\/|\\))?gradlew(?:\.bat)?\s+test\b/,
23]
24
25export function isTestCommand(cmd: string): boolean {
26  return segments(cmd).some(words => {
27    const line = words.join(' ')
28    return TEST_COMMANDS.some(re => re.test(line))
29  })
30}
31
32// Strip heredoc bodies: from the line after <<WORD up to a line containing only WORD
33function withoutHeredocs(cmd: string): string {
34  const out: string[] = []
35  let end: string | null = null
36  for (const line of cmd.split('\n')) {
37    if (end !== null) {
38      if (line.trim() === end) end = null
39      continue
40    }
41    out.push(line)
42    const m = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/.exec(line)
43    if (m) end = m[1]!
44  }
45  return out.join('\n')
46}
47
48// Strip quoted strings: merely "mentioning" a dangerous command (commit messages, grep patterns) doesn't count
49function unquoted(cmd: string): string {
50  return cmd.replace(/'[^']*'|"(?:\\.|[^"\\])*"/g, '""')
51}
52
53// Split on ; & | ( ) and newlines; drop a leading sudo and VAR=value
54function segments(cmd: string): string[][] {
55  return unquoted(withoutHeredocs(cmd))
56    .split(/[;&|()\n]+/)
57    .map(seg => seg.trim().split(/\s+/).filter(Boolean))
58    .map(words => {
59      let i = 0
60      while (i < words.length && (words[i] === 'sudo' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]!))) i++
61      return words.slice(i)
62    })
63    .filter(words => words.length > 0)
64}
65
66function shortFlags(words: string[]): string {
67  return words.filter(w => /^-[A-Za-z]+$/.test(w)).map(w => w.slice(1)).join('')
68}
69
70// Split into segments of words like segments(), but keep what's inside quotes (rm targets are often quoted paths).
71// $(...) stays inside its word. Unquoted backslash escapes the next character, as in bash.
72function quotedSegments(cmd: string): string[][] {
73  const segs: string[][] = []
74  let words: string[] = []
75  let word: string | null = null
76  const endWord = () => { if (word !== null) words.push(word); word = null }
77  const endSeg = () => { endWord(); if (words.length > 0) segs.push(words); words = [] }
78  const text = withoutHeredocs(cmd)
79  for (let i = 0; i < text.length; i++) {
80    const ch = text[i]!
81    if (ch === "'") {
82      const end = text.indexOf("'", i + 1)
83      const stop = end === -1 ? text.length : end
84      word = (word ?? '') + text.slice(i + 1, stop)
85      i = stop
86    } else if (ch === '"') {
87      let j = i + 1
88      let s = ''
89      while (j < text.length && text[j] !== '"') {
90        if (text[j] === '\\' && j + 1 < text.length && '"\\$`'.includes(text[j + 1]!)) j++
91        s += text[j]
92        j++
93      }
94      word = (word ?? '') + s
95      i = j
96    } else if (ch === '$' && text[i + 1] === '(') {
97      let depth = 0
98      let j = i + 1
99      for (; j < text.length; j++) {
100        if (text[j] === '(') depth++
101        else if (text[j] === ')' && --depth === 0) break
102      }
103      word = (word ?? '') + text.slice(i, j + 1)
104      i = j
105    } else if (ch === '\\' && i + 1 < text.length) {
106      word = (word ?? '') + text[++i]
107    } else if (';&|()\n'.includes(ch)) {
108      endSeg()
109    } else if (/\s/.test(ch)) {
110      endWord()
111    } else {
112      word = (word ?? '') + ch
113    }
114  }
115  endSeg()
116  return segs
117}
118
119// rm -rf only counts when a target wipes a whole tree from the top: the root, the home folder, the current or
120// parent folder, or everything in the current folder. Targets are matched as written (quotes removed):
121// - /  /*  and a Windows drive root (C:  C:/  C:\  C:/*), the same as /
122// - ~  ~/  ~/*  $HOME  ${HOME}  $HOME/  $HOME/*
123// - .  ./  ./*  ..  ../  *
124// Any other path (node_modules, dist, ./build, src/x, $SOME_VAR/x ...) does not count.
125
126const ROOT_TARGETS = new Set([
127  '/', '/*',
128  '~', '~/', '~/*', '$HOME', '${HOME}', '$HOME/', '${HOME}/', '$HOME/*', '${HOME}/*',
129  '.', './', './*', '..', '../', '*',
130])
131const DRIVE_ROOT = /^[A-Za-z]:[\\/]*\*?$/
132
133function isRootTarget(word: string): boolean {
134  return ROOT_TARGETS.has(word) || DRIVE_ROOT.test(word)
135}
136
137const isRedirect = (w: string) => /^\d*[<>]/.test(w)
138
139function wipesRoot(cmd: string): boolean {
140  for (const segment of quotedSegments(cmd)) {
141    let i = 0
142    while (i < segment.length && (segment[i] === 'sudo' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(segment[i]!))) i++
143    const words = segment.slice(i).filter(w => !isRedirect(w))
144    if (words[0] !== 'rm') continue
145    const flags = shortFlags(words)
146    const recursive = /[rR]/.test(flags) || words.includes('--recursive')
147    const force = flags.includes('f') || words.includes('--force')
148    if (!recursive || !force) continue
149    if (words.slice(1).some(w => !w.startsWith('-') && isRootTarget(w))) return true
150  }
151  return false
152}
153
154// Caution level: rm -rf of an ordinary path counts when some target lies outside a temp location. Temp locations:
155// - a path segment named tmp / temp / scratchpad with something below it (the folder itself still counts)
156// - anything under node_modules / bin / obj / build / .superpowers (including the folder itself), unless it sits
157//   under a system folder such as /usr or C:/Program Files
158// Paths are resolved with VAR=value / export / cd from earlier in the same command; $TEMP / $TMP / $TMPDIR and
159// $(mktemp ...) count as temp. Anything we can't resolve (unknown variables, ~, $(...) other than mktemp) counts.
160
161const TEMP_VARS: Record<string, string> = { TEMP: '/tmp', TMP: '/tmp', TMPDIR: '/tmp', LOCALAPPDATA: '/AppData/Local' }
162
163type Env = Map<string, string | null>
164
165function expand(word: string, env: Env): string | null {
166  if (/^\$\(\s*mktemp\b[^)]*\)$/.test(word)) return '/tmp/mktemp'
167  if (word.includes('$(') || word.includes('`') || word.startsWith('~')) return null
168  let unresolved = false
169  const out = word.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_, a: string | undefined, b: string | undefined) => {
170    const name = (a ?? b)!
171    const value = env.has(name) ? env.get(name)! : TEMP_VARS[name] ?? null
172    if (value === null) unresolved = true
173    return value ?? ''
174  })
175  return unresolved ? null : out
176}
177
178const isAbsolute = (p: string) => /^(?:\/|[A-Za-z]:)/.test(p)
179
180function resolvePath(word: string, env: Env, cwd: string | null): string | null {
181  const p = expand(word, env)
182  if (p === null) return null
183  const path = p.replace(/\\/g, '/')
184  if (isAbsolute(path)) return path
185  return cwd === null ? path : `${cwd}/${path}`
186}
187
188const OUTPUT_DIRS = new Set(['node_modules', 'bin', 'obj', 'build', '.superpowers'])
189const SYSTEM_ROOT = /^(?:usr|bin|sbin|etc|opt|lib|lib64|var|boot|system|library|windows|program files|program files \(x86\)|programdata)$/i
190
191// /usr/bin, C:/Program Files/App/bin and the like are system folders, not build output
192function underSystemRoot(path: string, parts: string[]): boolean {
193  if (!isAbsolute(path)) return false
194  const drive = /^[A-Za-z]:$/.test(parts[0]!) || (path.startsWith('/') && /^[A-Za-z]$/.test(parts[0]!))
195  const first = drive ? parts[1] : parts[0]
196  return first !== undefined && SYSTEM_ROOT.test(first)
197}
198
199function isTempPath(path: string): boolean {
200  const parts = path.split('/').filter(part => part !== '' && part !== '.')
201  if (parts.includes('..')) return false
202  if (parts.some(part => OUTPUT_DIRS.has(part)) && !underSystemRoot(path, parts)) return true
203  const i = parts.findIndex(part => /^(?:tmp|temp|scratchpad)$/i.test(part))
204  return i !== -1 && i < parts.length - 1
205}
206
207function riskyRm(cmd: string): boolean {
208  const env: Env = new Map()
209  let cwd: string | null = null
210  for (const segment of quotedSegments(cmd)) {
211    let words = segment
212    if (words[0] === 'export') words = words.slice(1)
213    let i = 0
214    while (i < words.length && (words[i] === 'sudo' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]!))) {
215      const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(words[i]!)
216      if (m) env.set(m[1]!, expand(m[2]!, env))
217      i++
218    }
219    words = words.slice(i).filter(w => !isRedirect(w))
220    const [head, ...args] = words
221    if (head === 'cd') {
222      const dest = args[0]
223      cwd = dest === undefined ? null : resolvePath(dest, env, cwd)
224      continue
225    }
226    if (head !== 'rm') continue
227    const flags = shortFlags(words)
228    const recursive = /[rR]/.test(flags) || words.includes('--recursive')
229    const force = flags.includes('f') || words.includes('--force')
230    if (!recursive || !force) continue
231    const targets = args.filter(w => !w.startsWith('-'))
232    if (targets.length === 0) continue
233    for (const t of targets) {
234      const path = resolvePath(t, env, cwd)
235      if (path === null || !isTempPath(path)) return true
236    }
237  }
238  return false
239}
240
241// Caution-level commands: everyday but risky. Each one is counted; enough of them during one egg also cracks it
242// (how many is part of the harvest rules)
243// - rm -rf of an ordinary path outside temp locations (see riskyRm)
244// - git reset --hard
245// - git clean -fd (not with -n / --dry-run)
246// - git push --force-with-lease
247export function cautionKeyword(cmd: string): string | null {
248  if (dangerKeyword(cmd) !== null) return null
249  for (const words of segments(cmd)) {
250    const [head, sub] = words
251    const flags = shortFlags(words)
252    if (head === 'rm') {
253      const recursive = /[rR]/.test(flags) || words.includes('--recursive')
254      const force = flags.includes('f') || words.includes('--force')
255      if (recursive && force && riskyRm(cmd)) return 'rm -rf'
256    }
257    if (head === 'git' && sub === 'reset' && words.includes('--hard')) return 'git reset --hard'
258    if (head === 'git' && sub === 'clean' && flags.includes('f') && flags.includes('d') && !flags.includes('n') && !words.includes('--dry-run')) return 'git clean -fd'
259    if (head === 'git' && sub === 'push' && words.some(w => w === '--force-with-lease' || w.startsWith('--force-with-lease='))) {
260      return 'git push --force-with-lease'
261    }
262  }
263  return null
264}
265
266// Dangerous commands we watch for:
267// - rm -rf (recursive + forced delete) of a root-like target (see wipesRoot)
268// - git push --force / -f (force push); --force-with-lease is the safe form and does not count
269// git reset --hard, git clean -fd and other everyday-but-risky commands are caution level (see cautionKeyword)
270// - chmod -R 777
271// - SQL DROP TABLE / DROP DATABASE / TRUNCATE: only when the command word of some segment is an SQL client
272//   (psql, mysql, mariadb, sqlite3, sqlcmd, duckdb, sqlplus, clickhouse-client, Invoke-Sqlcmd)
273
274const SQL_CLIENTS = new Set([
275  'psql', 'mysql', 'mariadb', 'sqlite3', 'sqlcmd', 'duckdb', 'sqlplus', 'clickhouse-client', 'invoke-sqlcmd',
276])
277
278const SQL: readonly [RegExp, string][] = [
279  [/\bDROP\s+TABLE\b/i, 'DROP TABLE'],
280  [/\bDROP\s+DATABASE\b/i, 'DROP DATABASE'],
281  [/\bTRUNCATE\s+TABLE\s+[A-Za-z_]/i, 'TRUNCATE'],
282  [/\bTRUNCATE\s+[A-Za-z_][A-Za-z0-9_]*\b/, 'TRUNCATE'],
283]
284
285const isSqlClient = (word: string) => SQL_CLIENTS.has(word.toLowerCase().replace(/\.exe$/, ''))
286
287export function dangerKeyword(cmd: string): string | null {
288  const segs = segments(cmd)
289  for (const words of segs) {
290    const [head, sub] = words
291    const flags = shortFlags(words)
292    if (head === 'rm') {
293      const recursive = /[rR]/.test(flags) || words.includes('--recursive')
294      const force = flags.includes('f') || words.includes('--force')
295      if (recursive && force && wipesRoot(cmd)) return 'rm -rf'
296    }
297    if (head === 'git' && sub === 'push') {
298      if (words.includes('--force') || flags.includes('f')) {
299        return 'git push --force'
300      }
301    }
302    if (head === 'chmod' && (flags.includes('R') || words.includes('--recursive')) && words.some(w => w === '777' || w === '0777')) {
303      return 'chmod -R 777'
304    }
305  }
306  // SQL usually sits inside quotes or a heredoc, so when an SQL client is present we match against the raw text
307  if (segs.some(words => isSqlClient(words[0]!))) {
308    for (const [re, keyword] of SQL) if (re.test(cmd)) return keyword
309  }
310  return null
311}
312
313export type Observation = { failed: boolean; test: 'pass' | 'fail' | null; danger: string | null; caution: string | null }
314
315export function observe(tool: string, command: string, ran: { deny?: string; isError?: boolean }): Observation | null {
316  if (ran.deny !== undefined) return null
317  const failed = ran.isError === true
318  const isShell = (OBSERVED_TOOLS as readonly string[]).includes(tool)
319  const cmd = typeof command === 'string' ? command : ''
320  const test = isShell && isTestCommand(cmd) ? (failed ? 'fail' : 'pass') : null
321  // Dangerous commands only count when they actually ran successfully (denied or failed calls don't)
322  const danger = isShell && !failed ? dangerKeyword(cmd) : null
323  const caution = isShell && !failed ? cautionKeyword(cmd) : null
324  if (!failed && test === null && danger === null && caution === null) return null
325  return { failed, test, danger, caution }
326}
327
hooks/dates.ts 435 lines
1// The special dates after the first (datemode.ts). What each kind does is here; which day, what it gives and every
2// line are spoiler data (decodeSpoilers().dates).
3//  - timed: the egg is paused all day. The first prompt, then the first prompt after each rest, starts an ask: pressing
4//    the button in time counts one. Enough of them by the end of the day give one prize, fewer the other (settled on
5//    the first open after)
6//  - grant: the day's first prompt hands over a prize; the egg goes on as usual
7//  - reply: for someone who got `needs` that year; press the button on the day for the prize. Miss it and the egg is
8//    cross on the first day opened after (faces and lines only; the egg goes on as usual)
9// Days missed are made up on the first open after (timed and grant), for saves made before that day.
10import type { DateKey, GrantEntry, ReplyEntry, Save, TimedEntry } from '../types'
11import type { LocalTime } from './clock'
12import type { Effect, Step } from './engine'
13import type { BandLook, DateSpec, GrantDate, ReplyDate, TimedDate } from './spoiler-types'
14import { decodeSpoilers } from './spoilers'
15import { T, fill, pick } from './text'
16
17const pad = (n: number) => String(n).padStart(2, '0')
18const dayOf = (year: number, d: { month: number; day: number }): DateKey => `${year}-${pad(d.month)}-${pad(d.day)}`
19const keyOf = (id: string, year: number) => `${id}:${year}`
20const isOn = (d: DateSpec, t: LocalTime) => d.month === t.month && d.day === t.day
21const toast = (text: string): Effect => ({ kind: 'toast', text })
22const begin = (prev: Save): Step => ({ save: structuredClone(prev), effects: [] })
23
24function all<K extends DateSpec['kind']>(kind: K): [string, Extract<DateSpec, { kind: K }>][] {
25  return Object.entries(decodeSpoilers().dates).filter((e): e is [string, Extract<DateSpec, { kind: K }>] => e[1].kind === kind)
26}
27
28// The date's most recent day strictly before today
29function lastBefore(d: DateSpec, t: LocalTime): { year: number; date: DateKey } {
30  const thisYear = dayOf(t.year, d)
31  return thisYear < t.date ? { year: t.year, date: thisYear } : { year: t.year - 1, date: dayOf(t.year - 1, d) }
32}
33
34// Add a prize to the dex; the text gets the "new in the dex" mark the first time
35function award(s: Save, id: string, text: string): string {
36  const isNew = (s.dex[id] ?? 0) === 0
37  s.dex[id] = (s.dex[id] ?? 0) + 1
38  return isNew ? text + T().newDex : text
39}
40
41const surfaced = (lines: { desktop: string; terminal: string }, terminal: boolean) => (terminal ? lines.terminal : lines.desktop)
42
43// ---- timed ----
44
45type Timed = { id: string; spec: TimedDate; key: string; entry: TimedEntry | undefined }
46
47// The countdown under way, whatever the date (one started just before midnight runs on into the next day)
48function running(s: Save): Timed | null {
49  for (const [id, spec] of all('timed')) {
50    for (const [key, entry] of Object.entries(s.dateMode)) {
51      if (key.startsWith(`${id}:`) && (entry as TimedEntry).phase === 'run') return { id, spec, key, entry: entry as TimedEntry }
52    }
53  }
54  return null
55}
56
57// The timed date to show now: a countdown under way, or today's
58export function timedNow(s: Save, t: LocalTime): Timed | null {
59  const run = running(s)
60  if (run) return run
61  for (const [id, spec] of all('timed')) {
62    if (!isOn(spec, t)) continue
63    const key = keyOf(id, t.year)
64    return { id, spec, key, entry: s.dateMode[key] as TimedEntry | undefined }
65  }
66  return null
67}
68
69export function remainingMs(spec: TimedDate, entry: TimedEntry, now: number): number {
70  return Math.max(0, spec.seconds * 1000 - (now - (entry.startedAt ?? now)))
71}
72
73// TEA_EGG_TEST_REST (seconds): a short rest between asks, to try the day out without waiting
74let restOverride: number | null = null
75export function setRestOverride(ms: number | null): void {
76  restOverride = ms
77}
78
79// The rest after an ask that ended at `at`, drawn in restMs. Seeded by `at` (mulberry32), so the timers that end an
80// ask need no rng and the same ask always draws the same rest
81function restAfter(spec: TimedDate, at: number): number {
82  if (restOverride !== null) return restOverride
83  let x = ((at % 4294967296) + 0x6d2b79f5) >>> 0
84  x = Math.imul(x ^ (x >>> 15), x | 1)
85  x ^= x + Math.imul(x ^ (x >>> 7), x | 61)
86  const unit = ((x ^ (x >>> 14)) >>> 0) / 4294967296
87  const [min, max] = spec.restMs
88  return min + Math.floor(unit * (max - min))
89}
90
91const tally = (spec: TimedDate, line: string, n: number) => fill(line, { n: String(n), need: String(spec.need) })
92
93// An ask is over (answered or not): rest until nextAt
94function endAsk(spec: TimedDate, entry: TimedEntry, at: number, answered: boolean): void {
95  if (answered) entry.got = (entry.got ?? 0) + 1
96  entry.phase = 'rest'
97  entry.nextAt = at + restAfter(spec, at)
98}
99
100// End an ask that ran out, or warn once it is nearly over. Runs on every event (and on the ask's timers)
101function checkTimed(step: Step, now: number): void {
102  const run = running(step.save)
103  if (!run || !run.entry) return
104  const { spec, entry } = run
105  const left = remainingMs(spec, entry, now)
106  if (left <= 0) {
107    endAsk(spec, entry, (entry.startedAt ?? now) + spec.seconds * 1000, false)
108    step.effects.push(toast(tally(spec, spec.lines.miss, entry.got ?? 0)))
109  } else if (left <= spec.warnSeconds * 1000 && !entry.warned) {
110    entry.warned = true
111    step.effects.push(toast(surfaced(spec.lines.warn, entry.terminal === true)))
112  }
113}
114
115export function timedTick(prev: Save, now: number): Step {
116  const step = begin(prev)
117  checkTimed(step, now)
118  return step
119}
120
121// Opened on the day: remember it (an idle day is made up like a missed one if no prompt ever comes)
122export function timedSeen(prev: Save, t: LocalTime): Step {
123  const step = begin(prev)
124  const day = timedNow(step.save, t)
125  if (day && !day.entry && isOn(day.spec, t)) step.save.dateMode[day.key] = { phase: 'idle' }
126  return step
127}
128
129// The danger line instead of cracking the paused egg, at most once per dangerGapMs
130export function timedDanger(prev: Save, now: number, t: LocalTime): Step {
131  const step = begin(prev)
132  const day = timedNow(step.save, t)
133  if (!day) return step
134  const entry = (step.save.dateMode[day.key] ??= { phase: 'idle' }) as TimedEntry
135  if (entry.lastDanger !== undefined && now - entry.lastDanger < day.spec.dangerGapMs) return step
136  entry.lastDanger = now
137  step.effects.push(toast(day.spec.lines.danger))
138  return step
139}
140
141// The button (or /egg refill): during an ask it counts one; otherwise a line for each case. null when no timed date
142// is showing
143export function timedPress(prev: Save, now: number, t: LocalTime): Step | null {
144  const step = begin(prev)
145  checkTimed(step, now)
146  const day = timedNow(step.save, t)
147  if (!day) return null
148  const { spec, entry } = day
149  if (entry?.phase === 'run') {
150    endAsk(spec, entry, now, true)
151    step.reply = tally(spec, spec.lines.got, entry.got ?? 0)
152  } else if (entry?.phase === 'rest') step.reply = spec.replies.resting
153  else if (entry?.phase === 'won') step.reply = spec.replies.afterWon
154  else if (entry?.phase === 'lost') step.reply = spec.replies.afterLost
155  else step.reply = spec.replies.early
156  return step
157}
158
159export function timedFlipReply(s: Save, t: LocalTime): string | null {
160  return timedNow(s, t)?.spec.replies.flip ?? null
161}
162
163// ---- the day's first prompt ----
164
165// Starts today's first ask (or the next, once the rest is over), hands over today's grant, opens today's reply.
166// terminal: a terminal is attached
167export function datesPrompt(prev: Save, now: number, t: LocalTime, terminal: boolean): Step {
168  const step = begin(prev)
169  const s = step.save
170  for (const [id, spec] of all('timed')) {
171    const key = keyOf(id, t.year)
172    const entry = s.dateMode[key] as TimedEntry | undefined
173    if (!isOn(spec, t)) continue
174    if (!entry || entry.phase === 'idle') {
175      s.dateMode[key] = { phase: 'run', startedAt: now, terminal, from: 'live', got: 0, asks: 1, warned: false }
176    } else if (entry.phase === 'rest' && now >= (entry.nextAt ?? 0)) {
177      Object.assign(entry, { phase: 'run', startedAt: now, terminal, warned: false, asks: (entry.asks ?? 0) + 1 })
178    } else continue
179    step.effects.push(toast(surfaced(spec.lines.start, terminal)))
180  }
181  for (const [id, spec] of all('grant')) {
182    const key = keyOf(id, t.year)
183    if (!isOn(spec, t) || s.dateMode[key]) continue
184    s.dateMode[key] = { got: true, date: t.date, from: 'live' }
185    step.effects.push(toast(award(s, spec.prize, spec.lines.got)))
186  }
187  for (const [id, spec] of all('reply')) {
188    const key = keyOf(id, t.year)
189    if (!isOn(spec, t) || s.dateMode[key] || !eligible(s, spec, t.year)) continue
190    s.dateMode[key] = { phase: 'open' }
191    step.effects.push(toast(surfaced(spec.lines.open, terminal)))
192  }
193  return step
194}
195
196// ---- catching up: on opening, on every turn and tick ----
197
198// Settle what happened while away: a countdown that ran out, days missed (made up oldest first), the end of a
199// timed day, and a reply day that was missed or a cross day that is over
200export function datesCatchUp(prev: Save, now: number, t: LocalTime): Step {
201  const step = begin(prev)
202  const s = step.save
203  checkTimed(step, now)
204  const since = s.installedOn
205  const missed: { date: DateKey; run: () => void }[] = []
206  for (const [id, spec] of [...all('timed'), ...all('grant')] as [string, TimedDate | GrantDate][]) {
207    const last = lastBefore(spec, t)
208    // Only for saves made before that day: someone who installed later never had the chance
209    if (since === undefined || since >= last.date) continue
210    const key = keyOf(id, last.year)
211    const entry = s.dateMode[key]
212    if (spec.kind === 'timed' && (!entry || (entry as TimedEntry).phase === 'idle')) {
213      missed.push({
214        date: last.date,
215        run: () => {
216          s.dateMode[key] = { phase: 'lost', from: 'missed', closed: true }
217          step.effects.push(toast(award(s, spec.prizes.lost, spec.lines.makeup)))
218        },
219      })
220    }
221    if (spec.kind === 'grant' && !entry) {
222      missed.push({
223        date: last.date,
224        run: () => {
225          s.dateMode[key] = { got: true, date: t.date, from: 'missed' }
226          step.effects.push(toast(award(s, spec.prize, spec.lines.makeup)))
227        },
228      })
229    }
230  }
231  for (const m of missed.sort((a, b) => a.date.localeCompare(b.date))) m.run()
232  // The first open after a timed day that was played: settle it by the count (once its last ask is over), back to the
233  // usual egg. A day settled the old way (a single countdown) only says it is over
234  for (const [id, spec] of all('timed')) {
235    const entry = s.dateMode[keyOf(id, lastBefore(spec, t).year)] as TimedEntry | undefined
236    if (entry?.phase === 'rest') {
237      const n = entry.got ?? 0
238      const phase = n >= spec.need ? 'won' : 'lost'
239      Object.assign(entry, { phase, closed: true })
240      step.effects.push(toast(award(s, spec.prizes[phase], fill(spec.lines[phase], { n: String(n) }))))
241    } else if (entry && entry.from === 'live' && (entry.phase === 'won' || entry.phase === 'lost') && !entry.closed) {
242      entry.closed = true
243      step.effects.push(toast(spec.lines.over))
244    }
245  }
246  for (const [id, spec] of all('reply')) replyCatchUp(step, id, spec, t)
247  return step
248}
249
250// ---- reply ----
251
252// Got `needs` that year, on or before this date's day (made up later doesn't count: there was no chance to answer)
253function eligible(s: Save, spec: ReplyDate, year: number): boolean {
254  const got = s.dateMode[keyOf(spec.needs, year)] as GrantEntry | undefined
255  return got?.got === true && got.date <= dayOf(year, spec)
256}
257
258function replyCatchUp(step: Step, id: string, spec: ReplyDate, t: LocalTime): void {
259  const s = step.save
260  const last = lastBefore(spec, t)
261  // A cross day that is over (the year before too, for someone back after a long time)
262  for (const year of [last.year - 1, last.year]) {
263    const entry = s.dateMode[keyOf(id, year)] as ReplyEntry | undefined
264    if (entry?.phase === 'late' && entry.lateDate !== undefined && entry.lateDate < t.date) {
265      entry.phase = 'over'
266      step.effects.push(toast(spec.lines.over))
267    }
268  }
269  // The day went by unanswered (or unopened): cross today, the first day opened after it
270  const key = keyOf(id, last.year)
271  const entry = s.dateMode[key] as ReplyEntry | undefined
272  if ((!entry || entry.phase === 'open') && eligible(s, spec, last.year)) {
273    s.dateMode[key] = { phase: 'late', lateDate: t.date }
274    step.effects.push(toast(spec.lines.late))
275  }
276}
277
278type Reply = { id: string; spec: ReplyDate; key: string; entry: ReplyEntry }
279
280// Today's reply entry: on the day itself, or the day the egg is cross
281export function replyNow(s: Save, t: LocalTime): Reply | null {
282  for (const [id, spec] of all('reply')) {
283    if (isOn(spec, t)) {
284      const key = keyOf(id, t.year)
285      const entry = s.dateMode[key] as ReplyEntry | undefined
286      if (entry) return { id, spec, key, entry }
287    }
288    for (const [key, entry] of Object.entries(s.dateMode)) {
289      const r = entry as ReplyEntry
290      if (key.startsWith(`${id}:`) && (r.phase === 'late' || r.phase === 'eased') && r.lateDate === t.date) {
291        return { id, spec, key, entry: r }
292      }
293    }
294  }
295  return null
296}
297
298export const isCross = (s: Save, t: LocalTime) => replyNow(s, t)?.entry.phase === 'late'
299
300// /egg <command> or the button: answered on the day gives the prize; while cross it eases. null: nothing to answer
301export function replyPress(prev: Save, t: LocalTime): Step | null {
302  const step = begin(prev)
303  const r = replyNow(step.save, t)
304  if (!r) return null
305  if (r.entry.phase === 'open') {
306    r.entry.phase = 'done'
307    step.reply = award(step.save, r.spec.prize, r.spec.lines.done)
308  } else if (r.entry.phase === 'late') {
309    r.entry.phase = 'eased'
310    step.reply = r.spec.lines.eased
311  } else return null
312  return step
313}
314
315export function replyCommand(): string[] {
316  return all('reply').map(([, spec]) => spec.command)
317}
318
319// While cross: one of its lines when a turn finishes, at most once per lineGapMs
320export function crossLine(prev: Save, now: number, t: LocalTime, rng: () => number): Step {
321  const step = begin(prev)
322  const r = replyNow(step.save, t)
323  if (r?.entry.phase !== 'late') return step
324  if (r.entry.lastLine !== undefined && now - r.entry.lastLine < r.spec.lineGapMs) return step
325  r.entry.lastLine = now
326  step.effects.push(toast(pick(r.spec.lines.lateLines, rng)))
327  return step
328}
329
330// While cross, refill and flip still work; only the reply changes
331export function crossReply(s: Save, t: LocalTime, what: 'refill' | 'flip'): string | null {
332  const r = replyNow(s, t)
333  if (r?.entry.phase !== 'late') return null
334  return what === 'refill' ? r.spec.lines.lateRefill : r.spec.lines.lateFlip
335}
336
337// The egg cracked while cross: the new egg holds no grudge
338export function endCross(prev: Save, t: LocalTime): Step {
339  const step = begin(prev)
340  const r = replyNow(step.save, t)
341  if (r?.entry.phase === 'late') r.entry.phase = 'over'
342  return step
343}
344
345// ---- what the band and the pane show ----
346
347// The timed date's band, instead of the egg's: an ask counting down, a rest between asks, or how a day settled the
348// old way ended (until the day is over). The timer's icon and its digits are separate, and the count has its mark
349// only between asks: what redraws every second stays emoji-free (view.ts)
350export type TimedBand = {
351  look: BandLook
352  timer: { icon: string; digits: string } | null
353  count: string | null
354  mark: string | null
355  warn: boolean
356}
357
358export function timedBand(s: Save, t: LocalTime, now: number): TimedBand | null {
359  const day = timedNow(s, t)
360  if (!day?.entry) return null
361  const { spec, entry } = day
362  const b = spec.band
363  const count = tally(spec, b.count, entry.got ?? 0)
364  if (entry.phase === 'run') {
365    const left = remainingMs(spec, entry, now)
366    const warn = left <= spec.warnSeconds * 1000
367    const secs = Math.ceil(left / 1000)
368    return {
369      look: { icon: b.icon, face: warn ? b.warnFace : b.face, text: warn ? b.warnAsk : b.ask },
370      timer: { icon: b.timer, digits: `${Math.floor(secs / 60)}:${pad(secs % 60)}` },
371      count,
372      mark: null,
373      warn,
374    }
375  }
376  if (entry.phase === 'rest' && isOn(spec, t)) {
377    return { look: { icon: b.icon, face: b.face, text: b.rest }, timer: null, count, mark: b.mark, warn: false }
378  }
379  if ((entry.phase === 'won' || entry.phase === 'lost') && isOn(spec, t)) {
380    return { look: b[entry.phase], timer: null, count: null, mark: null, warn: false }
381  }
382  return null
383}
384
385// The egg's band with the day's icon, face and hint: a grant got today, or the reply day / cross day
386export function dateLook(s: Save, t: LocalTime): BandLook | null {
387  const r = replyNow(s, t)
388  if (r && r.entry.phase !== 'over') return r.spec.band[r.entry.phase]
389  for (const [id, spec] of all('grant')) {
390    const got = s.dateMode[keyOf(id, t.year)] as GrantEntry | undefined
391    if (isOn(spec, t) && got?.from === 'live') return spec.band
392  }
393  return null
394}
395
396// The button on the band and the pane, and what it runs (as /egg <args>)
397export type DateAction = { label: string; paneLabel: string; hotkey: string; args: string; done?: boolean }
398
399export function dateAction(s: Save, t: LocalTime): DateAction | null {
400  const day = timedNow(s, t)
401  if (day?.entry?.phase === 'run') return { label: day.spec.button, paneLabel: day.spec.paneButton, hotkey: day.spec.hotkey, args: 'refill' }
402  const r = replyNow(s, t)
403  if (r && (r.entry.phase === 'open' || r.entry.phase === 'late')) {
404    return { label: r.spec.button, paneLabel: r.spec.paneButton, hotkey: r.spec.hotkey, args: r.spec.command }
405  }
406  if (r?.entry.phase === 'done') return { label: r.spec.doneButton, paneLabel: r.spec.doneButton, hotkey: '', args: '', done: true }
407  return null
408}
409
410// The pane's Refill button on a timed day (any phase): it presses the day's button instead
411export function paneRefillLabel(s: Save, t: LocalTime): string | null {
412  return timedNow(s, t)?.spec.paneButton ?? null
413}
414
415// Egg layers that replace the usual picture: the costume all through a timed day, the cross face, the done face.
416// prize: show that dex icon instead (how a timed day ended)
417export type DateArt = { base?: string; face?: string; steam?: boolean; palette?: string; prize?: string }
418
419export function dateArt(s: Save, t: LocalTime, now: number): DateArt | null {
420  const day = timedNow(s, t)
421  if (day?.entry?.phase === 'run') {
422    const warn = remainingMs(day.spec, day.entry, now) <= day.spec.warnSeconds * 1000
423    return { base: day.spec.art.base, face: warn ? day.spec.art.warnFace : day.spec.art.face, steam: false }
424  }
425  if (day?.entry?.phase === 'rest' && isOn(day.spec, t)) return { base: day.spec.art.base, face: day.spec.art.face, steam: false }
426  if (day?.entry && (day.entry.phase === 'won' || day.entry.phase === 'lost') && isOn(day.spec, t)) {
427    return { prize: day.spec.prizes[day.entry.phase] }
428  }
429  const r = replyNow(s, t)
430  if (r?.entry.phase === 'late') return { face: r.spec.art.late, steam: false }
431  if (r?.entry.phase === 'done') return { face: 'face_done' }
432  return null
433}
434
435
hooks/flow.ts 178 lines
1import type { Save } from '../types'
2import type { LocalTime } from './clock'
3import {
4  crossLine,
5  crossReply,
6  datesCatchUp,
7  datesPrompt,
8  endCross,
9  isCross,
10  paneRefillLabel,
11  replyCommand,
12  replyPress,
13  timedDanger,
14  timedFlipReply,
15  timedNow,
16  timedPress,
17  timedSeen,
18  timedTick,
19} from './dates'
20import {
21  humanCare,
22  humanClock,
23  humansDone,
24  humanToolFailed,
25  isPausedDay,
26  isSpecialDay,
27  specialEvent,
28  specialMakeup,
29  specialPrompt,
30  specialSeen,
31  specialTurn,
32  yearOf,
33} from './datemode'
34import type { Observation } from './detect'
35import { RULES, addActiveDay, flip, pauseClocks, refill, testObserved, tick, toolFailed, turnDone, type Step } from './engine'
36import { caution, crack, dexText, settle } from './rules'
37import { decodeSpoilers } from './spoilers'
38import { T, fill } from './text'
39
40const NAME_MAX = 12
41
42// Run the second step on the first step's result: keep the second step's save and accumulate the effects
43function then(first: Step, second: (s: Save) => Step): Step {
44  const next = second(first.save)
45  return { save: next.save, effects: [...first.effects, ...next.effects], reply: next.reply ?? first.reply }
46}
47
48export function dexTitle(t: LocalTime): string {
49  return isSpecialDay(t) ? decodeSpoilers().dateMode.dexTitle : T().dexTitle
50}
51
52// A timed special date pauses the egg like the first one does (dates.ts)
53const isTimedDay = (s: Save, t: LocalTime) => isPausedDay(t) && !isSpecialDay(t) && timedNow(s, t) !== null
54
55export function onSessionOpen(prev: Save, now: number, t: LocalTime, isNewSession: boolean): Step {
56  const save = structuredClone(prev)
57  const step: Step = { save, effects: [] }
58  if (!save.welcomed) {
59    save.welcomed = true
60    step.effects.push({ kind: 'toast', text: T().welcome })
61  }
62  // A save made before this version counts as made today: days missed before it are not made up
63  save.installedOn ??= t.date
64  save.clocks.lastTickAt = now // no catching up on time while closed
65  save.clocks.bucketStart = now
66  save.clocks.bucketActive = false
67  let made = then(step, s => specialMakeup(s, t))
68  made = then(made, s => datesCatchUp(s, now, t))
69  if (isSpecialDay(t)) return then(made, s => specialSeen(s, t))
70  if (isPausedDay(t)) return then(made, s => timedSeen(s, t))
71  // The session itself is counted on its first prompt (usage.ts): opening one without using it doesn't count
72  if (isNewSession) addActiveDay(made.save, t)
73  return made
74}
75
76// The person sent a prompt: the day's countdown, grant or reply may start. terminal: a terminal is attached
77export function onPrompt(prev: Save, now: number, t: LocalTime, terminal: boolean, rng: () => number = Math.random): Step {
78  if (isSpecialDay(t)) return specialPrompt(prev, now, t, rng)
79  const caught = datesCatchUp(prev, now, t)
80  return then(caught, s => datesPrompt(s, now, t, terminal))
81}
82
83// The first special date pauses the egg's clocks; the human's mood goes down over the same time instead
84function pauseForHuman(prev: Save, now: number, t: LocalTime): Step {
85  const save = structuredClone(prev)
86  const elapsed = Math.max(0, Math.min(now - save.clocks.lastTickAt, RULES.maxTickGapMs))
87  humanClock(save, t, elapsed, RULES.moodStepMs, RULES.moodStep)
88  return pauseClocks(save, now)
89}
90
91export function onTick(prev: Save, now: number, t: LocalTime, rng: () => number): Step {
92  if (isSpecialDay(t)) return then(pauseForHuman(prev, now, t), s => specialSeen(s, t))
93  if (isPausedDay(t)) return then(pauseClocks(prev, now), s => timedTick(s, now))
94  return then(settle(tick(prev, now, t), now, rng), s => timedTick(s, now))
95}
96
97export function onTurn(prev: Save, now: number, t: LocalTime, rng: () => number): Step {
98  if (isSpecialDay(t)) return then(pauseForHuman(prev, now, t), s => specialTurn(s, now, t, rng))
99  const caught = then(specialMakeup(prev, t), s => datesCatchUp(s, now, t))
100  if (isPausedDay(t)) return then(caught, s => pauseClocks(s, now))
101  const done = settle(then(caught, s => turnDone(s, now, t, rng)), now, rng)
102  return then(done, s => crossLine(s, now, t, rng))
103}
104
105export function onObserved(prev: Save, now: number, t: LocalTime, obs: Observation, rng: () => number): Step {
106  if (isSpecialDay(t)) {
107    const kind = obs.danger !== null ? 'danger' : obs.test === 'fail' ? 'testFail' : obs.test === 'pass' ? 'testPass' : null
108    const step: Step = kind === null ? { save: prev, effects: [] } : specialEvent(prev, now, t, kind, rng)
109    return obs.failed ? then(step, s => humanToolFailed(s, t)) : step
110  }
111  if (isTimedDay(prev, t)) return obs.danger !== null ? timedDanger(prev, now, t) : { save: prev, effects: [] }
112  if (obs.danger !== null) {
113    // A new egg holds no grudge: cracking ends a cross day
114    const cross = isCross(prev, t)
115    const cracked = crack(prev, obs.danger, now, rng)
116    return cross ? then(cracked, s => endCross(s, t)) : cracked
117  }
118  let step: Step = { save: prev, effects: [] }
119  if (obs.test !== null) step = then(step, s => testObserved(s, obs.test === 'pass'))
120  if (obs.failed) step = then(step, s => toolFailed(s))
121  const risky = obs.caution
122  if (risky) {
123    const cross = isCross(step.save, t)
124    const no = step.save.egg.no
125    step = then(step, s => caution(s, risky, now, rng))
126    if (cross && step.save.egg.no !== no) step = then(step, s => endCross(s, t))
127  }
128  return step
129}
130
131export function onCommand(prev: Save, now: number, t: LocalTime, args: string, rng: () => number): Step {
132  const [sub = '', ...rest] = args.split(/\s+/)
133  const special = isSpecialDay(t)
134  // The reply date's hidden command (the same as its button); like any unknown command on other days
135  if (replyCommand().includes(sub)) return replyPress(prev, t) ?? { save: prev, effects: [], reply: T().unknown }
136  switch (sub) {
137    case 'refill': {
138      if (special) return humanCare(prev, t, 'refill')
139      // A timed date: refill presses the day's button instead (the band's button does the same)
140      if (paneRefillLabel(prev, t) !== null) {
141        const pressed = timedPress(prev, now, t)
142        if (pressed) return pressed
143      }
144      const step = refill(prev)
145      const cross = crossReply(prev, t, 'refill')
146      return cross ? { ...step, reply: cross } : step
147    }
148    case 'flip': {
149      if (special) return humanCare(prev, t, 'flip')
150      const costume = timedFlipReply(prev, t)
151      if (costume !== null) return { save: prev, effects: [], reply: costume }
152      const step = settle(flip(prev, now, t), now, rng)
153      const cross = crossReply(prev, t, 'flip')
154      return cross ? { ...step, reply: cross } : step
155    }
156    case 'dex': {
157      const text = dexText(prev, dexTitle(t))
158      if (!special) return { save: prev, effects: [], reply: text }
159      // That day the dex also counts the humans marinated so far this year
160      const done = humansDone(yearOf(structuredClone(prev), t.year))
161      const count = fill(decodeSpoilers().dateMode.dexCount, { n: String(done) })
162      return { save: prev, effects: [], reply: `${text}
163 ${count}` }
164    }
165    case 'help':
166      return { save: prev, effects: [], reply: T().help }
167    case 'name': {
168      const name = rest.join(' ').trim()
169      if (name === '' || [...name].length > NAME_MAX) return { save: prev, effects: [], reply: T().nameUsage }
170      const save = structuredClone(prev)
171      save.egg.name = name
172      return { save, effects: [], reply: fill(T().nameReply, { name }) }
173    }
174    default:
175      return { save: prev, effects: [], reply: T().unknown }
176  }
177}
178
hooks/model.ts 97 lines
1import type { Egg, EggRecord, Save } from '../types'
2import { T } from './text'
3
4export const STORE_KEY = 'tea-egg/v1'
5// Used instead while TEA_EGG_FAKE_DATE is in effect, so fake test dates never touch the real egg
6export const FAKE_STORE_KEY = 'tea-egg/v1-fake'
7// Whether the band above the prompt is hidden; kept apart from the save so it survives fake dates and egg resets
8export const BAND_STORE_KEY = 'tea-egg/band-hidden'
9// The fingerprint of another identity's save the person chose not to copy; asked again once that save changes
10export const SYNC_DISMISSED_KEY = 'tea-egg/sync-dismissed'
11
12export function newRecord(now: number): EggRecord {
13  return {
14    startedAt: now,
15    activeDays: [],
16    maxGapDays: 0,
17    sessionCount: 0,
18    sessionMinutes: 0,
19    testRuns: 0,
20    testFails: 0,
21    cracked: null,
22  }
23}
24
25export function newEgg(no: number, now: number): Egg {
26  return {
27    no,
28    name: T().defaultName, // picked in the current language; existing saves keep their name
29    progress: 0,
30    broth: 100,
31    mood: 70,
32    flipWantedAt: null,
33    activeMinutes: 0,
34    record: newRecord(now),
35  }
36}
37
38export function newSave(now: number): Save {
39  return {
40    version: 1,
41    egg: newEgg(1, now),
42    dex: {},
43    daily: { date: '', gained: 0 },
44    clocks: { lastTickAt: now, brothMs: 0, moodMs: 0, bucketStart: now, bucketActive: false },
45    nightToastFor: null,
46    harvestedAt: null,
47    dateMode: {},
48    welcomed: false,
49  }
50}
51
52const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
53const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
54
55export function isSave(v: unknown): v is Save {
56  if (!isObj(v) || v.version !== 1) return false
57  const { egg, dex, daily, clocks, dateMode } = v
58  if (!isObj(egg) || !isObj(egg.record) || !isObj(dex) || !isObj(daily) || !isObj(clocks) || !isObj(dateMode)) return false
59  const r = egg.record
60  return (
61    isNum(egg.no) && typeof egg.name === 'string' && isNum(egg.progress) && isNum(egg.broth) && isNum(egg.mood) &&
62    isNum(egg.activeMinutes) && (egg.flipWantedAt === null || isNum(egg.flipWantedAt)) &&
63    isNum(r.startedAt) && Array.isArray(r.activeDays) && isNum(r.maxGapDays) && isNum(r.sessionCount) &&
64    isNum(r.sessionMinutes) && isNum(r.testRuns) && isNum(r.testFails) &&
65    (r.cracked === null || typeof r.cracked === 'string') &&
66    typeof daily.date === 'string' && isNum(daily.gained) &&
67    isNum(clocks.lastTickAt) && isNum(clocks.brothMs) && isNum(clocks.moodMs) && isNum(clocks.bucketStart) &&
68    typeof clocks.bucketActive === 'boolean' && typeof v.welcomed === 'boolean'
69  )
70}
71
72function salvageDex(raw: unknown): Record<string, number> {
73  if (!isObj(raw) || !isObj(raw.dex)) return {}
74  const dex: Record<string, number> = {}
75  for (const [id, n] of Object.entries(raw.dex)) if (isNum(n) && n > 0) dex[id] = Math.floor(n)
76  return dex
77}
78
79// Older saves keyed the first special date by the year alone ("2027"); it is "d1:2027" now, beside the other dates.
80// Still version 1: an older copy of the mod reading this save skips keys it doesn't know instead of resetting the egg
81function migrate(s: Save): Save {
82  const old = Object.keys(s.dateMode).filter(k => /^\d{4}$/.test(k))
83  if (old.length === 0) return s
84  const dateMode = { ...s.dateMode }
85  for (const k of old) {
86    dateMode[`d1:${k}`] ??= dateMode[k]!
87    delete dateMode[k]
88  }
89  return { ...s, dateMode }
90}
91
92export function parseSave(raw: unknown, now: number): Save {
93  if (isSave(raw)) return migrate(raw)
94  const dex = salvageDex(raw)
95  return { ...newSave(now), dex, welcomed: Object.keys(dex).length > 0 }
96}
97
hooks/sync.ts 64 lines
1import type { Save } from '../types'
2import type { LocalTime } from './clock'
3import { isSave } from './model'
4import { fill, T } from './text'
5
6// Claude keeps one store file per load identity (tea-egg@<marketplace> installed, tea-egg@inline by --plugin-dir).
7// Each identity only writes its own save; the others are read to offer the person a copy, never written.
8
9export type SyncOffer = { save: Save; fingerprint: string }
10
11// A short, stable id of a save's content, so a declined offer is not asked again until that save changes
12export function fingerprint(s: unknown): string {
13  const text = JSON.stringify(s) ?? ''
14  let h = 5381
15  for (let i = 0; i < text.length; i++) h = ((h * 33) ^ text.charCodeAt(i)) >>> 0
16  return `${h.toString(16)}-${text.length}`
17}
18
19// The other save worth offering: valid, different from ours, and if several, the furthest along
20// (higher egg number, then the later tick). null when there is nothing to offer.
21export function pickOther(own: unknown, others: readonly unknown[]): Save | null {
22  const mine = JSON.stringify(own)
23  const candidates = others.filter((s): s is Save => isSave(s) && JSON.stringify(s) !== mine)
24  if (candidates.length === 0) return null
25  return candidates.reduce((a, b) =>
26    b.egg.no > a.egg.no || (b.egg.no === a.egg.no && b.clocks.lastTickAt > a.clocks.lastTickAt) ? b : a,
27  )
28}
29
30// The offer to show now, or null when there is none or the person already declined this exact save
31export function offerFor(own: unknown, others: readonly unknown[], dismissed: unknown): SyncOffer | null {
32  const other = pickOther(own, others)
33  if (other === null) return null
34  const fp = fingerprint(other)
35  return fp === dismissed ? null : { save: other, fingerprint: fp }
36}
37
38const pad = (n: number) => String(n).padStart(2, '0')
39
40// One line describing a save, e.g. "小蛋 #13、入味 32%、圖鑑 1 種(12 次),最後遊玩 10/14 01:32"
41export function describe(s: unknown, at: (ms: number) => LocalTime): string {
42  if (!isSave(s)) return T().sync.none
43  const counts = Object.values(s.dex)
44  const t = at(s.clocks.lastTickAt)
45  return fill(T().sync.line, {
46    name: s.egg.name,
47    no: String(s.egg.no),
48    flavor: String(Math.floor(s.egg.progress)),
49    kinds: String(counts.length),
50    count: String(counts.reduce((a, b) => a + b, 0)),
51    when: `${pad(t.month)}/${pad(t.day)} ${pad(t.hour)}:${pad(t.minute)}`,
52  })
53}
54
55// The two saves side by side, as /egg sync and the pane show them
56export function compareLines(own: unknown, other: Save, at: (ms: number) => LocalTime): string[] {
57  return [
58    T().sync.title,
59    `${T().sync.current}${describe(own, at)}`,
60    `${T().sync.other}${describe(other, at)}`,
61    T().sync.question,
62  ]
63}
64
hooks/panel.ts 201 lines
1import type { Save } from '../types'
2import type { LocalTime } from './clock'
3import { FIRST_ART, isSpecialDay, specialBand } from './datemode'
4import { dateArt, dateLook, timedBand } from './dates'
5import { compose, rasterCells, svgSource, SIZE, type Layer } from './pixels'
6import { decodeSpoilers } from './spoilers'
7import { ICON_OWN_PALETTES, ICON_PALETTE, LAYER_PALETTE_OF, LAYER_PALETTES, PALETTE, SPRITES } from './sprites'
8import { T } from './text'
9import { FACE_TEXT, bar, faceOf, hintOf, stageOf, strWidth, type Face } from './view'
10
11// The bigger the pixel art, the coarser it looks; 3x (144px) looks the most refined
12const SVG_SCALE = 3
13export const SVG_PX = SIZE * SVG_SCALE
14// Dark brown backing card: without it the white steam is invisible on light themes
15const SVG_BACKGROUND = '#3b2f2a'
16
17export const ASCII_EGG: readonly string[][] = [
18  ['  .-""-.  ', ' /      \\ ', '|  FACE  |', ' \\      / ', "  '-..-'  "],
19  ['  .-""-.  ', ' / ╱    \\ ', '|  FACE  |', ' \\    ╲ / ', "  '-..-'  "],
20  ['  .-""-.  ', ' /▓╱▓▓▓▓\\ ', '|▓ FACE ▓|', ' \\▓▓▓╲▓▓/ ', "  '-..-'  "],
21  ['  .-""-.  ', ' /█╱████\\ ', '|█ FACE █|', ' \\███╲██/ ', "  '-..-'  "],
22]
23
24export type Art = { kind: 'raster'; cells: string } | { kind: 'svg'; source: string } | { kind: 'ascii'; lines: string[] }
25
26// The egg is stacked from layers: the pot + egg for the stage (the dry-pot version once the broth runs out),
27// then the steam, then the face. The same face sheet fits every base, so a face never changes the egg's color.
28// No steam over a dry pot, or with the flip face (its ↻ sits where the steam rises)
29function baseKey(s: Save): string {
30  return `base${stageOf(s.egg.progress)}${s.egg.broth <= 0 ? '_dry' : ''}`
31}
32
33function faceKey(face: Face): string {
34  return `face_${face === 'dry' ? 'cry' : face}`
35}
36
37function stackKeys(base: string, face: string, steam = true): string[] {
38  const withSteam = steam && !base.endsWith('_dry') && face !== 'face_flip'
39  return [base, ...(withSteam ? ['steam'] : []), face]
40}
41
42// Special-date layers are in the encoded spoilers; a missing layer is skipped
43function layersOf(keys: readonly string[]): Layer[] {
44  const hidden = decodeSpoilers().sprites
45  return keys.flatMap(k => {
46    const pixels = SPRITES[k] ?? hidden[k]
47    return pixels ? [{ pixels }] : []
48  })
49}
50
51// Layers in a group of their own (a costume and its faces) use that group's palette
52const paletteOfLayers = (keys: readonly string[]): readonly number[] => {
53  const group = keys.map(k => LAYER_PALETTE_OF[k]).find(g => g !== undefined)
54  return (group !== undefined ? LAYER_PALETTES[group] : undefined) ?? PALETTE
55}
56
57// The keys to stack now, special dates included (dates.ts); null when a special date shows a dex icon instead
58function eggKeys(s: Save, t: LocalTime, now: number): string[] | null {
59  const special = dateArt(s, t, now)
60  if (special?.prize !== undefined) return null
61  const face = special?.face ?? faceKey(faceOf(s, t, now))
62  return stackKeys(special?.base ?? baseKey(s), face, special?.steam ?? true)
63}
64
65export function eggLayers(s: Save, t: LocalTime, now: number): Layer[] {
66  const keys = eggKeys(s, t, now)
67  return keys ? layersOf(keys) : []
68}
69
70function artOf(pixels: string, surface: string, palette: readonly number[] = PALETTE): Art {
71  return surface === 'terminal'
72    ? { kind: 'raster', cells: rasterCells(pixels, palette) }
73    : { kind: 'svg', source: svgSource(pixels, palette, SVG_SCALE, SVG_BACKGROUND) }
74}
75
76const FACE_COLS = 4
77
78// Truncate by display width, then pad with spaces (full-width chars take 2 columns, combining marks 0)
79function fitWidth(text: string, cols: number): string {
80  let out = ''
81  for (const ch of text) {
82    if (strWidth(out + ch) > cols) break
83    out += ch
84  }
85  return out + ' '.repeat(cols - strWidth(out))
86}
87
88export function eggArt(s: Save, t: LocalTime, now: number, surface: string, columns: number): Art {
89  const tooNarrow = surface === 'terminal' && columns < SIZE
90  // The first special date: the egg is paused all day, and a stand-in takes its place
91  if (isSpecialDay(t) && !tooNarrow) {
92    const stand = dexArt(FIRST_ART, true, surface)
93    if (stand) return stand
94  }
95  const prize = dateArt(s, t, now)?.prize
96  if (prize !== undefined && !tooNarrow) {
97    const icon = dexArt(prize, true, surface)
98    if (icon) return icon
99  }
100  const keys = eggKeys(s, t, now) ?? []
101  const layers = layersOf(keys)
102  if (layers.length === 0 || tooNarrow) {
103    const stage = stageOf(s.egg.progress)
104    // Only a 4-column face goes inside the frame (parentheses removed) to keep alignment
105    const face = fitWidth(FACE_TEXT[faceOf(s, t, now)].replace(/[()]/g, ''), FACE_COLS)
106    return { kind: 'ascii', lines: [...ASCII_EGG[stage]!.map(l => l.replace('FACE', face)), `   ${T().stageNames[stage]}`] }
107  }
108  return artOf(compose(layers), surface, paletteOfLayers(keys))
109}
110
111// Dev preview: every picture the game can actually show, as "<base>+<face>", without reading or changing the save.
112// Dry broth outranks every face except sleep and done, and done only follows a harvest (a fresh raw egg)
113const PLAY_FACES = ['face_happy', 'face_normal', 'face_bored', 'face_sleep', 'face_flip'] as const
114export const PREVIEW_KEYS: readonly string[] = [
115  ...[0, 1, 2, 3].flatMap(n => [...PLAY_FACES, ...(n === 0 ? ['face_done'] : [])].map(f => `base${n}+${f}`)),
116  ...[0, 1, 2, 3].flatMap(n => ['face_cry', 'face_sleep'].map(f => `base${n}_dry+${f}`)),
117]
118
119// "Stage label + face label", read in the current language when accessed
120export const PREVIEW_LABELS: Readonly<Record<string, string>> = Object.defineProperties(
121  {},
122  Object.fromEntries(
123    PREVIEW_KEYS.map(key => {
124      const [base, face] = key.split('+') as [string, string]
125      return [key, { enumerable: true, get: () => `${T().previewLabels[base]} + ${T().previewLabels[face]}` }]
126    }),
127  ),
128)
129
130// Pick the preview from the command argument: empty/next = next, prev = previous, number = nth (1-based), or a sprite name; off = stop
131const NEXT_WORDS = ['', 'next', '下一張']
132const PREV_WORDS = ['prev', '上一張']
133
134export function nextPreview(current: string | null, arg: string): string | null | undefined {
135  const a = arg.trim().toLowerCase()
136  if (a === 'off') return null
137  const step = NEXT_WORDS.includes(a) ? 1 : PREV_WORDS.includes(a) ? -1 : 0
138  if (step !== 0) {
139    const n = PREVIEW_KEYS.length
140    const i = current === null ? (step > 0 ? -1 : 0) : PREVIEW_KEYS.indexOf(current)
141    return PREVIEW_KEYS[(i + step + n) % n]
142  }
143  const n = Number(a)
144  if (Number.isInteger(n) && n >= 1 && n <= PREVIEW_KEYS.length) return PREVIEW_KEYS[n - 1]
145  return PREVIEW_KEYS.includes(a) ? a : undefined
146}
147
148export function previewArt(key: string, surface: string, columns: number): Art | null {
149  if (surface === 'terminal' && columns < SIZE) return null
150  const [base, face] = key.split('+')
151  const layers = base && face ? layersOf(stackKeys(base, face)) : []
152  return layers.length ? artOf(compose(layers), surface) : null
153}
154
155// Dex sprites (art sets C/D/E and later) use their own ICON_PALETTE (or their entry in ICON_OWN_PALETTES); return null when one is missing and the dex shows text only.
156// Always the pixel SVG on desktop: 9 HD icons made the pane too big and desktop drew nothing at all
157export function dexArt(id: string, owned: boolean, surface: string): Art | null {
158  // An egg whose picture isn't drawn yet keeps the locked picture; its caption still shows the name once owned
159  const pixels = owned ? decodeSpoilers().sprites[id] ?? SPRITES.locked : SPRITES.locked
160  if (!pixels) return null
161  const own = owned && pixels !== SPRITES.locked ? ICON_OWN_PALETTES[id] : undefined
162  return artOf(pixels, surface, own ?? ICON_PALETTE)
163}
164
165export function panelLines(s: Save, t: LocalTime, now: number): string[] {
166  // The first special date: the human's progress, broth and mood in place of the paused egg's. The human's number
167  // gets its own line so the three bars keep the same two-character labels as the egg's and line up
168  if (isSpecialDay(t)) {
169    const b = specialBand(s, t)
170    return [
171      `${b.title}  ${b.face}`,
172      b.name,
173      `${b.flavor} ${bar(b.human, 10)} ${Math.round(b.human)}%`,
174      `${T().broth} ${bar(b.broth, 10)} ${Math.round(b.broth)}`,
175      `${T().mood} ${bar(b.mood, 10)} ${Math.round(b.mood)}`,
176      b.hint,
177    ]
178  }
179  // A timed special date: the egg is paused; show the ask's countdown and the count instead of its stats.
180  // The countdown line keeps its emoji right of the digits: it changes every second (see bandSegments)
181  const timed = timedBand(s, t, now)
182  if (timed) {
183    return [
184      `${s.egg.name} #${s.egg.no}  ${timed.look.face}`,
185      ...(timed.timer !== null ? [`${timed.timer.digits} ${timed.timer.icon}`] : []),
186      ...(timed.count !== null ? [timed.count + (timed.mark !== null ? ` ${timed.mark}` : '')] : []),
187      timed.look.text,
188    ]
189  }
190  // Another special date's face and line, as on the band
191  const look = dateLook(s, t)
192  const hint = look ? look.text : hintOf(s, now)
193  return [
194    `${s.egg.name} #${s.egg.no}  ${look?.face ?? FACE_TEXT[faceOf(s, t, now)]}`,
195    `${T().flavor} ${bar(s.egg.progress, 10)} ${Math.floor(s.egg.progress)}%`,
196    `${T().broth} ${bar(s.egg.broth, 10)} ${Math.round(s.egg.broth)}`,
197    `${T().mood} ${bar(s.egg.mood, 10)} ${Math.round(s.egg.mood)}`,
198    ...(hint ? [hint] : []),
199  ]
200}
201
hooks/rules.ts 143 lines
1import type { Egg, Save } from '../types'
2import { newEgg } from './model'
3import type { Effect, Step } from './engine'
4import { decodeSpoilers } from './spoilers'
5import type { Rule, Spoilers } from './spoiler-types'
6import { T, fill } from './text'
7
8const DAY = 86_400_000
9const HINT_FROM = 50
10
11export type Stats = {
12  cracked: boolean
13  maxGapDays: number
14  testRuns: number
15  failRate: number
16  ageDays: number
17  multiDays: number
18  activeDays: number
19  dryMinutes: number
20  sessionCount: number
21  avgSessionMinutes: number
22}
23
24export function statsOf(egg: Egg, now: number): Stats {
25  const r = egg.record
26  return {
27    cracked: r.cracked !== null,
28    maxGapDays: r.maxGapDays,
29    testRuns: r.testRuns,
30    failRate: r.testRuns > 0 ? r.testFails / r.testRuns : 0,
31    ageDays: (now - r.startedAt) / DAY,
32    multiDays: (r.multiDays ?? []).length,
33    activeDays: r.activeDays.length,
34    dryMinutes: r.dryMinutes ?? 0,
35    sessionCount: r.sessionCount,
36    avgSessionMinutes: r.sessionCount > 0 ? r.sessionMinutes / r.sessionCount : 0,
37  }
38}
39
40// Rule kinds and how they're evaluated are public; thresholds and which egg each yields are in SPOILERS
41export function matches(rule: Rule, st: Stats, roll: number): boolean {
42  switch (rule.when) {
43    case 'cracked': return st.cracked
44    case 'chance': return roll < rule.p
45    case 'gapAtLeast': return st.maxGapDays >= rule.days
46    case 'failRateAbove': return st.testRuns >= rule.minRuns && st.failRate > rule.rate
47    case 'ageAtLeast': return st.ageDays >= rule.days
48    case 'dryAtLeast': return st.dryMinutes >= rule.minutes
49    case 'multiDaysAtLeast': return st.multiDays >= rule.days && st.multiDays >= rule.ratio * st.activeDays
50    case 'avgSessionAbove': return st.sessionCount > 0 && st.avgSessionMinutes > rule.minutes
51    case 'avgSessionBelow': return st.sessionCount > 0 && st.avgSessionMinutes < rule.minutes
52    case 'always': return true
53  }
54}
55
56export function outcome(egg: Egg, now: number, rng: () => number): string {
57  const st = statsOf(egg, now)
58  const roll = rng()
59  const rules = decodeSpoilers().rules
60  return (rules.find(rule => matches(rule, st, roll)) ?? rules[rules.length - 1]!).egg
61}
62
63export function predictHint(egg: Egg, now: number): string | null {
64  if (egg.progress < HINT_FROM) return null
65  const st = statsOf(egg, now)
66  const { rules, hints } = decodeSpoilers()
67  const guess = rules.find(rule => rule.when !== 'cracked' && rule.when !== 'chance' && matches(rule, st, 1))
68  return guess ? hints[guess.egg] ?? null : null
69}
70
71function harvest(s: Save, now: number, rng: () => number): Effect {
72  const { eggs, crackToast } = decodeSpoilers()
73  const id = outcome(s.egg, now, rng)
74  const info = eggs[id] ?? { name: id, icon: '🥚' }
75  const isNew = (s.dex[id] ?? 0) === 0
76  s.dex[id] = (s.dex[id] ?? 0) + 1
77  const keyword = s.egg.record.cracked
78  const text = keyword !== null
79    ? fill(crackToast, { kw: keyword, name: info.name, icon: info.icon })
80    : fill(T().harvest, { name: info.name })
81  // A session that goes on after the harvest counts toward the new egg on its next prompt (usage.ts)
82  s.egg = newEgg(s.egg.no + 1, now)
83  s.daily.gained = 0 // the daily cap is per egg: a new egg gets a fresh cap even if the last one used today's up
84  s.harvestedAt = now
85  return { kind: 'toast', text: isNew ? text + T().newDex : text }
86}
87
88export function settle(step: Step, now: number, rng: () => number): Step {
89  const s = step.save
90  if (s.egg.record.cracked === null && s.egg.progress < 100) return step
91  const save = structuredClone(s)
92  const effect = harvest(save, now, rng)
93  return { ...step, save, effects: [...step.effects, effect] }
94}
95
96export function crack(prev: Save, keyword: string, now: number, rng: () => number): Step {
97  const save = structuredClone(prev)
98  save.egg.record.cracked = keyword
99  return settle({ save, effects: [] }, now, rng)
100}
101
102// A caution-level command: counted for this egg; enough of them crack it like a dangerous command would
103export function caution(prev: Save, keyword: string, now: number, rng: () => number): Step {
104  const save = structuredClone(prev)
105  const r = save.egg.record
106  r.cautions = (r.cautions ?? 0) + 1
107  const rule = decodeSpoilers().rules.find(x => x.when === 'cracked')
108  const limit = rule?.when === 'cracked' ? rule.cautions : Infinity
109  if (r.cautions >= limit) return crack(save, keyword, now, rng)
110  return { save, effects: [] }
111}
112
113// Special-date prize eggs hide even its icon until collected. Decided by "is it the prize", not by slot position,
114// so egg kinds added later (regular or special) can sit in any slot without being mistaken for it
115export function isPrizeEgg(id: string, sp: Spoilers = decodeSpoilers()): boolean {
116  if (id === sp.dateMode.prize) return true
117  return Object.values(sp.dates ?? {}).some(d => (d.kind === 'timed' ? d.prizes.won === id || d.prizes.lost === id : d.prize === id))
118}
119
120// Pane header: the pictures carry the rest
121export function dexHeader(save: Save, title: string, sp: Spoilers = decodeSpoilers()): string {
122  const owned = sp.dexSlots.filter(id => (save.dex[id] ?? 0) > 0)
123  return ` ${title} ${owned.length}/${sp.dexSlots.length}`
124}
125
126// Caption under one pane cell: name and count once collected, ??? before
127export function dexCaption(save: Save, id: string, sp: Spoilers = decodeSpoilers()): { name: string; count: string } {
128  const n = save.dex[id] ?? 0
129  return n > 0 ? { name: sp.eggs[id]!.name, count: `×${n}` } : { name: '???', count: ' ' }
130}
131
132// Text-only dex (the /egg dex reply)
133export function dexText(save: Save, title: string, sp: Spoilers = decodeSpoilers()): string {
134  const { eggs, dexSlots } = sp
135  const owned = dexSlots.filter(id => (save.dex[id] ?? 0) > 0)
136  const missing = dexSlots.filter(id => (save.dex[id] ?? 0) === 0)
137  const ownedText = owned.map(id => `${eggs[id]!.icon} ${eggs[id]!.name} ×${save.dex[id]}`)
138  const missingText = missing.map(id => (isPrizeEgg(id, sp) ? '❓ ???' : `${eggs[id]!.icon} ???`))
139  return [dexHeader(save, title, sp), ` ${ownedText.join('   ')}`, ` ${missingText.join('   ')}`]
140    .filter(line => line.trim() !== '')
141    .join('\n')
142}
143
hooks/store.ts 32 lines
1import type { Save } from '../types'
2import type { Step } from './engine'
3import { parseSave } from './model'
4
5
6// The plugin loader doesn't follow $ across imports, so every $.xxx call stays in register.tsx; this file only gets the wrapped StoreIo
7export type StoreIo = {
8  now: () => Promise<number>
9  read: () => Promise<unknown>
10  write: (save: Save) => Promise<void>
11  toast: (text: string, order: number) => void // order: its place among the event's toasts (register.tsx spaces them out)
12}
13
14let queue: Promise<unknown> = Promise.resolve()
15
16export async function loadSave(io: StoreIo): Promise<Save> {
17  return parseSave(await io.read(), await io.now())
18}
19
20// Read → compute → write, one at a time, so events within a session never overwrite each other
21export function mutate(io: StoreIo, fn: (s: Save, now: number) => Step): Promise<Step> {
22  const run = queue.then(async () => {
23    const now = await io.now()
24    const step = fn(parseSave(await io.read(), now), now)
25    await io.write(step.save)
26    step.effects.forEach((effect, i) => io.toast(effect.text, i))
27    return step
28  })
29  queue = run.catch(() => undefined)
30  return run
31}
32
hooks/usage.ts 135 lines
1import type { Save } from '../types'
2import type { LocalTime } from './clock'
3import { dryLine, humanBroth, isPausedDay, isSpecialDay } from './datemode'
4import { RULES, uncovered, useBroth, type Effect } from './engine'
5import { noteUse } from './multi'
6
7// Session length = time actually in use, not time the program stays open.
8// A segment runs from a prompt to the last turn that finished after it; a prompt 30+ minutes after the last turn
9// starts a new segment and the break in between doesn't count. Each session keeps its own record in the store
10// under its session id (a --resume keeps the id, so a resumed session carries on), and every finished turn adds
11// the new minutes to whichever egg is in the pot at that moment, so a harvest splits a session between two eggs.
12
13const MIN = 60_000
14export const SEGMENT_GAP_MS = 30 * MIN
15// Records of sessions not used for this long are dropped from the store
16export const USE_KEEP_MS = 30 * 24 * 60 * MIN
17
18export type SessionUse = {
19  minutes: number // total minutes in use, across days and eggs
20  segmentStart: number | null
21  lastTurnEnd: number | null
22  lastPromptAt: number | null
23  countedFor: number | null // the egg number this session already counted toward
24}
25
26export function newUse(): SessionUse {
27  return { minutes: 0, segmentStart: null, lastTurnEnd: null, lastPromptAt: null, countedFor: null }
28}
29
30const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
31const numOrNull = (v: unknown): number | null => (isNum(v) ? v : null)
32
33export function parseUse(raw: unknown): SessionUse {
34  if (typeof raw !== 'object' || raw === null) return newUse()
35  const r = raw as Record<string, unknown>
36  return {
37    minutes: isNum(r.minutes) ? r.minutes : 0,
38    segmentStart: numOrNull(r.segmentStart),
39    lastTurnEnd: numOrNull(r.lastTurnEnd),
40    lastPromptAt: numOrNull(r.lastPromptAt),
41    countedFor: numOrNull(r.countedFor),
42  }
43}
44
45export function useStale(use: SessionUse, now: number): boolean {
46  const last = Math.max(use.lastTurnEnd ?? 0, use.segmentStart ?? 0)
47  return now - last > USE_KEEP_MS
48}
49
50// When this segment was last active: its last finished turn, or its start if no turn has finished in it yet
51function lastActive(use: SessionUse): number | null {
52  if (use.segmentStart === null) return null
53  return use.lastTurnEnd !== null && use.lastTurnEnd >= use.segmentStart ? use.lastTurnEnd : use.segmentStart
54}
55
56export type UseStep = { save: Save; use: SessionUse; effects: Effect[] }
57
58// Stretches spent waiting for the person (a permission prompt, a question to answer) are not use
59export type Wait = [from: number, to: number]
60
61// [from, to] with the waits taken out, as the pieces that remain
62export function withoutWaits(from: number, to: number, waits: readonly Wait[]): Wait[] {
63  let pieces: Wait[] = [[from, to]]
64  for (const [a, b] of waits) {
65    pieces = pieces.flatMap(([x, y]): Wait[] => {
66      if (b <= x || a >= y) return [[x, y]]
67      const out: Wait[] = []
68      if (a > x) out.push([x, a])
69      if (b < y) out.push([b, y])
70      return out
71    })
72  }
73  return pieces
74}
75
76// prompt.submit: start a new segment after a long break, and count this session toward the egg in the pot once
77export function usePrompt(prev: Save, prevUse: SessionUse, now: number, t: LocalTime, _tag = ''): UseStep {
78  // The first special date keeps the segments going for the human's broth (useTurn); the egg's records stay as they are
79  const human = isSpecialDay(t)
80  if (isPausedDay(t) && !human) return { save: prev, use: prevUse, effects: [] }
81  const save = structuredClone(prev)
82  const use = { ...prevUse }
83  const last = lastActive(use)
84  if (last === null || now - last >= SEGMENT_GAP_MS) use.segmentStart = now
85  use.lastPromptAt = now
86  if (!human && use.countedFor !== save.egg.no) {
87    save.egg.record.sessionCount += 1
88    use.countedFor = save.egg.no
89  }
90  return { save, use, effects: [] }
91}
92
93// turn.complete: add the minutes since the segment was last active to the egg in the pot, use up broth for them,
94// and note them for this session (tag) so overlaps with other sessions can be found (multi.ts). Time spent waiting
95// for the person during the turn (waits) is left out of all three. On the first special date the time uses up the
96// human's broth instead (terminal: the dry toast mentions the fallback command), and the egg's records stay as they are
97export function useTurn(
98  prev: Save,
99  prevUse: SessionUse,
100  now: number,
101  t: LocalTime,
102  tag = '',
103  waits: readonly Wait[] = [],
104  terminal = false,
105): UseStep {
106  const human = isSpecialDay(t)
107  if (isPausedDay(t) && !human) return { save: prev, use: prevUse, effects: [] }
108  const save = structuredClone(prev)
109  const use = { ...prevUse }
110  const effects: Effect[] = []
111  const last = lastActive(use)
112  const prompted = use.lastPromptAt !== null && (use.lastTurnEnd === null || use.lastPromptAt > use.lastTurnEnd)
113  // A turn with no prompt before it opens a segment here and adds nothing yet, unless it follows the last turn
114  // closely. A turn that a prompt started always counts in full, however long it ran
115  if (last === null || (!prompted && now - last >= SEGMENT_GAP_MS)) {
116    use.segmentStart = now
117  } else {
118    for (const [a, b] of withoutWaits(last, now, waits)) {
119      if (human) {
120        const r = uncovered(save.clocks.usedSpans ?? [], a, b)
121        save.clocks.usedSpans = r.spans
122        if (humanBroth(save, t, r.ms, RULES.brothStepMs, RULES.brothStep)) effects.push({ kind: 'toast', text: dryLine(terminal) })
123        continue
124      }
125      const minutes = (b - a) / MIN
126      save.egg.record.sessionMinutes += minutes
127      use.minutes += minutes
128      useBroth(save, a, b, effects)
129      noteUse(save, tag, a, b, t)
130    }
131  }
132  use.lastTurnEnd = now
133  return { save, use, effects }
134}
135
hooks/engine.ts 204 lines
1import type { Save } from '../types'
2import { daysBetween, type LocalTime } from './clock'
3import { isPausedDay } from './datemode'
4import { T, pick } from './text'
5
6export type Effect = { kind: 'toast'; text: string }
7export type Step = { save: Save; effects: Effect[]; reply?: string }
8
9const MIN = 60_000
10
11export const RULES = {
12  dailyCap: 15,
13  brothStepMs: 15 * MIN,
14  brothStep: 4,
15  moodStepMs: 60 * MIN,
16  moodStep: 5,
17  bucketMs: 10 * MIN,
18  flipAfterMin: 90,
19  flipWindowMs: 30 * MIN,
20  flipBonus: 2,
21  maxTickGapMs: 3 * MIN,
22  lowBroth: 30,
23  nightEndHour: 5,
24} as const
25
26const clamp = (n: number) => Math.max(0, Math.min(100, n))
27const toast = (text: string): Effect => ({ kind: 'toast', text })
28const begin = (prev: Save): Step => ({ save: structuredClone(prev), effects: [] })
29
30export function gain(s: Save, n: number, t: LocalTime, capped: boolean): number {
31  if (s.egg.broth <= 0 || n <= 0) return 0
32  if (capped) {
33    if (s.daily.date !== t.date) s.daily = { date: t.date, gained: 0 }
34    n = Math.min(n, RULES.dailyCap - s.daily.gained)
35    if (n <= 0) return 0
36    s.daily.gained += n
37  }
38  const before = s.egg.progress
39  s.egg.progress = Math.min(100, before + n)
40  return s.egg.progress - before
41}
42
43// Spans of use are kept for a day: long enough for any session's turn to overlap them
44export const SPAN_KEEP_MS = 24 * 60 * MIN
45
46// The part of [from, to] not yet covered by the (merged) spans, and the spans with [from, to] merged in
47export function uncovered(spans: [number, number][], from: number, to: number): { ms: number; spans: [number, number][] } {
48  let covered = 0
49  for (const [a, b] of spans) covered += Math.max(0, Math.min(b, to) - Math.max(a, from))
50  const merged: [number, number][] = []
51  for (const [a, b] of [...spans, [from, to] as [number, number]].sort((x, y) => x[0] - y[0])) {
52    const last = merged[merged.length - 1]
53    if (last && a <= last[1]) last[1] = Math.max(last[1], b)
54    else merged.push([a, b])
55  }
56  return { ms: Math.max(0, to - from - covered), spans: merged.filter(([, b]) => b >= to - SPAN_KEEP_MS) }
57}
58
59// Broth goes down only for time in use ([from, to], one segment of a session). Several sessions in use at once
60// share the save's charged spans, so the same stretch of time is charged once
61export function useBroth(s: Save, from: number, to: number, effects: Effect[]): void {
62  if (to <= from) return
63  const r = uncovered(s.clocks.usedSpans ?? [], from, to)
64  s.clocks.usedSpans = r.spans
65  let ms = r.ms
66  while (ms > 0) {
67    if (s.egg.broth <= 0) {
68      // A dry pot: the rest of this stretch is time in use with no broth (whatever the day's flavor)
69      s.egg.record.dryMinutes = (s.egg.record.dryMinutes ?? 0) + ms / MIN
70      return
71    }
72    const part = Math.min(ms, RULES.brothStepMs - s.clocks.brothMs)
73    s.clocks.brothMs += part
74    ms -= part
75    if (s.clocks.brothMs >= RULES.brothStepMs) {
76      s.clocks.brothMs = 0
77      s.egg.broth = clamp(s.egg.broth - RULES.brothStep)
78      if (s.egg.broth === 0) effects.push(toast(T().brothEmpty))
79    }
80  }
81}
82
83// Special-date-mode days pause the egg: they are neither active days nor days not opened
84function pausedDaysBetween(a: string, b: string): number {
85  const start = Date.parse(`${a}T00:00:00Z`)
86  const span = Math.min(daysBetween(a, b), 400)
87  let n = 0
88  for (let i = 1; i < span; i++) {
89    const d = new Date(start + i * 24 * 60 * MIN)
90    const month = d.getUTCMonth() + 1
91    const day = d.getUTCDate()
92    if (isPausedDay({ month, day })) n++
93  }
94  return n
95}
96
97export function addActiveDay(s: Save, t: LocalTime): void {
98  const days = s.egg.record.activeDays
99  if (days.includes(t.date)) return
100  const last = days[days.length - 1]
101  // Gap = days not opened between two active days (consecutive days = 0); special-date days in between don't count
102  if (last !== undefined) {
103    const gap = daysBetween(last, t.date) - 1 - pausedDaysBetween(last, t.date)
104    s.egg.record.maxGapDays = Math.max(s.egg.record.maxGapDays, gap)
105  }
106  days.push(t.date)
107}
108
109export function tick(prev: Save, now: number, t: LocalTime): Step {
110  const step = begin(prev)
111  const s = step.save
112  const elapsed = Math.max(0, Math.min(now - s.clocks.lastTickAt, RULES.maxTickGapMs))
113  s.clocks.lastTickAt = Math.max(s.clocks.lastTickAt, now)
114  if (elapsed === 0) return step
115
116  // Session length and broth both follow actual use (usage.ts, useBroth), not the time the program stays open
117
118  s.clocks.moodMs += elapsed
119  while (s.clocks.moodMs >= RULES.moodStepMs) {
120    s.clocks.moodMs -= RULES.moodStepMs
121    s.egg.mood = clamp(s.egg.mood - RULES.moodStep)
122  }
123
124  if (now - s.clocks.bucketStart >= RULES.bucketMs) {
125    // Skip a bucket that started too long ago (the session was interrupted)
126    const fresh = now - s.clocks.bucketStart < RULES.bucketMs + RULES.maxTickGapMs
127    if (s.clocks.bucketActive && fresh) {
128      gain(s, 1, t, true)
129      s.egg.activeMinutes += RULES.bucketMs / MIN
130    }
131    s.clocks.bucketStart = now
132    s.clocks.bucketActive = false
133  }
134
135  if (s.egg.flipWantedAt !== null && now - s.egg.flipWantedAt > RULES.flipWindowMs) {
136    s.egg.flipWantedAt = null
137    s.egg.activeMinutes = 0
138  } else if (s.egg.flipWantedAt === null && s.egg.activeMinutes >= RULES.flipAfterMin) {
139    s.egg.flipWantedAt = now
140    step.effects.push(toast(T().flipWanted))
141  }
142  return step
143}
144
145export function turnDone(prev: Save, now: number, t: LocalTime, rng: () => number): Step {
146  const step = begin(prev)
147  const s = step.save
148  addActiveDay(s, t)
149  s.clocks.bucketActive = true
150  gain(s, 1, t, true)
151  if (t.hour < RULES.nightEndHour && s.nightToastFor !== t.date) {
152    s.nightToastFor = t.date
153    step.effects.push(toast(pick(T().night, rng)))
154  }
155  return step
156}
157
158export function refill(prev: Save): Step {
159  const step = begin(prev)
160  step.save.egg.broth = 100
161  step.save.egg.mood = Math.max(clamp(step.save.egg.mood + 20), 70)
162  step.reply = T().refillReply
163  return step
164}
165
166export function flip(prev: Save, now: number, t: LocalTime): Step {
167  const step = begin(prev)
168  const egg = step.save.egg
169  if (egg.flipWantedAt === null || now - egg.flipWantedAt > RULES.flipWindowMs) {
170    step.reply = T().flipNotNeeded
171    return step
172  }
173  const gained = gain(step.save, RULES.flipBonus, t, false)
174  egg.mood = clamp(egg.mood + 15)
175  egg.flipWantedAt = null
176  egg.activeMinutes = 0
177  step.reply = gained > 0 ? T().flipReply : T().flipNoGain
178  return step
179}
180
181export function testObserved(prev: Save, passed: boolean): Step {
182  const step = begin(prev)
183  const r = step.save.egg.record
184  r.testRuns += 1
185  if (passed) step.save.egg.mood = clamp(step.save.egg.mood + 5)
186  else r.testFails += 1
187  return step
188}
189
190export function toolFailed(prev: Save): Step {
191  const step = begin(prev)
192  step.save.egg.mood = clamp(step.save.egg.mood - 3)
193  return step
194}
195
196export function pauseClocks(prev: Save, now: number): Step {
197  const step = begin(prev)
198  const c = step.save.clocks
199  c.lastTickAt = Math.max(c.lastTickAt, now)
200  c.bucketStart = now
201  c.bucketActive = false
202  return step
203}
204