SLOPSHOPPER

context-weather

A lo-fi pixel weather window whose sky follows the context: clear when it is empty, a thunderstorm when it is full, and day or night by your clock

panebandspinnercommandprocesstimer
★ 2v0.2.0MITupdated 2026-10-10akerskuuug/claude-mods/plugins/context-weather
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · context-weather
│ ┃ Weather ✕ › fix the failing auth test and add an audit log call │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⏺ Read(src/auth.ts) │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⎿ Read 6 lines │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⏺ Update(src/auth.ts) │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /weather │ ┃ ⎿ context-weather: Weather window opened. │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Weather
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ overcast · 49% context
README

context-weather

A Claude Code mod that shows a lo-fi pixel weather window beside the conversation. The weather follows how full the context is, and the time of day follows your clock.

Weather from an empty context to a full one

Weather

ContextWeather
under 10%clear skies
10–25%fair
25–45%partly cloudy
45–60%overcast
60–75%light rain
75–88%heavy rain
88% and upthunderstorm, with lightning

Clouds get bigger and drift faster as the context fills, and the rain slants harder in the wind. The scene eases between levels, so after a compaction the storm clears over a few seconds. A caption under the scene reads like dusk · heavy rain · 76% context.

Time of day

Night, dawn, morning, afternoon, dusk, night, and a rainy night

The sun rises at 6:00 and sets at 20:00, local time, crossing the sky between them, with half an hour of twilight on either side. Dawn and dusk tint the sky warm. At night a moon crosses the sky and stars twinkle wherever it is clear. The house's window is lit at night and whenever the weather turns gloomy. The time zone is read from date +%z once a minute, so daylight saving changes are picked up.

Visitors

Every 3 to 8 minutes, at random, someone may pass through, if the weather suits them:

WeatherVisitor
clear or fair, by daya few birds flapping across
clear or fair, at dawn and duska cat, who climbs to the roof's peak, sits a while and goes on
clear or fair, at nighta shooting star, or an owl on the roof, blinking and looking about
partly cloudy or overcastsomeone flying a kite by the house (by day), a far-off plane with a blinking beacon, or at night the owl
rainsomeone walking out under an umbrella, which blows inside out in heavy rain and sends them running; or a duck, waddling through
thunderstormwhatever the gale picked up, tumbling past: a bike, a shed door, the umbrella someone lost, or (one time in four) a cow

A visitor who arrives stays until they are out of sight, even if the weather changes.

Commands

  • /weather opens or closes the window.
  • /weather at 22:30 shows that time of day instead of the clock (handy for a preview); /weather at now follows the clock again.
  • /weather visit cow sends a visitor by now, whatever the weather: birds, cat, star, owl, kite, plane, umbrella, duck, cow, bike, door or lost-umbrella (plurals and a few other names work too).

Where it shows

  • In the terminal's fullscreen layout the window opens by itself, docked beside the transcript, once the terminal is at least 144 columns wide. Narrower, open it with /weather.
  • On the main screen (not fullscreen) it never opens by itself. /weather opens it above the prompt, up to 8 rows tall.
  • The pixel scene is terminal-only. In the desktop app's Code tab the window shows the caption alone.
  • It animates at 8 frames per second, two pixels per cell (▀ with separate top and bottom colors).

Install

/plugin marketplace add akerskuuug/claude-mods
/plugin install context-weather@claude-mods

Pick the user scope when prompted.

The mod runs as function hooks, which Claude Code only loads when they are switched on. Add this to ~/.claude/settings.json (if the file already exists, merge env into it) and restart Claude Code:

{
  "env": {
    "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1"
  }
}

Without it the mod installs but shows nothing.

Source 2 files
hooks/register.tsx 948 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { DayPhase } from '../types'
5
6const PANE = 'context-weather'
7const FRAME_MS = 125 // 8 fps: lo-fi on purpose
8const UPPER_HALF = 0x2580 // '▀': foreground paints the top pixel, background the bottom
9// Where heavy rain turns into a thunderstorm: the forecast and the lightning share it.
10const STORM = 0.88
11// Where overcast turns into light rain: the forecast and the raindrops share it.
12const RAIN = 0.6
13// The terminal width from which the pane opens by itself.
14const WIDE = 144
15const DEFAULT_COLUMNS = 32
16
17
18const percent = atom({ plugin: 'context-weather', key: 'percent' } as const, null)
19const phaseNow = atom({ plugin: 'context-weather', key: 'phase' } as const, null)
20const override = atom({ plugin: 'context-weather', key: 'override' } as const, null)
21
22// ---------------------------------------------------------------- weather model
23
24export function contextPercent(context: { tokens?: number; window: number; percent?: number }): number {
25  const used = context.percent ?? (context.window > 0 ? ((context.tokens ?? 0) / context.window) * 100 : 0)
26  return Math.max(0, Math.min(100, used))
27}
28
29export function forecast(pct: number): string {
30  if (pct < 10) return 'clear skies'
31  if (pct < 25) return 'fair'
32  if (pct < 45) return 'partly cloudy'
33  if (pct < RAIN * 100) return 'overcast'
34  if (pct < 75) return 'light rain'
35  if (pct < STORM * 100) return 'heavy rain'
36  return 'thunderstorm'
37}
38
39const clamp01 = (n: number) => Math.max(0, Math.min(1, n))
40
41/** How hard it rains, 0 to 1: none until light rain, full by 90%. */
42export function rainfall(s: number): number {
43  return clamp01((s - RAIN) / 0.3)
44}
45
46// ---------------------------------------------------------------- the day
47
48// A simple day: sunrise at 6, sunset at 20, twilight half an hour either side.
49const SUNRISE = 6
50const SUNSET = 20
51const TWILIGHT = 0.75
52
53/** Hours since local midnight, 0..24, from epoch ms and the UTC offset in minutes. */
54export function localHour(ms: number, offsetMinutes: number): number {
55  const minutes = Math.floor(ms / 60_000) + offsetMinutes
56  return (((minutes % 1440) + 1440) % 1440) / 60
57}
58
59/** 0 at night, 1 by day, easing through dawn and dusk. */
60export function daylight(hour: number): number {
61  const rise = clamp01((hour - (SUNRISE - TWILIGHT)) / (2 * TWILIGHT))
62  const set = clamp01((SUNSET + TWILIGHT - hour) / (2 * TWILIGHT))
63  return Math.min(rise, set)
64}
65
66/** 1 right at sunrise or sunset, fading to 0 an hour and a quarter away. */
67function glow(hour: number): number {
68  return clamp01(1 - Math.min(Math.abs(hour - SUNRISE), Math.abs(hour - SUNSET)) / 1.25)
69}
70
71export function dayPhase(hour: number): DayPhase {
72  if (Math.abs(hour - SUNRISE) <= TWILIGHT) return 'dawn'
73  if (Math.abs(hour - SUNSET) <= TWILIGHT) return 'dusk'
74  return hour > SUNRISE && hour < SUNSET ? 'day' : 'night'
75}
76
77/** Parses `date +%z` (`+0200`, `-0530`) into minutes east of UTC. */
78export function parseOffset(text: string): number | null {
79  const m = /^([+-])(\d\d)(\d\d)$/.exec(text.trim())
80  if (!m) return null
81  return (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3]))
82}
83
84/** `22`, `22:30`, `7:05` as hours since midnight; null for anything else. */
85export function parseClock(text: string): number | null {
86  const m = /^(\d{1,2})(?::(\d\d))?$/.exec(text.trim())
87  if (!m) return null
88  const h = Number(m[1])
89  const min = Number(m[2] ?? 0)
90  return h < 24 && min < 60 ? h + min / 60 : null
91}
92
93function hash(n: number): number {
94  let x = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b)
95  x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35)
96  return ((x ^ (x >>> 16)) >>> 0) / 0x100000000
97}
98
99function mix(a: number, b: number, t: number): number {
100  const k = clamp01(t)
101  const ch = (shift: number) => {
102    const x = (a >> shift) & 0xff
103    const y = (b >> shift) & 0xff
104    return Math.round(x + (y - x) * k) << shift
105  }
106  return ch(16) | ch(8) | ch(0)
107}
108
109// ---------------------------------------------------------------- visitors
110
111// Now and then someone passes through, if the weather suits them (see visitorFor).
112// Each kind in KINDS says what it is called, how long it stays and how it is drawn.
113export const VISITORS = [
114  'birds',
115  'cat',
116  'star',
117  'owl',
118  'kite',
119  'plane',
120  'umbrella',
121  'duck',
122  'cow',
123  'bike',
124  'door',
125  'lost-umbrella',
126] as const
127export type VisitorKind = (typeof VISITORS)[number]
128export type Visitor = { kind: VisitorKind; start: number; seed: number }
129
130// What the storm blows past; the cow is one in four.
131const STORM_VISITORS: readonly VisitorKind[] = ['cow', 'bike', 'door', 'lost-umbrella']
132
133// Between visits: 3 to 8 minutes.
134const GAP_MIN = (3 * 60_000) / FRAME_MS
135const GAP_MAX = (8 * 60_000) / FRAME_MS
136// Where light rain turns heavy: the umbrella gives up from here.
137const HEAVY = 0.75
138
139// Pixels per frame.
140const BIRD_SPEED = 0.35
141const CAT_SPEED = 0.12
142const PLANE_SPEED = 0.5
143const WALK_SPEED = 0.25
144const RUN_SPEED = 0.6
145const DUCK_SPEED = 0.2
146const STAR_FALL = 8 // frames the shooting star moves
147const STAR_FADE = 5 // frames it fades after
148const KITE_FRAMES = 320 // 40 seconds of kite flying
149const KITE_REEL = 40 // frames to let the kite out, and to reel it in
150const CAT_SIT = 160 // frames the cat sits on the roof's peak
151const CAT_UP = Math.ceil(3 / CAT_SPEED) // from the left eave to the peak
152const CAT_DOWN = Math.ceil(5 / CAT_SPEED) // from the peak off the right eave
153const OWL_FRAMES = 480 // a minute on the roof
154const OWL_LEAVE = 24 // frames flying off at the end of it
155
156/** Frames until the next visit, from a roll of 0..1. */
157export function nextGap(roll: number): number {
158  return Math.round(GAP_MIN + clamp01(roll) * (GAP_MAX - GAP_MIN))
159}
160
161const pick = <T,>(list: readonly T[], roll: number): T => list[Math.min(list.length - 1, Math.floor(roll * list.length))]!
162
163/** Who visits this sky; `roll` (0..1) picks where several might. */
164export function visitorFor(s: number, hour: number, roll = 0, hasHouse = true): VisitorKind {
165  if (s >= STORM) return pick(STORM_VISITORS, roll)
166  if (s >= RAIN) return roll < 0.5 ? 'umbrella' : 'duck'
167  const phase = dayPhase(hour)
168  if (s < 0.25 && (phase === 'dawn' || phase === 'dusk')) return hasHouse ? 'cat' : 'birds'
169  const light = daylight(hour)
170  if (light < 0.3) {
171    if (!hasHouse) return s < 0.25 ? 'star' : 'plane'
172    return roll < 0.5 ? (s < 0.25 ? 'star' : 'plane') : 'owl'
173  }
174  if (s >= 0.25) return light > 0.6 && roll < 0.5 ? 'kite' : 'plane'
175  return 'birds'
176}
177
178/** How many frames a visit lasts in a scene `w` pixels wide: until it is out of sight. */
179export function visitLength(kind: VisitorKind, w: number): number {
180  return KINDS[kind].length(w)
181}
182
183/** The visitor `/weather visit <name>` means, or null. */
184export function visitorNamed(name: string): VisitorKind | null {
185  const key = name.trim().toLowerCase()
186  return VISITORS.find(k => k === key || KINDS[k].names.includes(key)) ?? null
187}
188
189/** What a visitor draws with: the scene's measures and pens, for one frame. */
190type Scene = {
191  w: number
192  groundY: number
193  s: number
194  light: number
195  frame: number
196  hx: number // the house's left wall
197  door: number // the house's middle: walkers come out from behind it
198  dot(x: number, y: number, color: number, alpha?: number): void
199  /** Rows of letters keyed into `colors`, '.' for clear, shaded for the dark. */
200  sprite(rows: readonly string[], colors: Record<string, number>, x: number, y: number): void
201  shade(color: number): number
202  /** Someone 3 pixels tall standing on the ground at `x`, legs apart mid-stride. */
203  person(x: number, isStriding: boolean): void
204  /** The roof's top edge at `x`. */
205  roofTop(x: number): number
206}
207
208// Where a visitor is drawn: behind the clouds, in front of the rain, or on the house.
209export type Layer = 'sky' | 'air' | 'roof'
210
211type Kind = {
212  arrival: string // what /weather visit answers
213  names: string[] // other names /weather visit takes
214  layer: Layer
215  length(w: number): number
216  /** Draws the visitor `t` frames into its visit. */
217  draw(scene: Scene, t: number, seed: number): void
218}
219
220/** Which way a visitor heads: 1 left to right, -1 right to left. */
221const heading = (seed: number) => (hash(seed + 2) < 0.5 ? -1 : 1)
222/** Where something crossing at `speed` is, `t` frames after it came in from the side `dir` says. */
223const across = (w: number, t: number, speed: number, dir: number) => (dir > 0 ? -2 + t * speed : w + 1 - t * speed)
224
225/** `rows` turned a quarter clockwise `quarters` times. */
226function turn(rows: readonly string[], quarters: number): string[] {
227  let out = [...rows]
228  for (let q = 0; q < quarters % 4; q++) out = Array.from(out[0]!, (_, c) => out.map(row => row[c]!).reverse().join(''))
229  return out
230}
231
232/** Something the gale picked up, tumbling across: `spin` frames per turn of `quarters`. */
233function blown(kind: {
234  arrival: string
235  names: string[]
236  rows: readonly string[]
237  colors: Record<string, number>
238  speed: number
239  spin: number
240  quarters: number
241}): Kind {
242  const turns = [0, 1, 2, 3].map(q => turn(kind.rows, q))
243  return {
244    arrival: kind.arrival,
245    names: kind.names,
246    layer: 'air',
247    length: w => Math.ceil((w + 16) / kind.speed),
248    draw({ groundY, sprite }, t, seed) {
249      const shape = turns[(Math.floor(t / kind.spin) * kind.quarters) % 4]!
250      const cx = Math.round(-8 + t * kind.speed)
251      const cy = Math.floor(groundY * (0.3 + hash(seed + 1) * 0.35)) + Math.round(Math.sin(t / 6) * 2)
252      sprite(shape, kind.colors, cx - (shape[0]!.length >> 1), cy - (shape.length >> 1))
253    },
254  }
255}
256
257const SKIN = 0xe8b796
258const COAT = 0xe0b030
259const BOOTS = 0x3a3f4a
260const SHOOTING = 0xffffff
261// A bird, wings up and level.
262const BIRD_UP = ['B.B', '.B.']
263const BIRD_LEVEL = ['BBB']
264const BIRD_COLORS: Record<string, number> = { B: 0x2b2f3a }
265const FLOCK_DY = [0, -2, 2]
266// A far-off plane and the beacon that blinks on it.
267const PLANE = 0xd8dce4
268const BEACON = 0xff3b30
269// An umbrella over a Handle: open, and blown inside out.
270const UMBRELLA_OPEN = ['.RRR.', 'RRRRR', '..H..']
271const UMBRELLA_BLOWN = ['R...R', '.RRR.', '..H..']
272const UMBRELLA_COLORS: Record<string, number> = { R: 0xc8423a, H: BOOTS }
273// A diamond Kite with a yellow Heart, on a String.
274const KITE = ['.K.', 'KHK', '.K.']
275const KITE_COLORS: Record<string, number> = { K: 0xd8443a, H: 0xf2c94c }
276const STRING = 0xd8d2c0
277// A duck facing left, 5 by 4: Green head, Orange bill, White body with an upturned tail,
278// webbed Feet that step as it waddles. Only the feet change, so the tail holds still.
279const DUCK = [
280  ['.G..W', 'OGWWW', '..WWW', '..F.F'],
281  ['.G..W', 'OGWWW', '..WWW', '...F.'],
282]
283const DUCK_COLORS: Record<string, number> = { G: 0x2f6b3a, O: 0xe8a23a, W: 0xf0ece0, F: 0xd8862a }
284// A cat, dark against the twilight: walking right, in two steps, and sitting facing
285// out; its tail and its eyes, which catch the light, are drawn apart.
286const CAT_WALK = [
287  ['K..K', '.KKK', '.K.K'],
288  ['K..K', '.KKK', '..K.'],
289]
290const CAT_SIT_ROWS = ['K.K', 'KKK', 'KKK']
291const CAT_COLORS: Record<string, number> = { K: 0x2c2830 }
292const CAT_EYES = 0x9be36a
293// An owl, 3 by 3, its yellow eyes drawn apart so they can blink and look about.
294const OWL = ['B.B', 'BBB', 'BBB']
295const OWL_COLORS: Record<string, number> = { B: 0x6b5440 }
296const OWL_EYES = 0xffd23a
297const OWL_LOOKS = [[0, 2], [0, 1], [1, 2]] // eyes ahead, left, right
298
299const KINDS: Record<VisitorKind, Kind> = {
300  // A few birds flap across a fair sky, one way or the other.
301  birds: {
302    arrival: 'Here come some birds.',
303    names: ['bird'],
304    layer: 'air',
305    length: w => Math.ceil((w + 16) / BIRD_SPEED),
306    draw({ w, groundY, sprite }, t, seed) {
307      const dir = heading(seed)
308      const lead = across(w, t, BIRD_SPEED, dir)
309      const y0 = 2 + Math.floor(hash(seed + 1) * groundY * 0.35) + Math.round(Math.sin(t / 10))
310      const flock = hash(seed + 3) < 0.5 ? 2 : 3
311      for (let i = 0; i < flock; i++) {
312        const [bx, by] = [Math.round(lead - dir * i * 4), y0 + FLOCK_DY[i]!]
313        if (((t >> 2) + i) % 2 === 0) sprite(BIRD_UP, BIRD_COLORS, bx - 1, by - 1)
314        else sprite(BIRD_LEVEL, BIRD_COLORS, bx - 1, by)
315      }
316    },
317  },
318
319  // A cat climbs to the roof's peak, sits a while with its tail curling, and goes on.
320  cat: {
321    arrival: 'A cat is out on the roof.',
322    names: ['cats'],
323    layer: 'roof',
324    length: () => CAT_UP + CAT_SIT + CAT_DOWN,
325    draw({ hx, dot, sprite, shade, roofTop }, t) {
326      if (t >= CAT_UP && t < CAT_UP + CAT_SIT) {
327        const [x, peak] = [hx + 1, roofTop(hx + 2)]
328        sprite(CAT_SIT_ROWS, CAT_COLORS, x, peak - 3)
329        if (t % 64 >= 2) for (const dx of [0, 2]) dot(x + dx, peak - 2, CAT_EYES)
330        dot(x + 3, peak - (Math.floor(t / 8) % 2 === 0 ? 1 : 2), shade(CAT_COLORS.K!))
331        return
332      }
333      const cx = Math.round(hx - 1 + (t < CAT_UP ? t : t - CAT_SIT) * CAT_SPEED)
334      if (cx <= hx + 6) sprite(CAT_WALK[Math.floor(t / 3) % 2]!, CAT_COLORS, cx - 2, roofTop(cx) - 3)
335    },
336  },
337
338  // A shooting star streaks down and fades, behind the clouds.
339  star: {
340    arrival: 'Here comes a shooting star.',
341    names: ['stars', 'shooting-star', 'shootingstar'],
342    layer: 'sky',
343    length: () => STAR_FALL + STAR_FADE,
344    draw({ w, groundY, dot }, t, seed) {
345      const dir = heading(seed)
346      const step = Math.min(t, STAR_FALL)
347      const headX = Math.floor(w * (0.2 + 0.6 * hash(seed))) + step * 2 * dir
348      const headY = Math.floor(hash(seed + 1) * groundY * 0.3) + step
349      const fade = t <= STAR_FALL ? 1 : 1 - (t - STAR_FALL) / STAR_FADE
350      for (let j = Math.min(6, step * 2); j >= 1; j--) dot(headX - dir * j, headY - Math.round(j / 2), SHOOTING, (1 - j / 7) * fade * 0.8)
351      dot(headX, headY, SHOOTING, fade)
352    },
353  },
354
355  // An owl keeps watch from the roof's peak, blinking and looking about, then flies off.
356  owl: {
357    arrival: 'An owl lands on the roof.',
358    names: ['owls'],
359    layer: 'roof',
360    length: () => OWL_FRAMES,
361    draw({ hx, dot, sprite, roofTop }, t) {
362      const away = Math.max(0, Math.floor((t - (OWL_FRAMES - OWL_LEAVE)) / 2))
363      const [x, y] = [hx + 1 + away, roofTop(hx + 2) - 3 - away]
364      sprite(OWL, OWL_COLORS, x, y)
365      const isBlinking = t % 48 < 2 || (t % 240 >= 6 && t % 240 < 8)
366      if (isBlinking || away > 0) return
367      for (const dx of OWL_LOOKS[Math.floor(t / 96) % 3]!) dot(x + dx, y + 1, OWL_EYES)
368    },
369  },
370
371  // Someone by the house flies a kite; the wind leans it over, harder the fuller the context.
372  kite: {
373    arrival: 'Someone is out flying a kite.',
374    names: ['kites'],
375    layer: 'air',
376    length: () => KITE_FRAMES,
377    draw({ w, groundY, s, door, dot, sprite, shade, person }, t) {
378      const x = door + 5
379      person(x, false)
380      const reach = Math.min(w * 0.5, groundY * 0.7) * clamp01(Math.min(t, KITE_FRAMES - t) / KITE_REEL)
381      const lean = 0.35 + s * 0.8
382      const [handX, handY] = [x + 1, groundY - 2]
383      const kx = Math.round(handX + Math.sin(lean) * reach + Math.sin(t / 7) * 1.5)
384      const ky = Math.round(handY - Math.cos(lean) * reach + Math.sin(t / 5))
385      const n = Math.max(Math.abs(kx - handX), Math.abs(ky - handY))
386      for (let i = 1; i < n; i += 2) {
387        dot(Math.round(handX + ((kx - handX) * i) / n), Math.round(handY + ((ky - handY) * i) / n), STRING, 0.6)
388      }
389      for (let j = 1; j <= 3; j++) dot(kx + Math.round(j * 0.5 + Math.sin(t / 3 + j) * 0.6), ky + 1 + j, shade(KITE_COLORS.H!))
390      sprite(KITE, KITE_COLORS, kx - 1, ky - 1)
391    },
392  },
393
394  // A plane far off, its beacon blinking and its contrail fading behind it.
395  plane: {
396    arrival: 'Here comes a plane.',
397    names: ['planes', 'airplane', 'aeroplane'],
398    layer: 'sky',
399    length: w => Math.ceil((w + 40) / PLANE_SPEED),
400    draw({ w, groundY, light, frame, dot, shade }, t, seed) {
401      const dir = heading(seed)
402      const x = Math.round(across(w, t, PLANE_SPEED, dir))
403      const y = 1 + Math.floor(hash(seed + 1) * groundY * 0.2)
404      for (let j = 2; j < 30; j++) dot(x - dir * j, y, 0xffffff, (0.15 + 0.35 * light) * (1 - j / 30))
405      dot(x, y, shade(PLANE))
406      dot(x - dir, y, frame % 8 < 4 ? BEACON : shade(PLANE))
407    },
408  },
409
410  // Someone walks out under an umbrella; in heavy rain it blows inside out halfway and they run.
411  umbrella: {
412    arrival: 'Someone is heading out under an umbrella.',
413    names: ['umbrellas', 'person'],
414    layer: 'air',
415    length: w => Math.ceil((w + 8) / WALK_SPEED),
416    draw({ w, groundY, s, door, sprite, person }, t) {
417      const mid = Math.max(door, Math.round(w * 0.55))
418      const flipAt = (mid - door) / WALK_SPEED
419      const isBlown = s >= HEAVY && t >= flipAt
420      const x = Math.round(isBlown ? mid + (t - flipAt) * RUN_SPEED : door + t * WALK_SPEED)
421      person(x, Math.floor(t / (isBlown ? 1 : 2)) % 2 === 1)
422      sprite(isBlown ? UMBRELLA_BLOWN : UMBRELLA_OPEN, UMBRELLA_COLORS, x - 2, groundY - 6)
423    },
424  },
425
426  // A duck waddles through the rain, glad of it.
427  duck: {
428    arrival: 'Here comes a duck.',
429    names: ['ducks'],
430    layer: 'air',
431    length: w => Math.ceil((w + 12) / DUCK_SPEED),
432    draw({ w, groundY, sprite }, t) {
433      sprite(DUCK[Math.floor(t / 4) % 2]!, DUCK_COLORS, Math.round(across(w, t, DUCK_SPEED, -1)), groundY - 4)
434    },
435  },
436
437  // Whatever the gale picked up tumbles past.
438  cow: blown({
439    arrival: 'Here comes a cow.',
440    names: ['cows'],
441    // Facing right, 8 by 4: White, Black patches, Pink snout, Legs.
442    rows: ['......WW', 'WBWWBWWP', 'WWBWWW..', 'L.L..L.L'],
443    colors: { W: 0xf4f1e8, B: 0x26221f, P: 0xf0a3a8, L: 0x5a4a40 },
444    speed: 0.9,
445    spin: 6,
446    quarters: 2,
447  }),
448  bike: blown({
449    arrival: 'Is that a bike?',
450    names: ['bikes', 'bicycle'],
451    // 7 by 5: blacK saddle and handlebar, a red Frame, twO wheels.
452    rows: ['.K...K.', '..FFFF.', 'OOOFOOO', 'O.O.O.O', 'OOO.OOO'],
453    colors: { K: 0x2a2a2a, F: 0xd04a3a, O: 0x3a3a3a },
454    speed: 0.8,
455    spin: 4,
456    quarters: 1,
457  }),
458  door: blown({
459    arrival: 'There goes a shed door.',
460    names: ['doors', 'shed-door'],
461    // 3 by 6, with a brass Knob.
462    rows: ['DDD', 'DDD', 'DDD', 'DDK', 'DDD', 'DDD'],
463    colors: { D: 0x9b6a3f, K: 0xe8c860 },
464    speed: 0.7,
465    spin: 5,
466    quarters: 1,
467  }),
468  'lost-umbrella': blown({
469    arrival: 'An umbrella blows past. Someone will miss that.',
470    names: ['brolly'],
471    // The umbrella from the rain, 5 by 5, with nobody under it.
472    rows: ['.RRR.', 'RRRRR', '..H..', '..H..', '.HH..'],
473    colors: UMBRELLA_COLORS,
474    speed: 1,
475    spin: 3,
476    quarters: 1,
477  }),
478}
479
480// Three anchor palettes; storminess 0..0.5 blends clear→overcast, 0.5..1 overcast→storm.
481type Pal = { top: number; bottom: number; cloud: number; shade: number; ground: number }
482
483const SKY: Pal[] = [
484  { top: 0x4f8fd9, bottom: 0xa8d8f0, cloud: 0xf4f6f8, shade: 0xc9d3de, ground: 0x5d8a4a },
485  { top: 0x6f7f90, bottom: 0xa9b3bd, cloud: 0xb7bec7, shade: 0x8b939e, ground: 0x4a6b40 },
486  { top: 0x161a24, bottom: 0x353c4b, cloud: 0x4a505c, shade: 0x2e333d, ground: 0x26331f },
487]
488
489// The same three, after dark.
490const NIGHT: Pal[] = [
491  { top: 0x0a1030, bottom: 0x22305a, cloud: 0x3a4466, shade: 0x262d48, ground: 0x1a2a1c },
492  { top: 0x14171f, bottom: 0x2a2f3c, cloud: 0x3a3f4c, shade: 0x262a33, ground: 0x161f15 },
493  { top: 0x08090d, bottom: 0x161920, cloud: 0x2a2e37, shade: 0x1a1d24, ground: 0x0e140d },
494]
495
496function blend(anchors: Pal[], s: number): Pal {
497  const [clear, gray, storm] = anchors as [Pal, Pal, Pal]
498  const [a, b, t] = s < 0.5 ? [clear, gray, s * 2] : [gray, storm, (s - 0.5) * 2]
499  return {
500    top: mix(a.top, b.top, t),
501    bottom: mix(a.bottom, b.bottom, t),
502    cloud: mix(a.cloud, b.cloud, t),
503    shade: mix(a.shade, b.shade, t),
504    ground: mix(a.ground, b.ground, t),
505  }
506}
507
508function palette(s: number, hour: number): Pal {
509  const day = blend(SKY, s)
510  const night = blend(NIGHT, s)
511  const light = daylight(hour)
512  const warm = glow(hour) * (1 - s) // dawn and dusk colors, hidden by overcast
513  const pal: Pal = {
514    top: mix(night.top, day.top, light),
515    bottom: mix(night.bottom, day.bottom, light),
516    cloud: mix(night.cloud, day.cloud, light),
517    shade: mix(night.shade, day.shade, light),
518    ground: mix(night.ground, day.ground, light),
519  }
520  pal.top = mix(pal.top, 0x5b4a8a, warm * 0.45)
521  pal.bottom = mix(pal.bottom, 0xf28c5a, warm * 0.75)
522  pal.cloud = mix(pal.cloud, 0xf5b08a, warm * 0.5)
523  return pal
524}
525
526const BAYER = [0, 2, 3, 1]
527
528/** The row the ground starts on, in a scene `h` pixels tall. */
529export function groundLine(h: number): number {
530  return h - Math.max(2, Math.round(h * 0.12))
531}
532
533/**
534 * One frame of the scene as `w * h` pixels (0xRRGGBB), `s` the storminess 0..1
535 * `hour` the local time of day, 0..24, and `visitor` whoever is passing through.
536 * Pure: the same arguments draw the same frame.
537 */
538export function paint(w: number, h: number, s: number, frame: number, hour = 12, visitor: Visitor | null = null): Uint32Array {
539  const px = new Uint32Array(w * h)
540  const pal = palette(s, hour)
541  const light = daylight(hour)
542  const wind = 0.08 + s * 0.7
543  const groundY = groundLine(h)
544
545  // Lightning: in some 24-frame windows, a double flicker.
546  const win = Math.floor(frame / 24)
547  const strikeChance = s < STORM ? 0 : 0.25 + ((s - STORM) / (1 - STORM)) * 0.6
548  const strikeAt = Math.floor(hash(win * 7 + 1) * 18)
549  const inWindow = frame % 24
550  const isStrike = hash(win * 7) < strikeChance && (inWindow === strikeAt || inWindow === strikeAt + 2)
551  const flash = isStrike ? 0.45 : 0
552
553  // Sky: banded gradient, 2x2 ordered dither between bands.
554  const bands = 6
555  for (let y = 0; y < groundY; y++) {
556    for (let x = 0; x < w; x++) {
557      const t = (y / Math.max(1, groundY - 1)) * bands + BAYER[(y & 1) * 2 + (x & 1)]! / 4 - 0.375
558      const band = Math.max(0, Math.min(bands, Math.round(t)))
559      px[y * w + x] = mix(mix(pal.top, pal.bottom, band / bands), 0xd8dcf0, flash)
560    }
561  }
562
563  // Stars, twinkling, wherever the sky is dark and clear.
564  const starAlpha = (1 - light) * clamp01(1 - s * 2.2)
565  if (starAlpha > 0) {
566    const stars = Math.round(w * groundY * 0.03)
567    for (let i = 0; i < stars; i++) {
568      const x = Math.floor(hash(i * 5 + 101) * w)
569      const y = Math.floor(hash(i * 5 + 102) * groundY * 0.75)
570      const dim = hash(i * 5 + 103 + Math.floor(frame / 6) * 977) < 0.15
571      const p = y * w + x
572      px[p] = mix(px[p]!, 0xfff6d8, starAlpha * (dim ? 0.35 : 0.9))
573    }
574  }
575
576  // Whoever is visiting, drawn in turn at its layer.
577  const hasHouse = w >= 16 && groundY >= 8
578  const hx = Math.round(w * 0.18)
579  const roofTop = (x: number) => (hasHouse ? groundY - 7 + Math.max(0, hx + 1 - x, x - (hx + 4)) : groundY) // a three-step gable, or ground fallback
580  const t = visitor ? frame - visitor.start : -1
581  const guest = visitor && t >= 0 && t < visitLength(visitor.kind, w) ? KINDS[visitor.kind] : null
582  const scene: Scene = {
583    w,
584    groundY,
585    s,
586    light,
587    frame,
588    hx,
589    door: hx + 3,
590    roofTop,
591    dot(x, y, color, alpha = 1) {
592      if (x < 0 || y < 0 || x >= w || y >= groundY) return
593      px[y * w + x] = mix(px[y * w + x]!, color, alpha)
594    },
595    shade: color => mix(color, 0x000000, (1 - light) * 0.35),
596    sprite(rows, colors, x, y) {
597      for (let r = 0; r < rows.length; r++) {
598        for (let c = 0; c < rows[r]!.length; c++) {
599          const ch = rows[r]![c]!
600          if (ch !== '.') scene.dot(x + c, y + r, scene.shade(colors[ch]!))
601        }
602      }
603    },
604    person(x, isStriding) {
605      scene.dot(x, groundY - 3, scene.shade(SKIN))
606      scene.dot(x, groundY - 2, scene.shade(COAT))
607      for (const dx of isStriding ? [-1, 1] : [0]) scene.dot(x + dx, groundY - 1, scene.shade(BOOTS))
608    },
609  }
610  const drawVisitor = (layer: Layer) => {
611    if (guest?.layer === layer) guest.draw(scene, t, visitor!.seed)
612  }
613
614  // Sun and moon ride an arc from the left horizon to the right one.
615  const r = Math.max(2, Math.round(Math.min(w, groundY) * 0.09))
616  const arc = (t: number) => ({
617    cx: Math.round(w * (0.1 + 0.8 * t)),
618    cy: Math.round(groundY - 1 - Math.sin(Math.PI * t) * groundY * 0.72),
619  })
620  const disc = (cx: number, cy: number, color: number, alpha: number, cut?: { dx: number; dy: number }) => {
621    for (let y = cy - r; y <= cy + r; y++) {
622      for (let x = cx - r; x <= cx + r; x++) {
623        if (x < 0 || y < 0 || x >= w || y >= groundY || Math.hypot(x - cx, y - cy) > r) continue
624        if (cut && Math.hypot(x - cx - cut.dx, y - cy - cut.dy) <= r) continue
625        px[y * w + x] = mix(px[y * w + x]!, color, alpha)
626      }
627    }
628  }
629
630  const sunAlpha = clamp01(1 - s * 2.6)
631  const sunT = (hour - (SUNRISE - 0.5)) / (SUNSET - SUNRISE + 1)
632  if (sunAlpha > 0 && sunT >= 0 && sunT <= 1) {
633    const { cx, cy } = arc(sunT)
634    const color = mix(0xffd34d, 0xff7a3d, glow(hour))
635    disc(cx, cy, color, sunAlpha)
636    const glint = frame % 16 < 8 ? 1 : 0
637    for (const [dx, dy] of [[0, -1], [0, 1], [-1, 0], [1, 0]] as const) {
638      for (let k = r + 1; k <= r + 1 + glint; k++) {
639        const x = cx + dx * k
640        const y = cy + dy * k
641        if (x >= 0 && y >= 0 && x < w && y < groundY) px[y * w + x] = mix(px[y * w + x]!, 0xffe9a0, sunAlpha * 0.8)
642      }
643    }
644  }
645
646  const moonAlpha = clamp01(1 - s * 2.2) * (1 - light)
647  const moonT = (((hour - SUNSET + 24) % 24) + 0.5) / (24 - (SUNSET - SUNRISE) + 1)
648  if (moonAlpha > 0 && moonT <= 1) {
649    const { cx, cy } = arc(moonT)
650    disc(cx, cy, 0xe9e4c8, moonAlpha, { dx: Math.ceil(r * 0.7), dy: -Math.ceil(r * 0.4) })
651  }
652
653  drawVisitor('sky')
654
655  // Overcast ceiling with a wavy lower edge.
656  const ceiling = clamp01((s - 0.45) * 2.2) * groundY * 0.3
657  if (ceiling > 0) {
658    for (let x = 0; x < w; x++) {
659      const edge = ceiling + Math.sin((x + frame * wind) / 3) * 1.2 + Math.sin((x + frame * wind * 0.6) / 7) * 1.5
660      for (let y = 0; y < Math.min(groundY, edge); y++) px[y * w + x] = y > edge - 2 ? pal.shade : pal.cloud
661    }
662  }
663
664  // Drifting clouds: more, bigger and faster the fuller the context.
665  const count = s < 0.06 ? 0 : Math.min(12, Math.ceil(s * 12))
666  for (let k = 0; k < count; k++) {
667    const cw = Math.round(6 + hash(k * 3 + 11) * 8 + s * 8)
668    const ch = Math.max(3, Math.round(cw * 0.35))
669    const span = w + cw * 2
670    const speed = wind * (0.5 + hash(k * 3 + 12) * 0.7)
671    const cx0 = (((hash(k * 3 + 13) * span + frame * speed) % span) + span) % span - cw
672    const cy0 = 1 + Math.round(hash(k * 5 + 17) * groundY * (0.35 + s * 0.15))
673    for (let y = cy0 - ch; y <= cy0 + 1; y++) {
674      for (let dx = -cw; dx <= cw; dx++) {
675        const x = Math.round(cx0 + dx)
676        if (x < 0 || y < 0 || x >= w || y >= groundY) continue
677        // Three bumps on a flat base.
678        const bump = Math.max(
679          ch - Math.abs(dx) * 0.35,
680          ch * 1.25 - Math.abs(dx + cw * 0.3) * 0.6,
681          ch * 0.9 - Math.abs(dx - cw * 0.35) * 0.55,
682        )
683        if (cy0 - y > bump || Math.abs(dx) > cw - (y === cy0 + 1 ? 2 : 0)) continue
684        px[y * w + x] = y >= cy0 ? pal.shade : mix(pal.cloud, 0xffffff, flash)
685      }
686    }
687  }
688
689  // Rain, slanting with the wind.
690  const rain = rainfall(s)
691  if (rain > 0) {
692    const drops = Math.round(w * groundY * 0.05 * rain)
693    const color = mix(0x55657f, mix(0x8fa8c8, 0xc8d6ea, s), Math.max(light, flash))
694    for (let i = 0; i < drops; i++) {
695      const v = 1.6 + hash(i * 4 + 1) * 1.2 + s
696      const y = Math.floor((hash(i * 4 + 2) * groundY + frame * v) % groundY)
697      const x = Math.floor(((hash(i * 4 + 3) * w + y * wind * 0.5) % w + w) % w)
698      // A streak, longer and more slanted the heavier it falls.
699      const length = rain > 0.6 ? 3 : 2
700      for (let k = 0; k < length && y - k >= 0; k++) {
701        const i = (y - k) * w + Math.max(0, x - Math.round(k * wind * 0.5))
702        px[i] = k === 0 ? color : mix(color, px[i]!, 0.45)
703      }
704    }
705  }
706
707  drawVisitor('air')
708
709  // The bolt itself.
710  if (isStrike) {
711    let x = Math.floor(hash(win * 7 + 2) * w * 0.8 + w * 0.1)
712    for (let y = Math.floor(ceiling); y < groundY; y++) {
713      px[y * w + Math.max(0, Math.min(w - 1, x))] = 0xfff7c2
714      x += Math.floor(hash(win * 131 + y) * 3) - 1
715    }
716  }
717
718  // Ground, and a little house whose window lights up when it gets gloomy or dark.
719  for (let y = groundY; y < h; y++) {
720    for (let x = 0; x < w; x++) px[y * w + x] = y === groundY ? mix(pal.ground, 0xffffff, 0.04 + 0.08 * light) : pal.ground
721  }
722  if (hasHouse) {
723    const wall = mix(mix(0x8a5a44, 0x2a1d18, s), 0x140e0c, (1 - light) * 0.6)
724    const roof = mix(mix(0xb2483b, 0x3a1c1a, s), 0x1a0c0b, (1 - light) * 0.6)
725    for (let y = groundY - 4; y < groundY; y++) for (let x = hx; x < hx + 6; x++) px[y * w + x] = wall
726    for (let x = hx - 1; x <= hx + 6; x++) for (let y = roofTop(x); y <= groundY - 5; y++) px[y * w + x] = roof
727    const lit = (s > 0.3 || light < 0.7) && !(s >= STORM && frame % 40 === 0)
728    px[(groundY - 3) * w + hx + 2] = lit ? 0xffcf6b : mix(wall, 0x000000, 0.3)
729    px[(groundY - 3) * w + hx + 3] = lit ? 0xffcf6b : mix(wall, 0x000000, 0.3)
730  }
731
732  drawVisitor('roof')
733
734  return px
735}
736
737/** Packs a `columns * rows*2` pixel frame into Raster cells, two pixels per '▀'. */
738export function encode(px: Uint32Array, columns: number, rows: number): string {
739  const words = new Uint32Array(columns * rows * 3)
740  for (let r = 0; r < rows; r++) {
741    for (let c = 0; c < columns; c++) {
742      const o = (r * columns + c) * 3
743      words[o] = UPPER_HALF
744      words[o + 1] = px[r * 2 * columns + c]!
745      words[o + 2] = px[(r * 2 + 1) * columns + c]!
746    }
747  }
748  return base64(new Uint8Array(words.buffer))
749}
750
751const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
752
753/** Standard padded base64, by hand: not every runtime has Uint8Array#toBase64. */
754export function base64(bytes: Uint8Array): string {
755  const out: string[] = []
756  let i = 0
757  for (; i + 2 < bytes.length; i += 3) {
758    const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!
759    out.push(B64[n >> 18]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + B64[n & 63]!)
760  }
761  const rest = bytes.length - i
762  if (rest === 1) {
763    const n = bytes[i]! << 16
764    out.push(B64[n >> 18]! + B64[(n >> 12) & 63]! + '==')
765  } else if (rest === 2) {
766    const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)
767    out.push(B64[n >> 18]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + '=')
768  }
769  return out.join('')
770}
771
772// ---------------------------------------------------------------- hooks
773
774// Module-local animation state; a reload starts it over, which is fine.
775let frame = 0
776let target = 0 // storminess the context asks for
777let shown = 0 // storminess on screen, easing toward the target
778let size: { columns: number; rows: number } | null = null
779let lastColumns = DEFAULT_COLUMNS
780let hour = 12 // local time of day the scene shows
781let clockHour = 12 // the real one
782let pinned: number | null = null // a time /weather at set, or null to follow the clock
783let isAutoOpened = false // opened unasked once this load, where it would be a sidebar
784let visitor: Visitor | null = null // whoever is passing through now
785let visitAt = 0 // the frame the next visit is due
786
787/** Lets someone in now; they stay until out of sight, whatever the weather does meanwhile. */
788function visit(kind: VisitorKind) {
789  visitor = { kind, start: frame, seed: Math.floor(Math.random() * 0x7fffffff) }
790}
791
792async function syncClock($: EngineInterface) {
793  let offset: number | null = null
794  try {
795    const run = await $.process.run(['date', '+%z'], { timeoutMs: 5_000 })
796    if (run.exitCode === 0) offset = parseOffset(run.stdout)
797  } catch {}
798  clockHour = localHour(await $.clock.now(), offset ?? -new Date().getTimezoneOffset())
799  hour = pinned ?? clockHour
800  const next = dayPhase(hour)
801  await update($, phaseNow, () => next)
802}
803
804async function setPercent($: EngineInterface, pct: number) {
805  target = pct / 100
806  await update($, percent, () => Math.round(pct))
807}
808
809/** Reads the context afresh and shows its weather at once, with no easing. */
810async function resetWeather($: EngineInterface) {
811  const { context } = await $.session.usage()
812  await setPercent($, contextPercent(context))
813  shown = target
814}
815
816/** Opens the pane at the person's word; the reply says if it waits undrawn. */
817async function openPane($: EngineInterface, done: string): Promise<{ text: string }> {
818  const opened = await $.ui.open({ id: PANE, title: 'Weather', columns: DEFAULT_COLUMNS })
819  return { text: opened.isPlaced ? done : `${done} The window is not shown yet: ${opened.reason}` }
820}
821
822export const register: Register = on => {
823  on('session.start', async ($, e, next) => {
824    const result = await next(e)
825    await $.command.register({
826      name: 'weather',
827      description:
828        'Toggle the context weather window; "at 22:30" shows that time, "at now" follows the clock, "visit <name>" sends a visitor by',
829      argumentHint: '[at HH:MM|now|visit <visitor>]',
830    })
831    await resetWeather($)
832    pinned = await read($, override)
833    await syncClock($)
834    visitAt = frame + nextGap(Math.random())
835    $.clock.every(60_000, () => syncClock($))
836    $.clock.every(FRAME_MS, () => {
837      frame += 1
838      shown += (target - shown) * 0.04
839      if (visitor && frame - visitor.start >= visitLength(visitor.kind, size?.columns ?? lastColumns)) visitor = null
840      if (!visitor && frame >= visitAt) {
841        const hasHouse = size ? size.columns >= 16 && groundLine(size.rows * 2) >= 8 : lastColumns >= 16
842        visit(visitorFor(shown, hour, Math.random(), hasHouse))
843        visitAt = frame + nextGap(Math.random())
844      }
845      if (!size) return
846      const { columns, rows } = size
847      $.ui
848        .blit({ requestId: PANE, key: 'sky', cells: encode(paint(columns, rows * 2, shown, frame, hour, visitor), columns, rows) })
849        .then(r => {
850          if ('deny' in r && r.deny) size = null
851        })
852        .catch(() => {
853          size = null
854        })
855    })
856    return result
857  })
858
859  on('session.measure', async ($, e, next) => {
860    await setPercent($, contextPercent(e.context))
861    return next(e)
862  })
863
864  // A /clear or a resume swaps the conversation without a session.start, and
865  // the next measure waits for a turn: show the new conversation's sky and hour now.
866  on('classic.SessionStart', async ($, e, next) => {
867    const result = await next(e)
868    if (e.source === 'clear' || e.source === 'resume') {
869      await resetWeather($)
870      // The new conversation has its own /weather at, and its own phase atom.
871      pinned = await read($, override)
872      await syncClock($)
873    }
874    return result
875  })
876
877  on('command.run', { command: 'weather' }, async ($, e) => {
878    const at = /^at\s+(.+)$/.exec(e.args.trim())
879    if (at) {
880      const wanted = at[1]!.trim() === 'now' ? null : parseClock(at[1]!)
881      if (wanted === null && at[1]!.trim() !== 'now') return { text: `Not a time: ${at[1]}. Try /weather at 22:30.` }
882      pinned = wanted
883      await update($, override, () => wanted)
884      await syncClock($)
885      return openPane($, wanted === null ? 'The weather follows the clock again.' : `The weather shows ${at[1]!.trim()}.`)
886    }
887    const guest = /^visit\s+(\S+)$/.exec(e.args.trim())
888    if (guest) {
889      const kind = visitorNamed(guest[1]!)
890      if (!kind) return { text: `Nobody called ${guest[1]} visits. Try ${VISITORS.join(', ')}.` }
891      visit(kind)
892      return openPane($, KINDS[kind].arrival)
893    }
894    const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
895    if (isOpen) {
896      await $.ui.close({ id: PANE })
897      return { text: 'Weather window closed.' }
898    }
899    return openPane($, 'Weather window opened.')
900  })
901
902  // Open unasked only where the pane docks as a sidebar: the terminal's
903  // fullscreen layout, at least WIDE columns across. Only a drawing knows
904  // that, so the prompt's own sites look, pass through, and open the pane once.
905  for (const component of ['AbovePrompt', 'PromptHint'] as const) {
906    on('ui.render', { component }, ($, e, next) => {
907      if (!isAutoOpened && e.surface === 'terminal' && e.viewport?.isFullscreen === true && e.viewport.columns >= WIDE) {
908        isAutoOpened = true
909        void $.ui.open({ id: PANE, title: 'Weather', columns: DEFAULT_COLUMNS })
910      }
911      return next(e)
912    })
913  }
914
915  on('ui.close', { id: PANE }, ($, e, next) => {
916    size = null
917    return next(e)
918  })
919
920  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
921    const pct = (await read($, percent)) ?? 0
922    const phase = (await read($, phaseNow)) ?? 'day'
923    const columns = Math.max(1, Math.min(512, e.props.bodyColumns))
924    const room = e.props.scroll.bodyRows - 1
925    const rows = Math.max(2, Math.min(256, e.props.placement === 'dock' ? room : Math.min(room, 8)))
926    const caption = `${phase === 'day' ? '' : `${phase} · `}${forecast(pct)} · ${pct}% context`
927
928    if (e.surface !== 'terminal') {
929      // Raster is terminal-only for now; elsewhere the forecast alone. The
930      // terminal's mounted Raster, if any, keeps animating.
931      const { Text } = $.ui.resolve(e)
932      return <Text>{caption}</Text>
933    }
934    const { Box, Raster, Text } = $.ui.resolve(e)
935    lastColumns = columns
936    size = { columns, rows }
937
938    return (
939      <Box flexDirection="column">
940        <Raster key="sky" columns={columns} rows={rows} cells={encode(paint(columns, rows * 2, shown, frame, hour, visitor), columns, rows)} />
941        <Text dimColor wrap="truncate">
942          {caption}
943        </Text>
944      </Box>
945    )
946  })
947}
948
types/index.d.ts 12 lines
1export type DayPhase = 'dawn' | 'day' | 'dusk' | 'night'
2
3declare module 'claude-code' {
4  interface PluginState {
5    'context-weather': {
6      percent: number | null
7      phase: DayPhase | null
8      override: number | null
9    }
10  }
11}
12