SLOPSHOPPER

eidola

An Engram's scene that reacts to what Claude is doing, in a pane or the band above the prompt.

panebandguardcommandtoaststatus
v0.6.3MITupdated 2026-10-18AyeJK/eidola-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · eidola
│ ┃ Eidola ✕ › fix the failing auth test and add an audit log call │ ┃ ( -_- ) z │ ⏺ 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 │ │ › /eidola │ ⎿ eidola: Engrams: 0 bundled, 0 yours. │ ⎿ eidola: Surfaces: terminal │ ⎿ eidola: Pane: placed. │ ⎿ eidola: Pane state: shown=undefined placed=true │ ⎿ eidola: Switches: pane on · band on (hidden while the pane is op │ ⎿ eidola: Band hook last saw: terminal, survey=false, working=true │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Eidola
( -_- ) z
README

Eidola (mod prototype)

An Engram's scene in a pane or the band above the prompt that reacts to what Claude is doing. Eidola adds nothing to the prompt.

  • States: idle, thinking, working, attention, success, responding, error, waiting (asleep when no Engram is awake: the pane and band show the Wisp's scene, dimmed)
  • Commands: /eidola (open the pane and print diagnostics), /eidola place [pane|band|hide|status on|off] (open the Surfaces screen on the desktop, print the switches elsewhere, or set one), /eidola frame (toggle the awake Engram's HUD), /eidola mood idle|working|attention (set the mood by hand until the next prompt), /eidola ink (show a failure), /eidola media (toggle the media test), /awaken <engram>, /sleep, /engrams [engram] (open the picker, or one Engram's page, in the pane on the desktop; print the list elsewhere)
  • Make your own: /eidola new, /eidola remix <engram>, /eidola edit <engram>, /eidola publish <engram> start the Eidola skill (skills/eidola-engram/, also /eidola:eidola-engram) on that task: Claude makes the Engram plugin with you in ~/.claude/eidola/engrams/<id>/, lists it in the local marketplace eidola-local, checks it, installs it with your yes, and publishes it to a GitHub repo of yours only with your yes. edit and publish take your own Engrams; a bundled one is remixed first.
  • The Engram picker: click the triangle in the bottom-right corner of the pane, or of the band for a band-only Engram, to list the Engrams, filter them by where they draw and where they come from, and awaken one

Options

All are in /config once the mod is installed.

OptionDefaultWhat it does
paneonThe awake Engram draws in the pane, when it shows there, and the pane opens by itself. Off: the pane opens only when you run /eidola.
bandonThe awake Engram draws in the band above the prompt, when it shows there.
hideBandWhilePaneOpenonThe band steps aside while the pane is open, for an Engram that shows in the pane. A band-only Engram, like the Wisp, keeps its band.
statusLineonThe Engram's name and state, such as "Wisp · idle", in the status line.

One setting for every Engram: an Engram draws on a surface only if its switch is on and its shows lists it. One that shows only in the band never opens the pane by itself; /eidola still opens it, and it draws its band view there.

  • Bundled Engrams: wisp (default), a will-o'-the-wisp in a night fen that draws in the band, kraken and lich. Spirit, Skull, Moon, Sigil and Starfield were removed in 0.7.0: one that was awake is cleared at session start, and /eidola says so once.
  • kraken, something vast in deep water, and lich, a crowned skull of alchemical glyphs with soul-fire in its sockets. On desktop each is drawn live over a still backdrop and moves through three moods (idle, working, attention) without a cut; something going wrong makes the Kraken ink and scorches the Lich (/eidola ink to see it). Elsewhere each draws as a field scene, one per state.

Diagnostics

/eidola prints the attached surfaces, whether the pane is placed, whether the band is showing, and network probes run from wherever the session runs: eidola.app (a future hosted relay), example.com (control), api.github.com and a Shrine on 127.0.0.1:9743. In a cloud session that host is the cloud machine, not your computer.

/eidola media swaps the pane to three tiny clips (a GIF in an SVG drawn in a sandboxed frame, the same GIF drawn as a plain image, and a WebM in an SVG foreignObject) to see which ones animate on each surface. Run it again to go back.

Known limits: session.compact hooks don't run where an organization manages Claude Code unless the org lists the plugin. The bundled Engrams are packages in engrams/<id>/ (an engram.json and its vessel/ thumbnails, docs/spec/engram-format.md), loaded at session start and on /engrams; one that fails validation is skipped, and /eidola says why.

Install

At the prompt of a terminal session:

/plugin install eidola --marketplace AyeJK/eidola-mod

From a shell:

claude plugin install eidola --marketplace AyeJK/eidola-mod

In the desktop app, where /plugin does not run: click + next to the prompt box, then Plugins, Add marketplace with AyeJK/eidola-mod, then Add plugin.

Answer y to add the marketplace, then pick a scope (user scope loads it in every session).

Develop

Run these from this folder before pushing:

claude plugin validate .
npx -p typescript tsc -p .
claude plugin test .
node scripts/bake-thumbs.mjs --check
node scripts/export-engram.mjs --check

Each bundled Engram draws through its own drawing module, engrams/<id>/hooks/draw.tsx, given the hand-off an Engram plugin is given (docs/spec/engram-plugin.md). node scripts/export-engram.mjs <id> <folder> turns one into a standalone Engram plugin under a new id, and node scripts/check-engram.mjs <folder> checks any Engram plugin against the contract, printing each problem with its file and fix. The tests read a committed export (test/fixtures/exported-lich/) and the checker's view of the exported three (hooks/exports.data.ts); after changing how a bundled Engram draws, write both again: node scripts/export-engram.mjs lich test/fixtures/exported-lich --fixture --force && node scripts/export-engram.mjs --data (--fixture is the only way an export lands inside the mod, and only under test/). --check fails when either has drifted.

The Eidola skill (skills/eidola-engram/SKILL.md) runs from wherever the mod is installed and never writes inside it. It works through scripts/engram-home.mjs (where, list, new, remix, check, draws, sync, publish-prep), which keeps your Engrams in ~/.claude/eidola/ (EIDOLA_HOME moves it) and refuses an id that is taken. "Create from nothing" copies the starter, skills/eidola-engram/starter/ (tested by hooks/starter.test.ts; keep tests out of the starter's folder). The skill's evals are in evals/eidola-engram/: claude plugin eval . --case "eidola-*" --runs 1 --ablation none --no-publish --scaffold --allow-tools Write Edit "Bash(node:*)" "Bash(git:*)" "Bash(ls:*)" "Bash(cat:*)" "Bash(mkdir:*)" "Bash(cd:*)" "Bash(pwd:*)" "Bash(find:*)" (from a terminal where claude auth status says logged in; --scaffold runs the cases' own setup scripts, which stage a broken Engram and a local bare git repo standing in for GitHub).

The Kraken's and the Lich's picker thumbnails are stills of their live drawings, baked into engrams/<id>/vessel/thumb-*.svg, the files each engram.json names. After changing how one of them draws, bake them again with node scripts/bake-thumbs.mjs: it runs each drawing in the test runner, keeps its best-composed frame, and writes the stills. --check only checks that every thumbnail an Engram names exists and fits a desktop Svg, that no per-state frame is left in a package's vessel/, and that the tests' copy of each manifest (hooks/packages.data.ts) matches it.

tsc needs the engine's types at .claude-plugin/types/claude-code/index.d.ts (git-ignored). The engine writes them there when it loads the mod from this folder (claude --plugin-dir .). The render tests mount the pane and the band on terminal and desktop. A mount fails when a surface refuses the tree (an element it lacks, a prop it doesn't take), which is how an empty desktop pane shows up in a test.

Source 48 files
hooks/register.tsx 2931 lines
1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderElement } from 'claude-code'
3
4import type { EidolaAnnounced, EidolaHandoff, EidolaWhere, Mood, Preview, VesselState, VesselView } from '../types'
5import { RESTING_ID } from './engrams'
6import { BRASS, SCENE_IDS, SELF_SCENE, isSelfDrawn, withDefaults } from './engram-types'
7import type { Engram, EngramJson, SceneName } from './engram-types'
8import { ENGRAMS_DIR, loadEngrams } from './loader'
9import type { Skipped } from './loader'
10import { MANIFEST, checkThumbnail, validate } from './validate'
11import { CONTRACT, fallbackKey, faultLine, judge, lineOf, slotKey } from './handoff'
12import type { PillDraw, PillTone } from './engram-page'
13import type { Fault, Verdict } from './handoff'
14import { BLEND_STEPS, blendTestSvg } from './blend-test'
15import { MEASURE_EDGE, MEASURE_GROUND, MEASURE_HELP, REFERENCE_PX, bandReport, paneReport, referenceSvg } from './measure'
16import { mediaCases } from './media-test'
17import { NET_PROBES, PROBE_TIMEOUT_MS, describeOutcome } from './net-probe'
18import type { NetProbe, Outcome } from './net-probe'
19import {
20  DEFAULT_SURFACES,
21  OPTION_KEYS,
22  SWITCHES,
23  SWITCH_HELP,
24  drawsIn,
25  isSwitch,
26  readOnOff,
27  readStatusLine,
28  readSurfaces,
29  surfacesLine,
30  switchOf,
31  whereItDraws,
32} from './placement'
33import type { Drawing, Surfaces, Switch } from './placement'
34import { EMPTY, step } from './resolver'
35import type { Model, Signal, TurnEndReason } from './resolver'
36import { FACES, SPRITE_PALETTE, vesselSvg } from './sprite'
37import { renderScene } from './field'
38import { krakenWaterScene } from './kraken'
39import { voidScene } from './lich'
40import { fenScene } from './wisp'
41import { overdrawn } from './drawing'
42import type { Draw, DrawKit } from './drawing'
43import { draw as drawKraken } from '../engrams/kraken/hooks/draw'
44import { draw as drawLich } from '../engrams/lich/hooks/draw'
45import { draw as drawWisp } from '../engrams/wisp/hooks/draw'
46import { FRAME_GREY, FRAME_STATES, labelSvg } from './hud'
47import { SCENES } from './scenes'
48import {
49  FRESH_PREVIEW,
50  chip,
51  divider,
52  drawingLine,
53  engramPage,
54  header,
55  button,
56  label,
57  previewRows,
58  screenInner,
59  screenPad,
60  dropdown,
61} from './engram-page'
62import type { Els, Kit } from './engram-page'
63import { surfacesPage } from './surfaces-page'
64import type { SurfacesControl } from './surfaces-page'
65import { THEME } from './theme'
66import { BACKDROP, BAND_SCENE_PX, BAND_STAGE_PX, PX_PER_COLUMN, PX_PER_ROW, VEIL, sceneSize, stageSize } from './stage'
67
68const PANE = 'eidola'
69const STORE_KEY = 'engram'
70/** The name of a removed Engram that was awake, kept until `/eidola` has said so once. */
71const REMOVED_KEY = 'removed'
72/** Where the frame's toggles are kept between sessions: by Engram id. */
73const FRAME_KEY = 'frames'
74
75const viewAtom = atom({ plugin: 'eidola', key: 'view' } as const, {
76  state: 'idle',
77  detail: '',
78} as VesselView)
79// The drawings read the mood alone, so a tool's detail never redraws them.
80const moodAtom = atom({ plugin: 'eidola', key: 'mood' } as const, 'idle' as Mood)
81const engramAtom = atom({ plugin: 'eidola', key: 'engram' } as const, RESTING_ID as string | null)
82const mediaAtom = atom({ plugin: 'eidola', key: 'media' } as const, false)
83const measureAtom = atom({ plugin: 'eidola', key: 'measure' } as const, false)
84const blendAtom = atom({ plugin: 'eidola', key: 'blend' } as const, null as number | null)
85const liveAtom = atom({ plugin: 'eidola', key: 'live' } as const, null as Mood | null)
86const inkAtom = atom({ plugin: 'eidola', key: 'ink' } as const, 0)
87const frameAtom = atom({ plugin: 'eidola', key: 'frame' } as const, {} as Record<string, boolean>)
88const pickerAtom = atom({ plugin: 'eidola', key: 'picker' } as const, false)
89const pickerMenuAtom = atom({ plugin: 'eidola', key: 'pickerMenu' } as const, null as 'surface' | 'source' | null)
90const pickerSurfaceAtom = atom({ plugin: 'eidola', key: 'pickerSurface' } as const, 'all' as 'all' | 'pane' | 'band')
91const pickerSourceAtom = atom({ plugin: 'eidola', key: 'pickerSource' } as const, 'all' as 'all' | 'bundled' | 'yours')
92const pageAtom = atom({ plugin: 'eidola', key: 'page' } as const, null as string | null)
93const previewAtom = atom({ plugin: 'eidola', key: 'preview' } as const, FRESH_PREVIEW as Preview)
94const surfacesAtom = atom({ plugin: 'eidola', key: 'surfaces' } as const, false)
95const switchedAtom = atom({ plugin: 'eidola', key: 'switched' } as const, 0)
96const pluginsAtom = atom({ plugin: 'eidola', key: 'plugins' } as const, 0)
97const contractAtom = atom({ plugin: 'eidola', key: 'contract' } as const, CONTRACT)
98
99/** Whether an Engram's HUD frame shows: as the person toggled it, else as it ships. */
100function isFramed(frames: Record<string, boolean>, engram: Engram | undefined): boolean {
101  return engram ? (frames[engram.id] ?? engram.vessel.hud.show) : false
102}
103const moodAtAtom = atom({ plugin: 'eidola', key: 'moodAt' } as const, 0)
104const moodBeforeAtom = atom({ plugin: 'eidola', key: 'moodBefore' } as const, 'idle' as Mood)
105const inkAtAtom = atom({ plugin: 'eidola', key: 'inkAt' } as const, 0)
106const epochAtom = atom({ plugin: 'eidola', key: 'epoch' } as const, 0)
107
108const LABELS: Record<VesselState, string> = {
109  idle: 'Idle',
110  thinking: 'Thinking',
111  working: 'Working',
112  attention: 'Needs you',
113  success: 'Done',
114  responding: 'Replying',
115  error: 'Hit an error',
116  waiting: 'Waiting',
117  sleeping: 'Asleep',
118}
119
120type Timer = ReturnType<EngineInterface['clock']['after']>
121
122/** The state a drawing shows for a mood: its Vessel's idle, working or attention. */
123const MOOD_STATE: Record<Mood, VesselState> = { idle: 'idle', working: 'working', attention: 'attention' }
124
125// Resolver bookkeeping. Not drawn, so module variables are fine: a reload
126// resets them and the next event puts them right.
127let model: Model = EMPTY
128let generation = 0
129let pending: Timer | undefined
130const svgCache = new Map<string, string>()
131// Thumbnail files, read once each. null: the file couldn't be read.
132const fileCache = new Map<string, string | null>()
133/** Cell rows the live band takes: it fills the band's own minimum height. */
134const BAND_ROWS = 7
135/** The Wisp's band: tall enough for sky, lanterns, the boardwalk and the water under them. */
136const WISP_BAND_ROWS = 9
137/** The Lich's band: tall enough for brow, eyes, nose and teeth at the pane's scale. */
138const LICH_BAND_ROWS = 12
139
140// What the band hook saw and drew last, for /eidola. Not drawn from.
141type BandSeen = { surface: string; hasSurvey: boolean; isWorking: boolean; drew: 'engine' | 'strip' | 'strip+survey' }
142let lastBand: BandSeen | undefined
143/** Which clock each live drawing keeps, as it reported on starting: for /eidola. */
144const liveClocks = new Map<string, string>()
145// The scene last built for the pane and the band. A scene's loops are locked
146// to the clock when it is built, so it is rebuilt only when its state or
147// size changes; a redraw for anything else (a tool's detail) reuses it and
148// the surface keeps the running drawing.
149const lastScene = new Map<'pane' | 'band', { key: string; svg: string }>()
150
151function sceneFor(where: 'pane' | 'band', key: string, build: () => string): string {
152  const last = lastScene.get(where)
153  if (last?.key === key) {
154    return last.svg
155  }
156  const svg = build()
157  lastScene.set(where, { key, svg })
158  return svg
159}
160
161// The person's options. A change in /config reloads the module, so these
162// are set once per load in register().
163let surfaces: Surfaces = DEFAULT_SURFACES
164let isStatusLineOn = true
165
166// ── The registry ───────────────────────────────────────────────────────
167
168/**
169 * The frames Engrams removed in 0.7.0, by id: v2 draws scenes only. A session
170 * whose stored awake id is one of these starts with nothing awake, and
171 * `/eidola` says once that it was removed. Migration data, not Engrams.
172 */
173const REMOVED: Record<string, string> = {
174  spirit: 'Spirit',
175  skull: 'Skull',
176  moon: 'Moon',
177  sigil: 'Sigil',
178  starfield: 'Starfield',
179}
180
181// The Engrams loaded from engrams/<id>/ (hooks/loader.ts), by id, and the
182// packages skipped with why. Loaded at session start and on /engrams, and on
183// first need by anything that runs before session start; a reload of the
184// module loads again, so module variables are fine.
185let registry = new Map<string, Engram>()
186let skipped: Skipped[] = []
187let loading: Promise<void> | undefined
188
189/** Loads the bundled packages afresh. Never rejects: a failure leaves the registry empty. */
190function loadRegistry($: EngineInterface): Promise<void> {
191  loading = (async () => {
192    const out = await loadEngrams({ list: path => $.fs.list(path), read: path => $.fs.read(path) }, `${$.plugin.root}/${ENGRAMS_DIR}`)
193    // The Engram plugins found so far stay: they announced, and won't again until they reload.
194    for (const [id, engram] of plugged) {
195      if (!out.registry.has(id)) {
196        out.registry.set(id, engram)
197      }
198    }
199    registry = out.registry
200    skipped = out.skipped
201    // A package's thumbnails may have changed with it.
202    fileCache.clear()
203  })().catch(() => undefined)
204  return loading
205}
206
207/** The registry, loaded once if nothing has loaded it yet. */
208async function engramsOf($: EngineInterface): Promise<Map<string, Engram>> {
209  await (loading ?? loadRegistry($))
210  return registry
211}
212
213async function engramOf($: EngineInterface, id: string | null): Promise<Engram | undefined> {
214  const engrams = await engramsOf($)
215  return id === null ? undefined : engrams.get(id)
216}
217
218/** The Engrams in the order they are listed: the resting one first, then by id. */
219async function listed($: EngineInterface): Promise<Engram[]> {
220  const all = [...(await engramsOf($)).values()]
221  return [...all.filter(one => one.id === RESTING_ID), ...all.filter(one => one.id !== RESTING_ID)]
222}
223
224/**
225 * Drawn, dimmed, while nothing is awake, should the resting Engram's
226 * package not load: its scene under the mod's own name.
227 */
228const UNNAMED_REST: Engram = withDefaults({
229  spec: 2,
230  id: RESTING_ID,
231  name: 'Eidola',
232  version: '0.0.0',
233  author: 'eidola',
234  description: '',
235  rights: 'original',
236  vessel: { scene: 'wisp' },
237})
238
239/** The scene the resting Engram draws: what stands in where no other scene can. */
240const RESTING_SCENE: SceneName = 'wisp'
241
242/** The resting Engram: its scene, dimmed, is what shows while nothing is awake. */
243async function restingOf($: EngineInterface): Promise<Engram> {
244  return (await engramsOf($)).get(RESTING_ID) ?? UNNAMED_REST
245}
246
247// ── Engram plugins (docs/spec/engram-plugin.md) ────────────────────────
248//
249// An Engram plugin announces itself at its session.start ($.eidola.announce),
250// or Eidola's plugin.register hook finds it loading after Eidola. Either way
251// Eidola reads its engram.json, checks it with the one validator, and adds it
252// to the registry. Module variables: a reload of Eidola forgets them, and the
253// plugins announce again at the session.start that reload brings.
254
255/** Engram plugins' Engrams, by id. */
256const plugged = new Map<string, Engram>()
257/**
258 * Engram plugins whose engram.json didn't load, by folder, with the plugin's
259 * name: /eidola says why, and the Yours view shows each as not loading.
260 */
261const pluginSkipped = new Map<string, Skipped & { name: string }>()
262/**
263 * Engrams marked not loading, by id: their drawing threw, drew nothing or ran
264 * over its budget. Eidola draws their fallback and stops asking until the
265 * plugin announces again (it reloaded) or /engrams reads the Engrams afresh.
266 */
267const faults = new Map<string, Fault>()
268
269/** The built-in scene Eidola draws for an Engram: its own, or for an Engram plugin's the one it was remixed from. */
270function builtInScene(engram: Engram): SceneName | undefined {
271  if (!isSelfDrawn(engram)) {
272    return engram.vessel.scene as SceneName
273  }
274  const base = engram.remixOf === undefined ? undefined : registry.get(engram.remixOf)
275  return base && !isSelfDrawn(base) && (SCENE_IDS as readonly string[]).includes(base.vessel.scene) ? (base.vessel.scene as SceneName) : undefined
276}
277
278function message(error: unknown): string {
279  return error instanceof Error ? error.message : String(error)
280}
281
282/** A plugin.json or hooks.json, parsed; undefined when it can't be read. */
283async function readJson($: EngineInterface, path: string): Promise<Record<string, unknown> | undefined> {
284  try {
285    const value: unknown = JSON.parse((await $.fs.read(path)).replace(/^/, ''))
286    return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined
287  } catch {
288    return undefined
289  }
290}
291
292/**
293 * Reads an Engram plugin's engram.json from its folder, checks it, and adds
294 * its Engram to the registry; the Engram awake when the session started is
295 * woken if it announced late. Never rejects: what fails is in `issues`.
296 */
297async function adopt($: EngineInterface, root: string): Promise<EidolaAnnounced> {
298  const dir = root.replace(/[\\/]+$/, '')
299  const forget = () => {
300    for (const [id, one] of plugged) {
301      if (one.plugin?.root === dir) {
302        plugged.delete(id)
303        registry.delete(id)
304      }
305    }
306  }
307  const refuse = async (issues: Skipped['issues']): Promise<EidolaAnnounced> => {
308    forget()
309    pluginSkipped.set(dir, { folder: dir, issues, name })
310    await update($, pluginsAtom, n => n + 1)
311    return { contract: CONTRACT, engram: null, issues: issues.map(({ file, problem, fix }) => ({ file, problem, fix })) }
312  }
313  const manifest = await readJson($, `${dir}/.claude-plugin/plugin.json`)
314  const name = typeof manifest?.['name'] === 'string' ? manifest['name'] : ''
315  const hooks = await readJson($, `${dir}/hooks/hooks.json`)
316  const first = Array.isArray(hooks?.['modules']) ? (hooks['modules'] as unknown[])[0] : undefined
317  const module = typeof first === 'string' ? `hooks/${first.replace(/^\.\//, '')}` : 'hooks/register.tsx'
318  let text: string
319  try {
320    text = await $.fs.read(`${dir}/${MANIFEST}`)
321  } catch (error) {
322    return refuse([
323      {
324        rule: 'manifest',
325        file: MANIFEST,
326        problem: `engram.json couldn't be read (${message(error)}).`,
327        fix: "Put an engram.json at the top of the plugin's folder, beside .claude-plugin/ (docs/spec/engram-plugin.md).",
328      },
329    ])
330  }
331  let id: unknown
332  try {
333    id = (JSON.parse(text.replace(/^/, '')) as { id?: unknown }).id
334  } catch {
335    id = undefined
336  }
337  const bundled = [...(await engramsOf($)).values()].filter(one => one.plugin === undefined).map(one => one.id)
338  // An Engram plugin's folder is named by where it was installed, not by its id: the id stands alone.
339  const report = validate({ folder: typeof id === 'string' ? id : 'engram', files: { [MANIFEST]: text } }, { scenes: [SELF_SCENE], reserved: bundled, thumbnails: false })
340  if (report.errors.length) {
341    return refuse(report.errors)
342  }
343  const engram: Engram = { ...withDefaults(JSON.parse(text.replace(/^/, '')) as EngramJson), plugin: { name, root: dir, module } }
344  const other = plugged.get(engram.id)
345  if (other && other.plugin?.root !== dir) {
346    return refuse([{ rule: 'id', file: MANIFEST, problem: `The Engram plugin ${other.plugin?.name || other.plugin?.root} already has the id ${engram.id}.`, fix: 'Give this one its own id.' }])
347  }
348  forget()
349  plugged.set(engram.id, engram)
350  registry.set(engram.id, engram)
351  pluginSkipped.delete(dir)
352  faults.delete(engram.id)
353  for (const key of [...fileCache.keys()].filter(key => key.startsWith(`${engram.id}/`))) {
354    fileCache.delete(key)
355  }
356  for (const key of [...thumbCache.keys()].filter(key => key.startsWith(`${engram.id}:`))) {
357    thumbCache.delete(key)
358  }
359  await update($, pluginsAtom, n => n + 1)
360  // Awake when the session started, before the plugin had announced: it wakes now.
361  const stored = await $.store.get(STORE_KEY).catch(() => undefined)
362  if (stored === engram.id && (await read($, engramAtom)) === null) {
363    await update($, engramAtom, () => engram.id)
364  }
365  return { contract: CONTRACT, engram: engram.id, issues: [] }
366}
367
368/** What Eidola hands the awake Engram's plugin: the room it has, and the state it draws from. */
369async function handoffOf($: EngineInterface, engram: Engram, where: EidolaWhere, columns: number, rows: number): Promise<EidolaHandoff> {
370  return {
371    contract: CONTRACT,
372    engram: engram.id,
373    where,
374    columns,
375    rows,
376    mood: await read($, moodAtom),
377    moodBefore: await read($, moodBeforeAtom),
378    moodAt: await read($, moodAtAtom),
379    ink: await read($, inkAtom),
380    inkAt: await read($, inkAtAtom),
381    epoch: await read($, epochAtom),
382  }
383}
384
385/**
386 * Judges what came back from the hand-off (handoff.ts), with any fault the
387 * plugin reported meanwhile, and marks the Engram not loading on a fault.
388 */
389function verdictOf(engram: Engram, got: unknown, trace: Parameters<typeof judge>[0]['trace'], tookMs: number): Verdict {
390  const reported = faults.get(engram.id)
391  if (reported) {
392    return { fault: reported }
393  }
394  const verdict = judge({ engram: engram.id, plugin: engram.plugin?.name ?? '', module: engram.plugin?.module ?? 'hooks/register.tsx', got, trace, tookMs })
395  if ('fault' in verdict) {
396    faults.set(engram.id, verdict.fault)
397  }
398  return verdict
399}
400
401/**
402 * The drawing an Engram plugin's Engram gets, `cols` × `rows`: the plugin's
403 * own; else its fallback (the Engram it was remixed from, a still of its
404 * scene, or the resting sprite) in a slot a plugin above Eidola fills, or,
405 * marked not loading, in a slot no plugin fills.
406 */
407async function slotFor(
408  $: EngineInterface,
409  els: Pick<Elements['desktop'], 'Box' | 'Text' | 'Svg'>,
410  isRich: boolean,
411  engram: Engram,
412  cols: number,
413  rows: number,
414  where: EidolaWhere,
415  verdict: Verdict,
416): Promise<RenderElement> {
417  if ('tree' in verdict) {
418    return verdict.tree
419  }
420  const { Box, Text, Svg } = els
421  const key = 'fault' in verdict ? fallbackKey(engram.id) : slotKey(engram.id)
422  const state = MOOD_STATE[await read($, moodAtom)]
423  if (!isRich) {
424    return (
425      <Box key={key} width={cols} height={rows}>
426        <Text>{FACES[state]}</Text>
427      </Box>
428    )
429  }
430  const width = Math.max(16, cols * PX_PER_COLUMN)
431  const height = Math.max(16, rows * PX_PER_ROW)
432  const scene = builtInScene(engram)
433  if (scene) {
434    const view = where === 'pane' && height > width * 1.1 ? 'pane' : 'band'
435    const now = await $.clock.now()
436    const svg = sceneFor(where, `fallback:${engram.id}:${scene}:${view}:${state}:${width}x${height}`, () => renderScene(SCENES[scene][view](state, width, height), now))
437    return (
438      <Box key={key} width={cols} height={rows} overflow="hidden">
439        <Svg key={`fallback:${scene}`} source={svg} alt={`${engram.name}, drawn as the ${engram.remixOf} it was remixed from: ${LABELS[state]}`} width={width} height={height} isInteractive />
440      </Box>
441    )
442  }
443  const size = Math.max(16, Math.min(width, height, 160))
444  return (
445    <Box key={key} width={cols} height={rows} alignItems="center" justifyContent="center" backgroundColor={BACKDROP}>
446      <Svg key={`fallback:sprite:${state}`} source={spriteSvg(state, size)} alt={`${engram.name}, drawn as the resting sprite: ${LABELS[state]}`} width={size} height={size} isInteractive />
447    </Box>
448  )
449}
450
451/** /eidola's lines on Engram plugins: those that didn't load, and those marked not loading. */
452function pluginLines(): string[] {
453  return [
454    ...[...pluginSkipped.values()].flatMap(one => [`Engram plugin at ${one.folder} didn't load:`, ...one.issues.map(issue => `  ${issue.file}: ${issue.problem} ${issue.fix}`)]),
455    ...[...faults].map(([id, fault]) => {
456      const engram = plugged.get(id)
457      return `Not loading: ${engram?.name ?? id}, from ${engram?.plugin?.name || engram?.plugin?.root || 'its plugin'}. ${faultLine(fault)} Eidola draws ${engram && builtInScene(engram) ? `the ${engram.remixOf} it was remixed from` : 'the resting sprite'} instead.`
458    }),
459  ]
460}
461
462/** Where a fault is: its file, and its line where it has one. */
463function faultPlace(fault: Fault): string {
464  return fault.line === undefined ? fault.file : `${fault.file}:${fault.line}`
465}
466
467/** An Engram plugin that didn't load, by name: its plugin's, else its folder's. */
468function skippedName(one: Skipped & { name: string }): string {
469  return one.name || one.folder.split(/[\\/]/).pop() || one.folder
470}
471
472/**
473 * /eidola's Engrams line: how many are bundled, how many are yours (Engram
474 * plugins, those that don't load included), and each of yours not loading,
475 * with its file and line.
476 */
477function engramsLine(engrams: Map<string, Engram>): string {
478  const all = [...engrams.values()]
479  const bundled = all.filter(one => one.plugin === undefined).length
480  const yours = all.length - bundled + pluginSkipped.size
481  const broken = [
482    ...[...faults].map(([id, fault]) => `${plugged.get(id)?.name ?? id} at ${faultPlace(fault)}`),
483    ...[...pluginSkipped.values()].map(one => `${skippedName(one)} at ${one.issues[0]?.file ?? MANIFEST}`),
484  ]
485  return `Engrams: ${bundled} bundled, ${yours} yours${broken.length ? `, ${broken.length} not loading: ${broken.join('; ')}` : ''}.`
486}
487
488/** The built-in sprite for a state, at a size: the media test's control. */
489function spriteSvg(state: VesselState, size: number): string {
490  const key = `sprite:${state}:${size}`
491  let svg = svgCache.get(key)
492  if (svg === undefined) {
493    svg = vesselSvg(state, SPRITE_PALETTE, size)
494    svgCache.set(key, svg)
495  }
496  return svg
497}
498
499/** How much of the resting scene the veil hides while nothing is awake. */
500const RESTING_DIM = 0.55
501
502/** A scene dimmed under a veil of the dark: the resting Wisp's, while nothing is awake. */
503function dimmed(svg: string): string {
504  return svg.replace(/<\/svg>$/, `<rect width="100%" height="100%" fill="${VEIL}" opacity="${RESTING_DIM}"/></svg>`)
505}
506
507/**
508 * A still sized to fill a `width` × `height` box edge to edge: kept in
509 * proportion and centred, what overflows the box cut off, as a cover image.
510 */
511function filling(svg: string, width: number, height: number): string {
512  return svg.replace(/^<svg\b[^>]*>/, tag =>
513    tag
514      .replace(/\s(width|height|preserveAspectRatio)="[^"]*"/g, '')
515      .replace(/>$/, ` width="${width}" height="${height}" preserveAspectRatio="xMidYMid slice">`),
516  )
517}
518
519/** One probe, never rejecting: the line says what happened. */
520async function probeLine($: EngineInterface, probe: NetProbe): Promise<string> {
521  let timer: Timer | undefined
522  const timeout = new Promise<Outcome>(resolve => {
523    timer = $.clock.after(PROBE_TIMEOUT_MS, () => resolve({ kind: 'timeout' }))
524  })
525  const fetched = $.http
526    .fetch(probe.url, { method: 'GET' })
527    .then((res): Outcome => ({ kind: 'status', status: res.status }))
528    .catch((error: unknown): Outcome => ({
529      kind: 'error',
530      message: error instanceof Error ? error.message : String(error),
531    }))
532  const outcome = await Promise.race([fetched, timeout])
533  timer?.cancel()
534  return describeOutcome(probe, outcome)
535}
536
537function setStatus($: EngineInterface, text: string | undefined): void {
538  $.ui.status(isStatusLineOn ? text : undefined)
539}
540
541/**
542 * Where the awake Engram draws now (the resting one while nothing is awake),
543 * from the surfaces setting and whether the pane is open.
544 */
545async function drawingNow($: EngineInterface, isPaneOpen: boolean): Promise<Drawing> {
546  const engram = (await engramOf($, await read($, engramAtom))) ?? (await restingOf($))
547  return whereItDraws(surfaces, engram, isPaneOpen)
548}
549
550/** An Engram that doesn't show in the pane: opened by hand, the pane draws its band view. */
551function drawsBandViewInPane(engram: Engram | undefined): boolean {
552  return engram !== undefined && whereItDraws(surfaces, engram, true).paneView === 'band'
553}
554
555async function show($: EngineInterface, view: VesselView): Promise<void> {
556  const current = await read($, viewAtom)
557  if (current.state === view.state && current.detail === view.detail) {
558    return
559  }
560  await update($, viewAtom, () => view)
561  const engram = await engramOf($, await read($, engramAtom))
562  setStatus($, engram ? `${engram.name} · ${LABELS[view.state].toLowerCase()}` : undefined)
563}
564
565/** The sigil's size in cells: about 56 px square. */
566const SIGIL_COLS = 7
567const SIGIL_ROWS = 3
568/**
569 * Where the sigil's ring sits in its rows, in px from their top: from the
570 * state label's cap height to the foot of the detail line under it, as
571 * measured on the desktop, so it stands level with both lines of text.
572 */
573const SIGIL_SPAN = { top: 8, bottom: 52 }
574
575/** How busy a HUD's recording runs in a state. */
576function waveLevel(state: VesselState): 'idle' | 'working' | 'attention' {
577  return state === 'attention' ? 'attention' : state === 'thinking' || state === 'working' || state === 'responding' || state === 'error' ? 'working' : 'idle'
578}
579
580/** The frame's brass: its brackets and its quieter lines. */
581const FRAME_GOLD = BRASS
582
583/**
584 * The Vessel in a HUD frame: brackets at three corners, its state in its
585 * colour with the detail under it, the Engram's name at the top right, and
586 * a level meter in the bottom left.
587 */
588function framed(
589  els: Pick<Elements['desktop'], 'Box' | 'Text' | 'Client' | 'Svg'>,
590  tree: RenderElement,
591  cols: number,
592  rows: number,
593  view: VesselView,
594  awake: Engram | undefined,
595): RenderElement {
596  const { Box, Text, Client, Svg } = els
597  const own = awake?.vessel.hud.colours[view.state]
598  const look = { ...FRAME_STATES[view.state], colour: own?.label ?? FRAME_STATES[view.state].colour }
599  const detailColour = own?.detail ?? FRAME_GREY
600  const width = Math.max(4, cols - 6)
601  const clip = (text: string) => (text.length > width ? text.slice(0, width - 1) + '…' : text)
602  const detail = clip((view.detail || look.line).toLowerCase())
603  const hud = awake?.vessel.hud
604  const tag = (awake?.name ?? 'Eidola').toUpperCase()
605  const isBottom = hud?.layout === 'bottom'
606  const label = labelSvg(look.name, look.colour, hud?.label, isBottom ? 'small' : 'large')
607  const at = (key: string, top: number, left: number, child: RenderElement) => (
608    <Box key={key} position="absolute" top={top} left={left}>
609      {child}
610    </Box>
611  )
612  // A bracket is two thin bars of brass, the same length and weight each way:
613  // drawn as Boxes, not glyphs, so no font can make them uneven.
614  const brass = awake?.vessel.hud?.bracket ?? FRAME_GOLD
615  const bracket = (key: string, top: number, left: number, isRight: boolean, isBottom: boolean) => {
616    // A cell is 8 × 19 px: 8% of its height and 10% of its 2-cell width are both about 1.5 px.
617    const across = <Box key="across" width="100%" height="8%" backgroundColor={brass} />
618    const down = (
619      <Box key="down" flexDirection="row" height="92%" justifyContent={isRight ? 'flex-end' : 'flex-start'}>
620        <Box width="10%" height="100%" backgroundColor={brass} />
621      </Box>
622    )
623    return at(
624      key,
625      top,
626      left,
627      <Box flexDirection="column" width={2} height={1}>
628        {isBottom ? [down, across] : [across, down]}
629      </Box>,
630    )
631  }
632  return (
633    <Box width={cols} height={rows}>
634      {tree}
635      {bracket('frame-tl', 0, 0, false, false)}
636      {bracket('frame-tr', 0, cols - 2, true, false)}
637      {bracket('frame-bl', rows - 1, 0, false, true)}
638      {/* The bottom-right corner is the picker's triangle, drawn over every desktop pane. */}
639      {/* The state and its detail: large at the top left, or small on the bottom row, the detail at its right. */}
640      {isBottom
641        ? // Both in the band's last two rows, centred in them: the water, under the waterline.
642          at(
643            'frame-state',
644            rows - 2,
645            3,
646            <Box width={cols - 7} height={2} flexDirection="row" alignItems="center" justifyContent="space-between">
647              <Svg key={`frame-label:${view.state}:${awake?.vessel.hud?.label ?? 'bold'}:s`} source={label.svg} alt={look.name} width={label.width} height={label.height} />
648              <Text key="frame-detail" color={detailColour}>
649                {detail}
650              </Text>
651            </Box>,
652          )
653        : [
654            at(
655              'frame-state',
656              1,
657              3,
658              <Box width={Math.ceil(label.width / PX_PER_COLUMN)} height={2}>
659                <Svg key={`frame-label:${view.state}:${awake?.vessel.hud?.label ?? 'bold'}:l`} source={label.svg} alt={look.name} width={label.width} height={label.height} />
660              </Box>,
661            ),
662            at('frame-detail', 3, 3, <Text color={detailColour}>{detail}</Text>),
663          ]}
664      {cols >= 44 &&
665        awake?.vessel.hud?.tag !== 'none' &&
666        (awake?.vessel.hud?.tag === 'livecam'
667          ? at('frame-tag', 1, cols - 23, <Client key="frame-cam" module="./frame-cam.tsx" props={{ name: tag, camera: awake.vessel.hud.camera ?? 'CAM 01' }} width={20} height={2} />)
668          : awake?.vessel.hud?.tag === 'sigil'
669            ? at(
670                'frame-tag',
671                1,
672                cols - 3 - SIGIL_COLS,
673                <Client key="frame-sigil" module="./frame-sigil.tsx" props={{ colour: look.colour, level: waveLevel(view.state), cols: SIGIL_COLS, rows: SIGIL_ROWS, ...SIGIL_SPAN }} width={SIGIL_COLS} height={SIGIL_ROWS} />,
674              )
675            : at('frame-tag', 1, cols - tag.length - 3, <Text color={FRAME_GOLD}>{tag}</Text>))}
676      {rows >= 6 &&
677        awake?.vessel.hud?.meter !== 'none' &&
678        (awake?.vessel.hud?.meter === 'wave'
679          ? at(
680              'frame-wave',
681              rows - 3,
682              2,
683              <Client key="frame-wave" module="./frame-wave.tsx" props={{ colour: look.colour, level: waveLevel(view.state), cols: cols - 4 }} width={cols - 4} height={3} />,
684            )
685          : awake?.vessel.hud?.meter === 'sparks'
686            ? at(
687                'frame-sparks',
688                rows - 6,
689                2,
690                <Client key="frame-sparks" module="./frame-sparks.tsx" props={{ colour: look.colour, level: waveLevel(view.state), cols: cols - 4, rows: 5 }} width={cols - 4} height={5} />,
691              )
692          : at('frame-meter', rows - 2, 3, <Client key="frame-meter" module="./frame-meter.tsx" props={{ state: view.state, colour: look.colour }} width={12} height={1} />))}
693    </Box>
694  )
695}
696
697/** Something went wrong: count it, and when. */
698async function bumpInk($: EngineInterface): Promise<void> {
699  const at = await $.clock.now()
700  await update($, inkAtom, n => n + 1)
701  await update($, inkAtAtom, () => at)
702}
703
704// ── The bundled three's drawings ───────────────────────────────────────
705//
706// Each bundled Engram draws through its own drawing module,
707// engrams/<id>/hooks/draw.tsx, given the hand-off an Engram plugin is given
708// (hooks/drawing.ts). Eidola calls it directly: the code is its own. An
709// Engram plugin exported from one (scripts/export-engram.mjs) calls the same
710// module from its own hooks.
711
712/** The bundled Engrams' drawing modules, by scene. */
713const DRAWINGS: Record<SceneName, Draw> = { kraken: drawKraken, lich: drawLich, wisp: drawWisp }
714
715/** What a drawing is given besides the hand-off: the name, the clock, and the pane's or band's backdrop cache. */
716async function drawKit($: EngineInterface, engram: Engram, where: EidolaWhere): Promise<DrawKit> {
717  return { name: engram.name, now: await $.clock.now(), memo: (key, build) => sceneFor(where, key, build) }
718}
719
720/** A bundled Engram's creature, `cols` × `rows`, drawn by its drawing module from the hand-off. */
721async function drawBundled(
722  $: EngineInterface,
723  els: Elements['desktop'],
724  engram: Engram,
725  scene: SceneName,
726  where: EidolaWhere,
727  cols: number,
728  rows: number,
729): Promise<RenderElement> {
730  return DRAWINGS[scene](els, await handoffOf($, engram, where, cols, rows), await drawKit($, engram, where))
731}
732
733/** A drawing with one more child after its own: the band's corner over a creature's strip. */
734function withChild(tree: RenderElement, child: RenderElement): RenderElement {
735  const own = (tree as { children?: unknown }).children
736  const children = Array.isArray(own) ? own : own === undefined ? [] : [own]
737  return { ...tree, children: [...children, child] } as RenderElement
738}
739
740/**
741 * The rows a band drawing takes for a scene: the Lich's as tall as the band
742 * allows up to twelve (fewer, and its face is a smear), the Wisp's tall
743 * enough for sky, lanterns, boardwalk and water, the rest the band's own.
744 * An Engram plugin's band gets its remixOf scene's, so a remix draws as tall
745 * as the Engram it came from.
746 */
747function bandRows(scene: SceneName | undefined, hasSurvey: boolean, maxRows: number): number {
748  if (scene === 'lich') {
749    return hasSurvey ? BAND_ROWS : Math.max(BAND_ROWS, Math.min(LICH_BAND_ROWS, maxRows))
750  }
751  return scene === 'wisp' ? WISP_BAND_ROWS : BAND_ROWS
752}
753
754/**
755 * The Wisp in its fen, `cols` wide and its band's rows tall, by its drawing
756 * module, in its HUD when that is on. Drawn in the band, and in the pane when
757 * the pane is opened by hand.
758 */
759async function fenView($: EngineInterface, els: Elements['desktop'], awake: Engram, cols: number, where: 'pane' | 'band'): Promise<RenderElement> {
760  const rows = WISP_BAND_ROWS
761  const tree = await drawBundled($, els, awake, 'wisp', where, cols, rows)
762  return isFramed(await read($, frameAtom), awake) ? framed(els, tree, cols, rows, await read($, viewAtom), awake) : tree
763}
764
765/**
766 * An Engram's band view, drawn in the pane for one that doesn't show there:
767 * the Wisp's fen, or any other scene's band view as a still strip.
768 */
769async function bandView($: EngineInterface, els: Elements['desktop'], awake: Engram, cols: number, where: 'pane' | 'band'): Promise<RenderElement> {
770  if (awake.vessel.scene === 'wisp') {
771    return fenView($, els, awake, cols, where)
772  }
773  const { Svg } = els
774  const state = MOOD_STATE[await read($, moodAtom)]
775  const width = Math.max(96, cols * PX_PER_COLUMN - 4)
776  const height = BAND_SCENE_PX
777  const now = await $.clock.now()
778  const views = SCENES[builtInScene(awake) ?? RESTING_SCENE]
779  const scene = sceneFor(where, `band-view:${state}:${width}x${height}`, () => renderScene(views.band(state, width, height), now))
780  return <Svg key="scene:band-view" source={scene} alt={`${awake.name}: ${LABELS[state]}`} width={width} height={height} isInteractive />
781}
782
783// Every hook goes through here, and nothing here may break a tool call or
784// a turn: failures are swallowed and the Vessel just misses a beat.
785async function signal($: EngineInterface, s: Signal): Promise<void> {
786  try {
787    const out = step(model, s)
788    model = out.model
789    generation += 1
790    const mine = generation
791    pending?.cancel()
792    pending = undefined
793    if ((await read($, moodAtom)) !== model.mood) {
794      const mood = model.mood
795      const at = await $.clock.now()
796      const before = await read($, moodAtom)
797      await update($, moodBeforeAtom, () => before)
798      await update($, moodAtom, () => mood)
799      await update($, moodAtAtom, () => at)
800    }
801    // Something went wrong: the live Kraken inks; the Lich is scorched.
802    if ((s.kind === 'toolEnd' && !s.isOk) || (s.kind === 'turnEnd' && (s.reason === 'error' || s.reason === 'refusal'))) {
803      await bumpInk($)
804    }
805    await show($, out.view)
806    if (out.then) {
807      const later = out.then.view
808      pending = $.clock.after(out.then.ms, () => {
809        if (generation === mine) {
810          void show($, later).catch(() => undefined)
811        }
812      })
813    }
814  } catch {
815    // The Vessel is decoration; never let it cost the session anything.
816  }
817}
818
819async function setEngram($: EngineInterface, id: string | null): Promise<void> {
820  await $.store.set(STORE_KEY, id)
821  await update($, engramAtom, () => id)
822  const engram = await engramOf($, id)
823  setStatus($, engram ? `${engram.name} · awake` : undefined)
824  // An open pane is retitled with the new name; a closed one stays closed.
825  // One that doesn't show in the pane never keeps it open by itself: it closes.
826  try {
827    const panes = await $.ui.panes()
828    if (panes.some(one => one.id === PANE)) {
829      if (drawsBandViewInPane(engram)) {
830        await update($, pickerAtom, () => false)
831        await update($, pageAtom, () => null)
832        await $.ui.close({ id: PANE })
833      } else {
834        await $.ui.open({ id: PANE, title: PANE_TITLE })
835      }
836    }
837  } catch {
838    // The old title is only cosmetic.
839  }
840  // A different Engram may draw on different surfaces.
841  $.ui.invalidate('ui.render')
842}
843
844/** The pane's title: always Eidola, whichever Engram is awake; the status line names the Engram. */
845const PANE_TITLE = 'Eidola'
846
847// With "hide the band while the pane is open" on, the band steps aside while
848// the pane is placed. Every open and close redraws it to keep that true.
849async function isPanePlaced($: EngineInterface): Promise<boolean> {
850  try {
851    const panes = await $.ui.panes()
852    return panes.some(one => one.id === PANE && one.isPlaced)
853  } catch {
854    // Can't tell: show the band rather than risk showing no Vessel at all.
855    return false
856  }
857}
858
859async function openPane($: EngineInterface) {
860  const opened = await $.ui.open({ id: PANE, title: PANE_TITLE })
861  $.ui.invalidate('ui.render')
862  return opened
863}
864
865function listText(engrams: Engram[], active: string | null): string {
866  return engrams
867    .map(one => {
868      const mark = one.id === active ? ' (awake)' : ''
869      return `${one.id}${mark}: ${one.description}`
870    })
871    .join('\n')
872}
873
874/** The status line's switch in `/eidola place` and on the Surfaces screen: its option, and what it does. */
875const STATUS_OPTION = 'statusLine'
876const STATUS_HELP = "the Engram's name and state in the status line"
877
878/** `/eidola place`: the switches, and how to set one. */
879function placeText(): string {
880  const switches = SWITCHES.map(one => `  ${one} ${switchOf(surfaces, one) ? 'on' : 'off'}: ${SWITCH_HELP[one]}`).join('\n')
881  const status = `  status ${isStatusLineOn ? 'on' : 'off'}: ${STATUS_HELP}`
882  return `Surfaces: ${surfacesLine(surfaces)}.\n${switches}\n${status}\nSet one with /eidola place <switch> on|off, e.g. /eidola place band off.`
883}
884
885/** Each surfaces switch's field in the setting. */
886const SWITCH_FIELDS: Record<Switch, keyof Surfaces> = { pane: 'pane', band: 'band', hide: 'hideBand' }
887
888/**
889 * Writes one switch, as the person's own /config choice: the same option
890 * whether `/eidola place` or the Surfaces screen sets it. The engine reloads
891 * the module with it; until then this load takes the new value too, so the
892 * screen redraws with it at once. Resolves to the refusal, if any.
893 */
894async function writeSwitch($: EngineInterface, control: SurfacesControl, isOn: boolean): Promise<string | undefined> {
895  const option = control === 'status' ? STATUS_OPTION : OPTION_KEYS[control]
896  let written: Awaited<ReturnType<EngineInterface['config']['set']>>
897  try {
898    written = await $.config.set({ key: `eidola.${option}`, value: isOn })
899  } catch (error) {
900    return error instanceof Error ? error.message : String(error)
901  }
902  if ('deny' in written && written.deny !== undefined) {
903    return written.deny
904  }
905  if (control === 'status') {
906    isStatusLineOn = isOn
907    const engram = await engramOf($, await read($, engramAtom))
908    $.ui.status(isOn && engram ? `${engram.name} · ${LABELS[(await read($, viewAtom)).state].toLowerCase()}` : undefined)
909  } else {
910    surfaces = { ...surfaces, [SWITCH_FIELDS[control]]: isOn }
911  }
912  // The pane reads this count, so it redraws with the new value now.
913  await update($, switchedAtom, n => n + 1)
914  $.ui.invalidate('ui.render')
915  return undefined
916}
917
918// ── The Eidola skill (skills/eidola-engram/SKILL.md) ────────────────────
919//
920// /eidola new, remix, edit, fix and publish each start the skill on that task,
921// and so do the picker's and the Engram page's buttons (Create, Edit, Fix,
922// Remix, Publish with Claude):
923// the skill's own slash command, run with `$.command.run` (docs/spec/
924// engram-plugin.md, Starting Claude from a pane button), not awaited, since
925// it runs once the session is idle. Where the engine won't run it, the same
926// command is put in the prompt box for the person to send.
927
928/** The skill's folder name: a plugin's skill runs as /<plugin>:<skill>. */
929const SKILL = 'eidola-engram'
930const SKILL_COMMAND = `eidola:${SKILL}`
931
932/** The tasks /eidola starts the skill on, and what each needs. */
933const SKILL_TASKS = {
934  new: { needs: 'nothing', what: 'make a new Engram from nothing' },
935  remix: { needs: 'any', what: 'remix' },
936  edit: { needs: 'yours', what: 'change' },
937  fix: { needs: 'yours', what: 'fix' },
938  publish: { needs: 'yours', what: 'publish' },
939} as const
940
941/** What a bundled Engram can't be, for edit, fix and publish. */
942const IN_PLACE: Record<'edit' | 'fix' | 'publish', string> = { edit: 'changed', fix: 'fixed', publish: 'published' }
943type SkillTask = keyof typeof SKILL_TASKS
944
945function isSkillTask(value: string): value is SkillTask {
946  return Object.hasOwn(SKILL_TASKS, value)
947}
948
949/** The skill's command as this session lists it: /eidola:eidola-engram, or the bare name where the engine lists it so. */
950async function skillCommand($: EngineInterface): Promise<string> {
951  try {
952    const commands = await $.command.list()
953    const found =
954      commands.find(one => one.name === SKILL_COMMAND) ??
955      commands.find(one => one.name === SKILL && (one.plugin === undefined || one.plugin === 'eidola')) ??
956      commands.find(one => one.name.endsWith(`:${SKILL}`))
957    if (found) {
958      return found.name
959    }
960  } catch {
961    // The list out of reach: the name a plugin's skill runs by.
962  }
963  return SKILL_COMMAND
964}
965
966/**
967 * Starts the skill with `args`, once the session is idle. Never waits on it
968 * and never rejects. The engine refuses `$.command.run` from inside a
969 * `command.run` hook (it would wait on the turn that hook holds), so the run
970 * is made from a timer, after /eidola has answered.
971 */
972async function startSkill($: EngineInterface, args: string): Promise<string> {
973  const command = await skillCommand($)
974  $.clock.after(0, () => {
975    void $.command.run({ command, args }).catch(() => $.prompt.fill({ text: `/${command} ${args}` }).catch(() => undefined))
976  })
977  return command
978}
979
980/**
981 * /eidola new|remix|edit|fix|publish: the skill started on that task, or why
982 * not. Remix takes any Engram's id; edit, fix and publish only an Engram plugin's
983 * (one of the person's), since a bundled Engram lives in Eidola's own folder.
984 * Fix also takes an Engram plugin whose engram.json didn't load, by name or
985 * folder, and passes its folder, as the picker's Fix with Claude does.
986 */
987async function skillTaskText($: EngineInterface, task: SkillTask, raw: string): Promise<string> {
988  const [, given = '', ...rest] = raw.trim().split(/\s+/)
989  const spec = SKILL_TASKS[task]
990  if (spec.needs === 'nothing') {
991    const command = await startSkill($, `new ${raw.trim().slice(task.length).trim()}`.trim())
992    return `Starting the Eidola skill (/${command}) to ${spec.what}. Describe the creature when it asks.`
993  }
994  const id = given.toLowerCase()
995  const engrams = await listed($)
996  const list = listText(engrams, await read($, engramAtom))
997  if (!id) {
998    return `Say which Engram: /eidola ${task} <engram>.\n${list}`
999  }
1000  const engram = engrams.find(one => one.id === id)
1001  // fix also takes an Engram plugin whose engram.json didn't load, as the picker's Fix does: it has no id, so its folder goes.
1002  const unread = !engram && task === 'fix' ? skippedNamed(raw.trim().slice(task.length).trim()) : undefined
1003  if (unread) {
1004    const command = await startSkill($, `fix ${folderArg(unread.folder)}`)
1005    return `Starting the Eidola skill (/${command}) to fix the Engram plugin at ${unread.folder}.`
1006  }
1007  if (!engram) {
1008    const skipped = task === 'fix' ? [...pluginSkipped.values()].map(one => `${skippedName(one)}: didn't load, at ${one.folder}`) : []
1009    return `No Engram called "${id}". Engrams:\n${list}${skipped.length ? `\nEngram plugins that didn't load (/eidola fix <name or folder>):\n${skipped.join('\n')}` : ''}`
1010  }
1011  if (spec.needs === 'yours' && engram.plugin === undefined) {
1012    return `${engram.name} is bundled with Eidola: it can't be ${IN_PLACE[task as keyof typeof IN_PLACE]} in place. /eidola remix ${id} makes one of your own from it.`
1013  }
1014  const command = await startSkill($, [task, id, ...rest].join(' '))
1015  return `Starting the Eidola skill (/${command}) to ${spec.what} ${engram.name}.`
1016}
1017
1018/** Whether the session draws on the desktop app, where `/engrams` and `/eidola place` open their screens. */
1019async function isOnDesktop($: EngineInterface): Promise<boolean> {
1020  try {
1021    return (await $.session.surfaces()).includes('desktop')
1022  } catch {
1023    return false
1024  }
1025}
1026
1027// ── The picker and an Engram's page ────────────────────────────────────
1028
1029/**
1030 * Back from the picker (or a page) to the awake Engram: in the pane, or, for
1031 * one that doesn't show in the pane, back to the band, the pane closed.
1032 */
1033async function closePicker($: EngineInterface, awake: Engram | undefined): Promise<void> {
1034  await update($, pickerAtom, () => false)
1035  await update($, pickerMenuAtom, () => null)
1036  await update($, pageAtom, () => null)
1037  await update($, surfacesAtom, () => false)
1038  if (drawsBandViewInPane(awake)) {
1039    await $.ui.close({ id: PANE }).catch(() => undefined)
1040  }
1041}
1042
1043/** Whether the pane shows one of the mod's screens: the picker, a page or Surfaces. */
1044async function isScreenOpen($: EngineInterface): Promise<boolean> {
1045  return (await read($, pickerAtom)) || (await read($, pageAtom)) !== null || (await read($, surfacesAtom))
1046}
1047
1048/** Opens an Engram's page, its preview fresh: idle, nothing scorched. */
1049async function openPage($: EngineInterface, id: string): Promise<void> {
1050  await update($, previewAtom, () => FRESH_PREVIEW)
1051  await update($, pickerMenuAtom, () => null)
1052  await update($, surfacesAtom, () => false)
1053  await update($, pageAtom, () => id)
1054}
1055
1056/** Back from a page: to the picker it was opened over, else to the awake Engram. */
1057async function closePage($: EngineInterface, awake: Engram | undefined): Promise<void> {
1058  if (await read($, pickerAtom)) {
1059    await update($, pageAtom, () => null)
1060  } else {
1061    await closePicker($, awake)
1062  }
1063}
1064
1065/** The Surfaces button and link: the Surfaces screen opens over the screen they are on. */
1066async function showSurfaces($: EngineInterface): Promise<void> {
1067  await update($, surfacesAtom, () => true)
1068}
1069
1070/** Back from Surfaces: to the page or picker under it, else to the awake Engram. */
1071async function closeSurfaces($: EngineInterface, awake: Engram | undefined): Promise<void> {
1072  if ((await read($, pickerAtom)) || (await read($, pageAtom)) !== null) {
1073    await update($, surfacesAtom, () => false)
1074  } else {
1075    await closePicker($, awake)
1076  }
1077}
1078
1079/** A control on the Surfaces screen: its option written; a refusal said in a toast. */
1080async function setFromScreen($: EngineInterface, control: SurfacesControl, isOn: boolean): Promise<void> {
1081  const deny = await writeSwitch($, control, isOn)
1082  if (deny !== undefined) {
1083    $.ui.toast(`Couldn't change the ${control} switch here (${deny}). Set it in /config instead.`)
1084  }
1085}
1086
1087/** The Surfaces screen, its controls wired. */
1088function surfacesScreen($: EngineInterface, kit: Kit, awake: Engram | undefined): RenderElement {
1089  return surfacesPage(kit, {
1090    surfaces,
1091    isStatusLineOn,
1092    back: { onPress: () => void closeSurfaces($, awake) },
1093    onSet: (control, isOn) => void setFromScreen($, control, isOn),
1094  })
1095}
1096
1097/** A preview mood chip: the preview takes the mood; the session's is left alone. */
1098async function setPreviewMood($: EngineInterface, mood: Mood): Promise<void> {
1099  const at = await $.clock.now()
1100  await update($, previewAtom, was => ({ ...was, isError: false, mood, moodBefore: was.mood, moodAt: was.mood === mood ? was.moodAt : at }))
1101}
1102
1103/** The preview's Error button: the preview shows the error and its Engram takes it; the session's ink is left alone. */
1104async function previewError($: EngineInterface): Promise<void> {
1105  const at = await $.clock.now()
1106  await update($, previewAtom, was => ({ ...was, isError: true, ink: was.ink + 1, inkAt: at }))
1107}
1108
1109/** The picker's Surface dropdown: all Engrams, those that draw in a pane, those that draw in the band. */
1110const SURFACE_FILTERS = ['all', 'pane', 'band'] as const
1111type SurfaceFilter = (typeof SURFACE_FILTERS)[number]
1112const SURFACE_LABELS: Record<SurfaceFilter, string> = { all: 'All', pane: 'Pane', band: 'Band' }
1113
1114/** The picker's Source dropdown: all Engrams, those bundled with Eidola, yours. */
1115const SOURCE_FILTERS = ['all', 'bundled', 'yours'] as const
1116type SourceFilter = (typeof SOURCE_FILTERS)[number]
1117const SOURCE_LABELS: Record<SourceFilter, string> = { all: 'All', bundled: 'Bundled', yours: 'Yours' }
1118
1119/** Whether an Engram is one of the person's: an Engram plugin, not one bundled with Eidola. */
1120function isYours(engram: Engram): boolean {
1121  return engram.plugin !== undefined
1122}
1123
1124/** Whether an Engram is listed under both dropdowns: one that shows in both surfaces is listed under each. */
1125function isListed(engram: Engram, surface: SurfaceFilter, source: SourceFilter): boolean {
1126  const isSurface = surface === 'all' || drawsIn(engram)[surface]
1127  const isSource = source === 'all' || (source === 'yours' ? isYours(engram) : !isYours(engram))
1128  return isSurface && isSource
1129}
1130
1131/**
1132 * A press that starts the Eidola skill on a task, as /eidola does: Create,
1133 * Edit, Fix, Remix and Publish with Claude. The pane stays as it is, so the
1134 * Engram shows live while Claude works on it.
1135 */
1136function withClaude($: EngineInterface, args: string): () => void {
1137  return () => void startSkill($, args).catch(() => undefined)
1138}
1139
1140/** A folder, its slashes one way, no slash at its end, its case gone: Windows' folders ignore case. */
1141function sameFolder(folder: string): string {
1142  return folder.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
1143}
1144
1145/**
1146 * The Engram plugin that didn't load that `/eidola fix` names, by its
1147 * plugin's name, its folder's name or its folder, quoted or not: the
1148 * folder may hold a space. Its first word alone also names it: what follows
1149 * a name is dropped, since the skill takes only the folder.
1150 */
1151function skippedNamed(text: string): (Skipped & { name: string }) | undefined {
1152  const quoted = /^(["'])(.*?)\1/.exec(text)
1153  const tries = [quoted?.[2], text, text.split(/\s+/)[0]].filter((one): one is string => Boolean(one)).map(sameFolder)
1154  return [...pluginSkipped.values()].find(one => {
1155    const names = [one.name, one.folder.split(/[\\/]/).pop() ?? '', one.folder].filter(Boolean).map(sameFolder)
1156    return tries.some(tried => names.includes(tried))
1157  })
1158}
1159
1160/** A folder as one argument to the skill: quoted where it holds a space. */
1161function folderArg(folder: string): string {
1162  return /\s/.test(folder) ? `"${folder}"` : folder
1163}
1164
1165/** Back from the Yours view to every source: "or remix one". */
1166function showAll($: EngineInterface): () => void {
1167  return () => void update($, pickerSourceAtom, () => 'all')
1168}
1169
1170/** Thumbnails by Engram, view and size: a scene is costly to draw, so once each. */
1171const thumbCache = new Map<string, string>()
1172
1173/**
1174 * A still of an Engram at rest, `width` × `height` px, as it looks where it
1175 * draws: its pane view for one that shows in a pane (or both), its band view
1176 * for one that shows only in the band: its own still for the view where it
1177 * ships one, else its scene drawing that view.
1178 */
1179async function thumbFor($: EngineInterface, engram: Engram, view: 'pane' | 'band', width: number, height: number): Promise<{ svg: string; width: number }> {
1180  // Its own still for the view, where it ships one, fitted to the box by its
1181  // viewBox: read from its package the first time it is shown, checked by the
1182  // thumbnail rules then, and its scene drawn in place of one that fails.
1183  const file = engram.vessel.thumbnails[view]
1184  if (file) {
1185    const at = `${engram.id}/${file}`
1186    if (!fileCache.has(at)) {
1187      try {
1188        // An Engram plugin's stills are in its own folder's vessel/.
1189        const folder = engram.plugin ? engram.plugin.root : `${$.plugin.root}/${ENGRAMS_DIR}/${engram.id}`
1190        const text = await $.fs.read(`${folder}/vessel/${file}`)
1191        fileCache.set(at, checkThumbnail(file, text).length ? null : text)
1192      } catch {
1193        fileCache.set(at, null)
1194      }
1195    }
1196    const still = fileCache.get(at)
1197    if (still) {
1198      return { svg: filling(still, width, height), width }
1199    }
1200  }
hooks/engrams.ts 11 lines
1// The bundled Engrams are packages now, engrams/<id>/ in the mod, loaded at
2// session start by hooks/loader.ts. Their shape is hooks/engram-types.ts.
3// This holds no Engram data: only which one rests.
4
5/**
6 * The resting Engram: its scene, dimmed, is what the pane and band show while
7 * nothing is awake; it is awake in a session that has stored nothing yet, and
8 * `/awaken` alone wakes it.
9 */
10export const RESTING_ID = 'wisp'
11
hooks/engram-types.ts 199 lines
1// Engram spec v2 (docs/spec/engram-format.md): the shape of a package's
2// engram.json, and the registry's Engram, the same with every default
3// filled in. Pure: no `$`, nothing from 'claude-code'. The lists here are
4// what hooks/validate.ts checks against, and what the schema is tested
5// against.
6
7import type { VesselState } from '../types'
8
9/** The `spec` an engram.json must carry. */
10export const SPEC_VERSION = 2
11
12/** The scenes built into the mod (hooks/scenes.ts), which `vessel.scene` may name. */
13export const SCENE_IDS = ['kraken', 'lich', 'wisp'] as const
14export type SceneName = (typeof SCENE_IDS)[number]
15
16/**
17 * The scene an Engram plugin's engram.json names: its creature is drawn by
18 * the plugin itself (docs/spec/engram-plugin.md), not by the mod.
19 */
20export const SELF_SCENE = 'self'
21export type SelfScene = typeof SELF_SCENE
22
23/** Every value `vessel.scene` can take: a built-in scene, or `self` in an Engram plugin. */
24export const SCENE_NAMES = [...SCENE_IDS, SELF_SCENE] as const
25
26/** The places an Engram can draw: the pane, the band above the prompt, the local Shrine. */
27export const SHOW_PLACES = ['pane', 'band', 'shrine'] as const
28export type ShowPlace = (typeof SHOW_PLACES)[number]
29
30/** Where an Engram is made to draw: at least one place, each once. */
31export type Shows = ShowPlace[]
32
33/** The creator's word on the Engram: they made it, or they may share it. */
34export const RIGHTS = ['original', 'licensed'] as const
35export type Rights = (typeof RIGHTS)[number]
36
37/** The views a picker thumbnail can be for. */
38export const THUMB_VIEWS = ['pane', 'band'] as const
39export type ThumbView = (typeof THUMB_VIEWS)[number]
40
41export const HUD_METERS = ['bars', 'wave', 'sparks', 'none'] as const
42export const HUD_TAGS = ['name', 'livecam', 'sigil', 'none'] as const
43export const HUD_LAYOUTS = ['top', 'bottom'] as const
44export const HUD_LABELS = ['bold', 'serif', 'pixel'] as const
45
46/** The resolver's nine states, which key `vessel.hud.colours`. */
47export const VESSEL_STATES = [
48  'idle',
49  'thinking',
50  'working',
51  'waiting',
52  'responding',
53  'success',
54  'error',
55  'attention',
56  'sleeping',
57] as const satisfies readonly VesselState[]
58
59/** A state's own colours in the HUD: its label, and the detail under it. */
60export type HudColour = { label: string; detail: string }
61
62/** The HUD frame over the Vessel, as an engram.json gives it: every field optional. */
63export type Hud = {
64  /** On until the person toggles it (`/eidola frame`). */
65  show?: boolean
66  /** `bars`, a level meter in the corner; `wave`, a recording scrolling along the bottom; `sparks`, rising sparks; `none`. */
67  meter?: (typeof HUD_METERS)[number]
68  /** The corner tag: the Engram's `name`; a `livecam` stamp; a turning `sigil`; `none`. */
69  tag?: (typeof HUD_TAGS)[number]
70  /** The camera's name on a `livecam` tag. */
71  camera?: string
72  /** The state large at the `top` left, or small along the `bottom`. */
73  layout?: (typeof HUD_LAYOUTS)[number]
74  /** The state label's face. */
75  label?: (typeof HUD_LABELS)[number]
76  /** The corner brackets' colour, hex. */
77  bracket?: string
78  /** Its own colours per state, hex. */
79  colours?: Partial<Record<VesselState, HudColour>>
80}
81
82/** A package's engram.json, as the spec gives it. */
83export type EngramJson = {
84  /** Editors' hint; the mod ignores it. */
85  $schema?: string
86  spec: typeof SPEC_VERSION
87  /** Slug, 2-32 of a-z 0-9 -, equal to the folder's name. */
88  id: string
89  /** Up to 32 characters. */
90  name: string
91  /** Semver. */
92  version: string
93  author: string
94  /** Up to 160 characters. */
95  description: string
96  rights: Rights
97  /**
98   * An Engram plugin's: the id of the Engram it was remixed from. Eidola draws
99   * that one's scene while the plugin's own drawing can't (it throws, draws
100   * nothing or runs over its budget); the resting sprite when left out.
101   */
102  remixOf?: string
103  vessel: {
104    /** A built-in scene; `self` in an Engram plugin, which draws its own. */
105    scene: SceneName | SelfScene
106    /** Where it draws; all three when left out. */
107    shows?: Shows
108    /** Picker stills, file names in `vessel/`; the scene's own when left out. */
109    thumbnails?: Partial<Record<ThumbView, string>>
110    hud?: Hud
111  }
112  /** A free namespace: kept as it is, never read. */
113  extensions?: Record<string, unknown>
114}
115
116/** The HUD with every default filled in, but `camera` (`CAM 01` where drawn) and per-state colours (the mod's own). */
117export type FilledHud = Required<Omit<Hud, 'camera' | 'colours'>> & {
118  camera?: string
119  colours: Partial<Record<VesselState, HudColour>>
120}
121
122/** The frame's brass: the brackets' colour when an Engram names none. */
123export const BRASS = '#b8913a'
124
125export const HUD_DEFAULTS: Readonly<Required<Omit<Hud, 'camera' | 'colours'>>> = {
126  show: false,
127  meter: 'bars',
128  tag: 'name',
129  layout: 'top',
130  label: 'bold',
131  bracket: BRASS,
132}
133
134/**
135 * Where an Engram plugin lives, as Eidola found it: its plugin.json name,
136 * its folder, and its hooks module (for a "not loading" line).
137 */
138export type EngramPlugin = { name: string; root: string; module: string }
139
140/** An Engram in the registry: its engram.json with every default filled in. */
141export type Engram = {
142  id: string
143  name: string
144  version: string
145  author: string
146  description: string
147  rights: Rights
148  /** An Engram plugin's: the Engram it was remixed from, drawn while its own drawing can't be. */
149  remixOf?: string
150  /** Set for an Engram plugin's Engram: the plugin that draws it. */
151  plugin?: EngramPlugin
152  vessel: {
153    scene: SceneName | SelfScene
154    shows: Shows
155    thumbnails: Partial<Record<ThumbView, string>>
156    hud: FilledHud
157  }
158  extensions: Record<string, unknown>
159}
160
161/** The registry's Engram for a manifest that has passed validation. */
162export function withDefaults(json: EngramJson): Engram {
163  const hud = json.vessel.hud ?? {}
164  const filled: FilledHud = {
165    show: hud.show ?? HUD_DEFAULTS.show,
166    meter: hud.meter ?? HUD_DEFAULTS.meter,
167    tag: hud.tag ?? HUD_DEFAULTS.tag,
168    layout: hud.layout ?? HUD_DEFAULTS.layout,
169    label: hud.label ?? HUD_DEFAULTS.label,
170    bracket: hud.bracket ?? HUD_DEFAULTS.bracket,
171    colours: { ...hud.colours },
172  }
173  if (hud.camera !== undefined) {
174    filled.camera = hud.camera
175  }
176  const remix = json.remixOf === undefined ? {} : { remixOf: json.remixOf }
177  return {
178    id: json.id,
179    name: json.name,
180    version: json.version,
181    author: json.author,
182    description: json.description,
183    rights: json.rights,
184    ...remix,
185    vessel: {
186      scene: json.vessel.scene,
187      shows: [...(json.vessel.shows ?? SHOW_PLACES)],
188      thumbnails: { ...json.vessel.thumbnails },
189      hud: filled,
190    },
191    extensions: { ...json.extensions },
192  }
193}
194
195/** True for an Engram whose creature its own plugin draws (`vessel.scene: "self"`). */
196export function isSelfDrawn(engram: Engram | undefined): boolean {
197  return engram?.vessel.scene === SELF_SCENE
198}
199
hooks/loader.ts 100 lines
1// The Engram loader (Plan decision 7): lists the mod's engrams/ folder, reads
2// each package's engram.json and nothing else, checks it with the one
3// validator, and fills its defaults. A package that fails goes on the skipped
4// list with the validator's file, problem and fix; the rest are the registry.
5// Thumbnails are read later, on first use. It never throws.
6
7import type { FsEntry } from 'claude-code'
8
9import { withDefaults } from './engram-types'
10import type { Engram, EngramJson } from './engram-types'
11import { MANIFEST, validate } from './validate'
12import type { Issue, ValidateOptions } from './validate'
13
14/** The folder under the mod's root that holds the bundled packages. */
15export const ENGRAMS_DIR = 'engrams'
16
17/** What the loader reads through: `$.fs` in the mod, a stand-in in tests. */
18export type Disk = {
19  list: (path: string) => Promise<readonly FsEntry[]>
20  read: (path: string) => Promise<string>
21}
22
23/** A package that didn't load: its folder's name, and why. */
24export type Skipped = { folder: string; issues: Issue[] }
25
26/** The registry, by id, in the folders' order (by name), and what was skipped. */
27export type Loaded = { registry: Map<string, Engram>; skipped: Skipped[] }
28
29/** A folder the loader passes over: `_template` and the like, and hidden ones. */
30export function isIgnored(name: string): boolean {
31  return name.startsWith('_') || name.startsWith('.')
32}
33
34function message(error: unknown): string {
35  return error instanceof Error ? error.message : String(error)
36}
37
38/**
39 * Loads every package under `dir`. Never throws: a folder that can't be
40 * listed gives an empty registry and one skipped entry; a package that can't
41 * be read or fails validation is skipped with its issues.
42 */
43export async function loadEngrams(disk: Disk, dir: string, options: ValidateOptions = {}): Promise<Loaded> {
44  const registry = new Map<string, Engram>()
45  const skipped: Skipped[] = []
46  let entries: readonly FsEntry[]
47  try {
48    entries = await disk.list(dir)
49  } catch (error) {
50    skipped.push({
51      folder: ENGRAMS_DIR,
52      issues: [{ rule: 'manifest', file: `${ENGRAMS_DIR}/`, problem: `The Engrams folder couldn't be listed (${message(error)}).`, fix: 'Reinstall the mod: its engrams/ folder is missing or unreadable.' }],
53    })
54    return { registry, skipped }
55  }
56  try {
57    const folders = entries
58      .filter(entry => entry.kind === 'dir' && !isIgnored(entry.name))
59      .map(entry => entry.name)
60      .sort()
61    for (const folder of folders) {
62      const one = await loadOne(disk, `${dir}/${folder}`, folder, options)
63      if ('issues' in one) {
64        skipped.push(one)
65      } else if (registry.has(one.id)) {
66        // Folders differ only in case on a case-blind disk: the first stands.
67        skipped.push({ folder, issues: [{ rule: 'id', file: MANIFEST, problem: `Another package already has the id ${one.id}.`, fix: 'Give this one its own id, and rename its folder to match.' }] })
68      } else {
69        registry.set(one.id, one)
70      }
71    }
72  } catch (error) {
73    // Nothing above should throw; if it does, keep what loaded.
74    skipped.push({ folder: ENGRAMS_DIR, issues: [{ rule: 'manifest', file: `${ENGRAMS_DIR}/`, problem: `Loading stopped early (${message(error)}).`, fix: 'Run /engrams to load again.' }] })
75  }
76  return { registry, skipped }
77}
78
79/** One package: its Engram, or why it was skipped. */
80async function loadOne(disk: Disk, path: string, folder: string, options: ValidateOptions): Promise<Engram | Skipped> {
81  let text: string
82  try {
83    text = await disk.read(`${path}/${MANIFEST}`)
84  } catch (error) {
85    return {
86      folder,
87      issues: [{ rule: 'manifest', file: MANIFEST, problem: `engram.json couldn't be read (${message(error)}).`, fix: 'Add an engram.json at the top of the package folder, readable by Claude Code (docs/spec/engram-format.md).' }],
88    }
89  }
90  const report = validate({ folder, files: { [MANIFEST]: text } }, { ...options, thumbnails: false })
91  if (report.errors.length) {
92    return { folder, issues: report.errors }
93  }
94  try {
95    return withDefaults(JSON.parse(text.replace(/^/, '')) as EngramJson)
96  } catch (error) {
97    return { folder, issues: [{ rule: 'manifest', file: MANIFEST, problem: `engram.json couldn't be loaded (${message(error)}).`, fix: 'Check it against docs/spec/engram-format.md.' }] }
98  }
99}
100
hooks/validate.ts 546 lines
1// The one Engram validator (docs/spec/engram-format.md, "Validation rules"):
2// the loader skips a package it fails and says why, the checker prints its
3// report, and `/eidola check <id>` shows it. Pure: it takes a package's files
4// as given, reads nothing itself, imports nothing from 'claude-code', and
5// never throws, whatever it is handed.
6
7import {
8  HUD_LABELS,
9  HUD_LAYOUTS,
10  HUD_METERS,
11  HUD_TAGS,
12  RIGHTS,
13  SCENE_IDS,
14  SCENE_NAMES,
15  SHOW_PLACES,
16  SPEC_VERSION,
17  THUMB_VIEWS,
18  VESSEL_STATES,
19} from './engram-types'
20
21export type RuleId =
22  | 'manifest'
23  | 'id'
24  | 'scene'
25  | 'thumb-size'
26  | 'thumb-safe'
27  | 'thumb-exists'
28  | 'frame'
29  | 'shows'
30  | 'soul'
31  | 'unknown-key'
32  | 'camera'
33  | 'v1'
34
35export type Level = 'error' | 'warning'
36
37/** Every rule in the spec's table, its level, and what it checks. */
38export const RULES: Readonly<Record<RuleId, { level: Level; checks: string }>> = {
39  manifest: {
40    level: 'error',
41    checks: 'engram.json exists and parses, spec is 2, the required fields are present, and every field present has the right type',
42  },
43  id: { level: 'error', checks: "id equals the folder's name and, for a package that isn't bundled, isn't a bundled id" },
44  scene: { level: 'error', checks: 'vessel.scene is set and names a scene the mod has' },
45  'thumb-size': { level: 'error', checks: 'each thumbnail is at most 131,072 characters and starts with <svg' },
46  'thumb-safe': { level: 'error', checks: 'no <script>, no on*= attribute and no href to http(s): in a thumbnail' },
47  'thumb-exists': { level: 'error', checks: 'each file named in vessel.thumbnails exists in vessel/' },
48  frame: { level: 'warning', checks: 'a v1 per-state frame file in vessel/ is ignored' },
49  shows: { level: 'error', checks: 'vessel.shows, when given, lists known places, at least one, each once' },
50  soul: { level: 'warning', checks: 'a v1 Soul file is ignored' },
51  'unknown-key': { level: 'warning', checks: 'a key the format does not have, outside extensions, is ignored' },
52  camera: { level: 'warning', checks: 'vessel.hud.camera is set without tag: livecam' },
53  v1: { level: 'error', checks: 'a v1 package (engram.yaml, no engram.json) does not load' },
54}
55
56/** One problem: the file it is in, what is wrong, and how to fix it. */
57export type Issue = { rule: RuleId; file: string; problem: string; fix: string }
58
59export type Report = { errors: Issue[]; warnings: Issue[] }
60
61/**
62 * A package as the validator sees it: its folder's name, and its files by
63 * path inside the folder (`engram.json`, `vessel/thumb-pane.svg`), each
64 * file's text. A file listed with no text read yet may be given as ''.
65 */
66export type PackageFiles = { folder: string; files: Readonly<Record<string, string>> }
67
68export type ValidateOptions = {
69  /** Ids the package may not take: the bundled ids, for a package that isn't bundled. */
70  reserved?: readonly string[]
71  /**
72   * The scenes `vessel.scene` may name; the mod's built-in scenes by default,
73   * and `["self"]` for an Engram plugin's engram.json.
74   */
75  scenes?: readonly string[]
76  /**
77   * Whether to check the thumbnails' files (default true). The loader reads
78   * them on first use, not at start, and checks each then with checkThumbnail.
79   */
80  thumbnails?: boolean
81}
82
83export const MANIFEST = 'engram.json'
84export const V1_MANIFEST = 'engram.yaml'
85export const SOUL_FILE = 'SOUL.md'
86
87/** A desktop Svg's bound on its source, which a thumbnail is drawn in. */
88export const THUMBNAIL_MAX = 131_072
89
90/** The required fields, at each level of engram.json that has them. */
91export const REQUIRED = {
92  engram: ['spec', 'id', 'name', 'version', 'author', 'description', 'rights', 'vessel'],
93  vessel: ['scene'],
94  colour: ['label', 'detail'],
95} as const
96
97/** Every key the format has, at each level; any other draws an unknown-key warning. */
98export const KEYS = {
99  engram: [...REQUIRED.engram, 'remixOf', 'extensions', '$schema'],
100  vessel: ['scene', 'shows', 'thumbnails', 'hud'],
101  thumbnails: THUMB_VIEWS,
102  hud: ['show', 'meter', 'tag', 'camera', 'layout', 'label', 'bracket', 'colours'],
103  colours: VESSEL_STATES,
104  colour: REQUIRED.colour,
105} as const
106
107/** Every field that takes one of a list of values. */
108export const ENUMS = {
109  spec: [SPEC_VERSION],
110  rights: RIGHTS,
111  scene: SCENE_NAMES,
112  shows: SHOW_PLACES,
113  meter: HUD_METERS,
114  tag: HUD_TAGS,
115  layout: HUD_LAYOUTS,
116  label: HUD_LABELS,
117} as const
118
119/** The patterns string fields must match, as regular expression sources. */
120export const PATTERNS = {
121  id: '^[a-z0-9-]{2,32}$',
122  version:
123    '^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?(\\+[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$',
124  colour: '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$',
125  thumbnail: '^[A-Za-z0-9_-][A-Za-z0-9._-]*\\.svg$',
126} as const
127
128/** Length limits on string fields, in characters. */
129export const LIMITS = {
130  name: { min: 1, max: 32 },
131  description: { min: 1, max: 160 },
132  author: { min: 1 },
133} as const
134
135/** v1 keys that v2 dropped, and why: a hint beside the unknown-key warning. */
136const DROPPED: Readonly<Record<string, string>> = {
137  engram_version: 'v2 uses spec and version',
138  voice_id: 'v2 has no voice',
139  meta: 'v2 keeps author and description at the top level',
140  tags: 'nothing reads tags',
141  created: 'nothing reads it',
142  soul: 'Eidola adds nothing to the prompt',
143  type: 'every v2 Engram draws a scene',
144  pack: "a v2 package's own vessel/ folder holds its files",
145  forge: 'nothing reads it',
146  placement: 'where an Engram draws is the person\'s surfaces setting, and vessel.shows',
147  fallback: 'every scene draws every mood',
148  media: 'v2 has no media tier',
149}
150
151const RE = {
152  id: new RegExp(PATTERNS.id),
153  version: new RegExp(PATTERNS.version),
154  colour: new RegExp(PATTERNS.colour),
155  thumbnail: new RegExp(PATTERNS.thumbnail),
156  script: /<script\b/i,
157  // An on* attribute inside a tag: `<g onload=`, `<a onclick =`.
158  handler: /<[A-Za-z][^<>]*?\son[A-Za-z]+\s*=/,
159  // An href (or xlink:href) to a web address.
160  webHref: /\bhref\s*=\s*["']?\s*https?:/i,
161  frame: /^vessel\/([^/]+)\.svg$/,
162}
163
164type Json = Record<string, unknown>
165
166function isObject(value: unknown): value is Json {
167  return typeof value === 'object' && value !== null && !Array.isArray(value)
168}
169
170/** A value as a short quote for a problem line. */
171function quote(value: unknown): string {
172  let text: string
173  try {
174    text = typeof value === 'string' ? JSON.stringify(value) : (JSON.stringify(value) ?? String(value))
175  } catch {
176    text = typeof value
177  }
178  return text.length > 40 ? `${text.slice(0, 37)}...` : text
179}
180
181function oneOf(values: readonly unknown[]): string {
182  return values.map(v => (typeof v === 'string' ? `"${v}"` : String(v))).join(', ')
183}
184
185class Collector {
186  readonly report: Report = { errors: [], warnings: [] }
187
188  add(rule: RuleId, file: string, problem: string, fix: string): void {
189    const issue: Issue = { rule, file, problem, fix }
190    if (RULES[rule].level === 'error') {
191      this.report.errors.push(issue)
192    } else {
193      this.report.warnings.push(issue)
194    }
195  }
196
197  /** An unknown-key warning for each key of `obj` not in `known`; `at` is the path to `obj`. */
198  unknownKeys(obj: Json, known: readonly string[], at: string): void {
199    for (const key of Object.keys(obj)) {
200      if (known.includes(key)) {
201        continue
202      }
203      const path = at ? `${at}.${key}` : key
204      const why = DROPPED[key]
205      this.add(
206        'unknown-key',
207        MANIFEST,
208        why ? `${path} was a v1 field; ${why}, so it is ignored.` : `${path} isn't part of the format, so it is ignored.`,
209        `Delete ${path}, or move it under extensions to keep it.`,
210      )
211    }
212  }
213}
214
215/** Checks one thumbnail's text: its size, that it is an SVG, and that it is safe to draw. */
216export function checkThumbnail(file: string, text: unknown): Issue[] {
217  const out = new Collector()
218  try {
219    thumbnail(out, file, text)
220  } catch {
221    out.add('thumb-size', file, "This thumbnail couldn't be read.", 'Save it again as a plain SVG file.')
222  }
223  return out.report.errors
224}
225
226function thumbnail(out: Collector, file: string, text: unknown): void {
227  if (typeof text !== 'string') {
228    out.add('thumb-size', file, "This thumbnail isn't text.", 'Save it as a plain SVG file.')
229    return
230  }
231  if (text.length > THUMBNAIL_MAX) {
232    out.add(
233      'thumb-size',
234      file,
235      `This thumbnail is ${text.length} characters, over the 131,072 a desktop Svg can draw.`,
236      'Simplify it or bake it smaller, then check it again.',
237    )
238  }
239  if (!text.trimStart().startsWith('<svg')) {
240    out.add(
241      'thumb-size',
242      file,
243      "This thumbnail doesn't start with <svg.",
244      'Save it as a bare SVG: the <svg> element first, no XML prolog or doctype before it.',
245    )
246  }
247  if (RE.script.test(text)) {
248    out.add('thumb-safe', file, 'This thumbnail has a <script>.', 'Remove it: a thumbnail is a still picture, and the host strips scripts anyway.')
249  }
250  if (RE.handler.test(text)) {
251    out.add('thumb-safe', file, 'This thumbnail has an on* event attribute, such as onload.', 'Remove every on*= attribute.')
252  }
253  if (RE.webHref.test(text)) {
254    out.add(
255      'thumb-safe',
256      file,
257      'This thumbnail links to a web address (an href to http: or https:).',
258      'Inline what it links to, or remove the link: a thumbnail draws from its own text alone.',
259    )
260  }
261}
262
263/**
264 * Validates an Engram package against spec v2. Returns every error (the
265 * package doesn't load) and warning (it loads; something is ignored).
266 */
267export function validate(pkg: PackageFiles | unknown, options: ValidateOptions = {}): Report {
268  const out = new Collector()
269  try {
270    check(out, pkg, options)
271  } catch (error) {
272    out.add(
273      'manifest',
274      MANIFEST,
275      `The validator couldn't read this package (${error instanceof Error ? error.message : quote(error)}).`,
276      'Check the package is a folder holding an engram.json.',
277    )
278  }
279  return out.report
280}
281
282function check(out: Collector, pkg: unknown, options: ValidateOptions): void {
283  if (!isObject(pkg) || !isObject(pkg['files'])) {
284    out.add('manifest', MANIFEST, 'No package was given: no files to read.', 'Point the check at a package folder holding an engram.json.')
285    return
286  }
287  const files = new Map<string, string>()
288  for (const [path, text] of Object.entries(pkg['files'])) {
289    files.set(path.replace(/\\/g, '/').replace(/^\.\//, ''), typeof text === 'string' ? text : '')
290  }
291  const rawFolder = pkg['folder']
292  const folder = typeof rawFolder === 'string' ? rawFolder.replace(/\\/g, '/').replace(/\/+$/, '').split('/').pop() : undefined
293
294  if (!files.has(MANIFEST)) {
295    if (files.has(V1_MANIFEST)) {
296      out.add(
297        'v1',
298        V1_MANIFEST,
299        "v1 Engram: its clips can't draw in Claude. A v1 package has engram.yaml and no engram.json.",
300        'Remake it as v2: an engram.json naming a scene (docs/spec/engram-format.md).',
301      )
302    } else {
303      out.add('manifest', MANIFEST, 'There is no engram.json.', 'Add an engram.json at the top of the package folder (docs/spec/engram-format.md).')
304    }
305    return
306  }
307
308  leftovers(out, files)
309
310  let json: unknown
311  try {
312    json = JSON.parse((files.get(MANIFEST) ?? '').replace(/^/, ''))
313  } catch (error) {
314    out.add(
315      'manifest',
316      MANIFEST,
317      `engram.json doesn't parse as JSON (${error instanceof Error ? error.message : 'a syntax error'}).`,
318      'Fix the JSON: quoted keys, no trailing commas, no comments.',
319    )
320    return
321  }
322  if (!isObject(json)) {
323    out.add('manifest', MANIFEST, "engram.json isn't a JSON object.", 'Make the whole file one object: { "spec": 2, "id": ..., ... }.')
324    return
325  }
326
327  top(out, json, folder, options)
328
329  const vessel = json['vessel']
330  if (vessel === undefined) {
331    out.add('manifest', MANIFEST, 'The required field vessel is missing.', 'Add "vessel": { "scene": "kraken" }, naming the scene it draws.')
332  } else if (!isObject(vessel)) {
333    out.add('manifest', MANIFEST, `vessel is ${quote(vessel)}, not an object.`, 'Make vessel an object: { "scene": "kraken" }.')
334  } else {
335    const named = vesselFields(out, vessel, options)
336    if (options.thumbnails !== false) {
337      for (const file of named) {
338        const text = files.get(file)
339        if (text === undefined) {
340          out.add('thumb-exists', file, `vessel.thumbnails names ${file}, which isn't in the package.`, `Add ${file}, or take it out of vessel.thumbnails.`)
341        } else {
342          thumbnail(out, file, text)
343        }
344      }
345    }
346  }
347
348  const extensions = json['extensions']
349  if (extensions !== undefined && !isObject(extensions)) {
350    out.add('manifest', MANIFEST, `extensions is ${quote(extensions)}, not an object.`, 'Make extensions an object, such as {}.')
351  }
352  out.unknownKeys(json, KEYS.engram, '')
353}
354
355/** Files v2 no longer has: per-state frames and the Soul. */
356function leftovers(out: Collector, files: Map<string, string>): void {
357  for (const path of files.keys()) {
358    const frame = RE.frame.exec(path)
359    if (frame && (VESSEL_STATES as readonly string[]).includes(frame[1] ?? '')) {
360      out.add('frame', path, 'v2 has no frames; this file is ignored. Every Engram draws a scene.', `Delete ${path}.`)
361    }
362    if (path.toLowerCase() === SOUL_FILE.toLowerCase()) {
363      out.add('soul', path, 'Eidola adds nothing to the prompt; this file is ignored.', `Delete ${path}. A persona belongs in CLAUDE.md, an output style or a skill.`)
364    }
365  }
366}
367
368function top(out: Collector, json: Json, folder: string | undefined, options: ValidateOptions): void {
369  const spec = json['spec']
370  if (spec === undefined) {
371    out.add('manifest', MANIFEST, 'The required field spec is missing.', 'Add "spec": 2.')
372  } else if (spec !== SPEC_VERSION) {
373    out.add('manifest', MANIFEST, `spec is ${quote(spec)}; this mod reads spec 2.`, 'Set "spec": 2, and check the package against docs/spec/engram-format.md.')
374  }
375
376  const id = json['id']
377  if (id === undefined) {
378    out.add('manifest', MANIFEST, 'The required field id is missing.', 'Add "id", the same as the folder\'s name, such as "my-engram".')
379  } else if (typeof id !== 'string' || !RE.id.test(id)) {
380    out.add('manifest', MANIFEST, `id is ${quote(id)}, not a slug.`, 'Use 2 to 32 of a-z, 0-9 and -, such as "my-engram", and name the folder the same.')
381  } else {
382    if (folder !== undefined && id !== folder) {
383      out.add('id', MANIFEST, `id is "${id}" but the folder is named "${folder}".`, `Rename the folder to ${id}, or set "id": "${folder}".`)
384    }
385    if (options.reserved?.includes(id)) {
386      out.add('id', MANIFEST, `"${id}" is a bundled Engram's id.`, 'Remix it under a new id: change id and rename the folder to match.')
387    }
388  }
389
390  text(out, json, 'name', LIMITS.name.max, 'Add "name", what the picker and the HUD call it.')
391  const version = json['version']
392  if (version === undefined) {
393    out.add('manifest', MANIFEST, 'The required field version is missing.', 'Add "version": "1.0.0".')
394  } else if (typeof version !== 'string' || !RE.version.test(version)) {
395    out.add('manifest', MANIFEST, `version is ${quote(version)}, not a semver version.`, 'Use major.minor.patch, such as "1.0.0".')
396  }
397  text(out, json, 'author', undefined, 'Add "author", your name or handle.')
398  text(out, json, 'description', LIMITS.description.max, 'Add "description", a line or two for the picker card.')
399
400  const rights = json['rights']
401  if (rights === undefined) {
402    out.add('manifest', MANIFEST, 'The required field rights is missing.', 'Add "rights": "original" if you made it, or "licensed" if you may share it.')
403  } else if (!(RIGHTS as readonly unknown[]).includes(rights)) {
404    out.add('manifest', MANIFEST, `rights is ${quote(rights)}.`, `Set rights to one of ${oneOf(RIGHTS)}.`)
405  }
406
407  const remixOf = json['remixOf']
408  if (remixOf !== undefined) {
409    if (typeof remixOf !== 'string' || !RE.id.test(remixOf)) {
410      out.add('manifest', MANIFEST, `remixOf is ${quote(remixOf)}, not an Engram's id.`, 'Set remixOf to the id of the Engram it was remixed from, such as "kraken", or leave it out.')
411    } else if (remixOf === json['id']) {
412      out.add('manifest', MANIFEST, 'remixOf names this Engram itself.', 'Set remixOf to the id of the Engram it was remixed from, or leave it out.')
413    }
414  }
415}
416
417/** A required string field, non-blank and at most `max` characters. */
418function text(out: Collector, json: Json, field: 'name' | 'author' | 'description', max: number | undefined, add: string): void {
419  const value = json[field]
420  if (value === undefined) {
421    out.add('manifest', MANIFEST, `The required field ${field} is missing.`, add)
422  } else if (typeof value !== 'string' || value.trim() === '') {
423    out.add('manifest', MANIFEST, `${field} is ${quote(value)}, not a non-empty string.`, add)
424  } else if (max !== undefined && value.length > max) {
425    out.add('manifest', MANIFEST, `${field} is ${value.length} characters, over ${max}.`, `Shorten ${field} to ${max} characters or fewer.`)
426  }
427}
428
429/** Checks vessel's fields; returns the thumbnail files it names, as paths in the package. */
430function vesselFields(out: Collector, vessel: Json, options: ValidateOptions): string[] {
431  const scenes: readonly string[] = options.scenes ?? SCENE_IDS
432  const scene = vessel['scene']
433  if (scene === undefined) {
434    out.add('scene', MANIFEST, 'vessel.scene is missing: every Engram draws a scene.', `Set vessel.scene to one of ${oneOf(scenes)}.`)
435  } else if (typeof scene !== 'string' || !scenes.includes(scene)) {
436    out.add('scene', MANIFEST, `vessel.scene is ${quote(scene)}, which isn't a scene this mod has.`, `Set vessel.scene to one of ${oneOf(scenes)}.`)
437  }
438
439  const shows = vessel['shows']
440  if (shows !== undefined) {
441    if (!Array.isArray(shows)) {
442      out.add('shows', MANIFEST, `vessel.shows is ${quote(shows)}, not a list.`, `Make it a list of places: ${oneOf(SHOW_PLACES)}.`)
443    } else if (shows.length === 0) {
444      out.add('shows', MANIFEST, 'vessel.shows lists no place, so it would draw nowhere.', `List at least one of ${oneOf(SHOW_PLACES)}, or leave shows out for all three.`)
445    } else {
446      const seen = new Set<unknown>()
447      for (const place of shows) {
448        if (!(SHOW_PLACES as readonly unknown[]).includes(place)) {
449          out.add('shows', MANIFEST, `vessel.shows lists ${quote(place)}, which isn't a place.`, `Use only ${oneOf(SHOW_PLACES)}.`)
450        } else if (seen.has(place)) {
451          out.add('shows', MANIFEST, `vessel.shows lists "${String(place)}" twice.`, 'List each place once.')
452        }
453        seen.add(place)
454      }
455    }
456  }
457
458  const named: string[] = []
459  const thumbnails = vessel['thumbnails']
460  if (thumbnails !== undefined) {
461    if (!isObject(thumbnails)) {
462      out.add('manifest', MANIFEST, `vessel.thumbnails is ${quote(thumbnails)}, not an object.`, 'Make it { "pane": "thumb-pane.svg", "band": "thumb-band.svg" }, or leave it out.')
463    } else {
464      for (const view of THUMB_VIEWS) {
465        const file = thumbnails[view]
466        if (file === undefined) {
467          continue
468        }
469        if (typeof file !== 'string' || !RE.thumbnail.test(file)) {
470          out.add('manifest', MANIFEST, `vessel.thumbnails.${view} is ${quote(file)}, not an SVG file name in vessel/.`, `Name a file in vessel/, such as "thumb-${view}.svg".`)
471        } else {
472          named.push(`vessel/${file}`)
473        }
474      }
475      out.unknownKeys(thumbnails, KEYS.thumbnails, 'vessel.thumbnails')
476    }
477  }
478
479  const hud = vessel['hud']
480  if (hud !== undefined) {
481    if (!isObject(hud)) {
482      out.add('manifest', MANIFEST, `vessel.hud is ${quote(hud)}, not an object.`, 'Make vessel.hud an object, or leave it out.')
483    } else {
484      hudFields(out, hud)
485    }
486  }
487
488  out.unknownKeys(vessel, KEYS.vessel, 'vessel')
489  return named
490}
491
492function hudFields(out: Collector, hud: Json): void {
493  const show = hud['show']
494  if (show !== undefined && typeof show !== 'boolean') {
495    out.add('manifest', MANIFEST, `vessel.hud.show is ${quote(show)}, not true or false.`, 'Set it to true or false.')
496  }
497  const enums = { meter: HUD_METERS, tag: HUD_TAGS, layout: HUD_LAYOUTS, label: HUD_LABELS } as const
498  for (const field of ['meter', 'tag', 'layout', 'label'] as const) {
499    const value = hud[field]
500    if (value !== undefined && !(enums[field] as readonly unknown[]).includes(value)) {
501      out.add('manifest', MANIFEST, `vessel.hud.${field} is ${quote(value)}.`, `Set it to one of ${oneOf(enums[field])}.`)
502    }
503  }
504  const camera = hud['camera']
505  if (camera !== undefined) {
506    if (typeof camera !== 'string' || camera.trim() === '') {
507      out.add('manifest', MANIFEST, `vessel.hud.camera is ${quote(camera)}, not a name.`, 'Set it to the camera\'s name, such as "DEEPCAM 02".')
508    } else if (hud['tag'] !== 'livecam') {
509      out.add('camera', MANIFEST, 'vessel.hud.camera is set but the tag isn\'t "livecam", so nothing shows it.', 'Set vessel.hud.tag to "livecam", or remove camera.')
510    }
511  }
512  const bracket = hud['bracket']
513  if (bracket !== undefined && !(typeof bracket === 'string' && RE.colour.test(bracket))) {
514    out.add('manifest', MANIFEST, `vessel.hud.bracket is ${quote(bracket)}, not a hex colour.`, 'Use #rgb or #rrggbb, such as "#b8913a".')
515  }
516  const colours = hud['colours']
517  if (colours !== undefined) {
518    if (!isObject(colours)) {
519      out.add('manifest', MANIFEST, `vessel.hud.colours is ${quote(colours)}, not an object.`, 'Make it an object of states, such as { "idle": { "label": "#ffffff", "detail": "#a0a0b8" } }.')
520    } else {
521      for (const state of VESSEL_STATES) {
522        const pair = colours[state]
523        if (pair === undefined) {
524          continue
525        }
526        const at = `vessel.hud.colours.${state}`
527        if (!isObject(pair)) {
528          out.add('manifest', MANIFEST, `${at} is ${quote(pair)}, not { label, detail }.`, `Set ${at} to { "label": "#rrggbb", "detail": "#rrggbb" }.`)
529          continue
530        }
531        for (const part of REQUIRED.colour) {
532          const value = pair[part]
533          if (value === undefined) {
534            out.add('manifest', MANIFEST, `${at}.${part} is missing.`, `Add ${at}.${part}, a hex colour.`)
535          } else if (!(typeof value === 'string' && RE.colour.test(value))) {
536            out.add('manifest', MANIFEST, `${at}.${part} is ${quote(value)}, not a hex colour.`, 'Use #rgb or #rrggbb.')
537          }
538        }
539        out.unknownKeys(pair, KEYS.colour, at)
540      }
541      out.unknownKeys(colours, KEYS.colours, 'vessel.hud.colours')
542    }
543  }
544  out.unknownKeys(hud, KEYS.hud, 'vessel.hud')
545}
546
hooks/handoff.ts 142 lines
1// The hand-off to an Engram plugin (docs/spec/engram-plugin.md): what Eidola
2// asks for, how it judges the drawing that comes back, and the keys both
3// sides use. Pure: no `$`; register.tsx makes the calls.
4//
5// Eidola draws its frame, HUD and corner around a slot. The awake Engram's
6// plugin fills the slot from wherever its hooks sit in the chain:
7//   - beneath Eidola (it loaded after): Eidola's `next` reaches it with
8//     `e.props.eidola` set, and it answers a Box keyed `eidola:<id>`;
9//   - above Eidola (it loaded first): it calls `next` itself, finds the Box
10//     keyed `eidola-slot:<id>` in Eidola's tree, and puts its drawing there.
11
12import type { RenderElement, TraceEntry } from 'claude-code'
13
14import type { EidolaContract } from '../types'
15import { BOX_BUDGET } from './live-pixels'
16
17/** The public contract's version: types/index.d.ts and docs/spec/engram-plugin.md. */
18export const CONTRACT: EidolaContract = 1
19
20/** Most blocks (elements) one drawing may hold: the live drawings' own budget. */
21export const BLOCK_BUDGET = BOX_BUDGET
22
23/** How long a plugin's drawing beneath Eidola may take, its own hooks' time, before it falls back. */
24export const DRAW_BUDGET_MS = 250
25
26/** The key of the Box an Engram plugin's drawing comes back in. */
27export function sceneKey(id: string): string {
28  return `eidola:${id}`
29}
30
31/** The key of the slot Eidola leaves for a plugin above it to fill. */
32export function slotKey(id: string): string {
33  return `eidola-slot:${id}`
34}
35
36/** The key of the slot once the Engram is marked not loading: no plugin fills it. */
37export function fallbackKey(id: string): string {
38  return `eidola-fallback:${id}`
39}
40
41/** Why an Engram is marked not loading: the file, the line when known, and the problem. */
42export type Fault = { file: string; line?: number; problem: string }
43
44/** A fault as one line: `hooks/register.tsx:12: it threw.` */
45export function faultLine(fault: Fault): string {
46  return `${fault.file}${fault.line === undefined ? '' : `:${fault.line}`}: ${fault.problem}`
47}
48
49/** The line an error's stack names first (`at draw (hooks/creature.tsx:12:5)`), if any. */
50export function lineOf(stack: unknown): number | undefined {
51  if (typeof stack !== 'string') {
52    return undefined
53  }
54  const found = /:(\d+):\d+\)?\s*$/m.exec(stack.split('\n').find(line => /:\d+:\d+\)?\s*$/.test(line)) ?? '')
55  return found ? Number(found[1]) : undefined
56}
57
58/** How many elements a tree holds, itself included; strings are free. */
59export function countBlocks(node: unknown): number {
60  if (node === null || typeof node !== 'object') {
61    return 0
62  }
63  const children = (node as { children?: unknown }).children
64  let n = 1
65  if (Array.isArray(children)) {
66    for (const child of children) {
67      n += countBlocks(child)
68    }
69  } else if (children !== undefined) {
70    n += countBlocks(children)
71  }
72  return n
73}
74
75/** The key a tree's root carries, if it is an element with one. */
76export function keyOf(node: unknown): string | undefined {
77  if (node === null || typeof node !== 'object') {
78    return undefined
79  }
80  const key = (node as { props?: { key?: unknown } }).props?.key
81  return typeof key === 'string' ? key : undefined
82}
83
84/** One link of the chain beneath Eidola, as much of `next.trace` as the judge reads. */
85export type Link = Pick<TraceEntry, 'plugin' | 'outcome'> & Partial<Pick<TraceEntry, 'ms'>>
86
87/** What the judge is handed: the Engram, what came back from beneath, and how. */
88export type Asked = {
89  engram: string
90  /** The plugin's name, as its plugin.json gives it. */
91  plugin: string
92  /** Its hooks module, relative to its folder: where a throw is reported. */
93  module: string
94  got: unknown
95  trace: readonly Link[]
96  /** The whole `next()` chain's time, every plugin beneath Eidola included. */
97  tookMs: number
98}
99
100/**
101 * How long the Engram's own plugin took: its links' own time, which the
102 * trace gives with their `next()` calls taken out, so a slow plugin elsewhere
103 * in the chain isn't counted against it. Where its plugin isn't in the trace
104 * by name (or a link has no time), the whole chain's.
105 */
106export function ownMs(mine: readonly Link[], tookMs: number): number {
107  return mine.length > 0 && mine.every(link => typeof link.ms === 'number') ? mine.reduce((sum, link) => sum + (link.ms ?? 0), 0) : tookMs
108}
109
110/**
111 * The drawing to place, a fault, or neither (nothing beneath answered: the
112 * plugin's hooks sit above Eidola, so the slot is left for it to fill).
113 */
114export type Verdict = { tree: RenderElement } | { fault: Fault } | { slot: true }
115
116export function judge(asked: Asked): Verdict {
117  const { engram, plugin, module, got, trace, tookMs } = asked
118  const at = sceneKey(engram)
119  const mine = plugin ? trace.filter(link => link.plugin === plugin) : []
120  if (keyOf(got) === at) {
121    const blocks = countBlocks(got)
122    if (blocks > BLOCK_BUDGET) {
123      return { fault: { file: module, problem: `its drawing holds ${blocks} blocks, over the ${BLOCK_BUDGET} a drawing may hold.` } }
124    }
125    const took = ownMs(mine, tookMs)
126    if (took > DRAW_BUDGET_MS) {
127      return { fault: { file: module, problem: `its drawing took ${Math.round(took)} ms, over the ${DRAW_BUDGET_MS} ms a drawing may take.` } }
128    }
129    return { tree: got as RenderElement }
130  }
131  if (mine.length === 0) {
132    return { slot: true }
133  }
134  if (mine.some(link => link.outcome === 'expired')) {
135    return { fault: { file: module, problem: 'its ui.render hook ran out of time.' } }
136  }
137  if (mine.some(link => link.outcome === 'skipped' || link.outcome === 'kept' || link.outcome === 'rejected' || link.outcome === 'caught')) {
138    return { fault: { file: module, problem: 'its ui.render hook threw.' } }
139  }
140  return { fault: { file: module, problem: `it drew nothing Eidola can place: its drawing must be one Box keyed "${at}".` } }
141}
142
hooks/engram-page.tsx 436 lines
1// An Engram's own page, and the pieces it shares with the picker: the
2// header, the title and its accent rule, chips, panels and buttons, all in
3// the pane's colours (theme.ts) as docs/design/design-system.md lays them
4// out. The desktop draws them with stills and icons; the terminal and mobile
5// draw the same screens in plain text, no `Svg` and no `Client`.
6//
7// Nothing here reaches the engine: register.tsx hands each screen what it
8// shows and what each button does, and draws the live preview scene itself,
9// since a `Client` is named in the hooks module's own source.
10
11import type { Elements, RenderElement } from 'claude-code'
12
13import type { Mood, Preview, VesselState } from '../types'
14import type { Engram } from './engram-types'
15import { FRAME_STATES } from './hud'
16import { ICON_NAMES, ICON_PX, iconSvg } from './icons'
17import type { SurfaceIcon } from './icons'
18import { showsLabel, whereItDraws } from './placement'
19import type { Surfaces } from './placement'
20import { RULE, THEME } from './theme'
21import { WORDMARK_HEIGHT, WORDMARK_WIDTH, wordmarkSvg } from './wordmark'
22
23/** The elements a screen draws with. `Svg` only where `isRich`. */
24export type Els = Pick<Elements['desktop'], 'Box' | 'Text' | 'Button' | 'Svg'>
25
26/** How a button looks: the gold primary (Awaken), the deep red danger (Sleep), a neutral button, a chip on or off, or a gold underlined link. */
27export type PillTone = 'primary' | 'danger' | 'neutral' | 'on' | 'off' | 'link'
28
29/** Draws a button on the desktop, where register.tsx draws its label as a Client and wires the press. */
30export type PillDraw = (key: string, label: string, onPress: () => void, tone: PillTone) => RenderElement
31
32/**
33 * What every screen piece needs: its elements, whether it may draw stills,
34 * its width in cells, and, on the desktop, how a button is drawn.
35 */
36export type Kit = { els: Els; isRich: boolean; cols: number; pill?: PillDraw }
37
38/** The surfaces, in the order their icons stand. */
39export const SURFACE_ICONS: readonly SurfaceIcon[] = ['pane', 'band', 'shrine']
40
41/** The moods a preview chip sets, in order. */
42export const PREVIEW_MOODS: readonly Mood[] = ['idle', 'working', 'attention']
43
44/** A fresh preview: idle, no error, nothing scorched. */
45export const FRESH_PREVIEW: Preview = { mood: 'idle', isError: false, ink: 0, inkAt: 0, moodAt: 0, moodBefore: 'idle' }
46
47const MOOD_NAMES: Record<Mood, string> = { idle: 'Idle', working: 'Working', attention: 'Attention' }
48const MOOD_STATE: Record<Mood, VesselState> = { idle: 'idle', working: 'working', attention: 'attention' }
49
50// ── Pieces ──────────────────────────────────────────────────────────────
51
52/** A surface icon in a colour: a small still on the desktop, the surface's name in text elsewhere. */
53export function surfaceIcon(kit: Kit, icon: SurfaceIcon, colour: string, key: string): RenderElement {
54  const { Box, Text, Svg } = kit.els
55  if (!kit.isRich) {
56    return (
57      <Text key={key} color={colour}>
58        {icon}
59      </Text>
60    )
61  }
62  return (
63    <Box key={key} width={2} height={1} alignItems="center" justifyContent="center">
64      <Svg key={`${key}:${colour}`} source={iconSvg(icon, colour)} alt={ICON_NAMES[icon]} width={ICON_PX} height={ICON_PX} />
65    </Box>
66  )
67}
68
69/**
70 * The one control every screen draws, in four tones: the gold primary, a
71 * neutral button, and a chip on or off. On the desktop it is register.tsx's
72 * (`kit.pill`): a rounded box with its label drawn as a Client, the whole
73 * label the hit, one click, no inverting under the pointer. In text, a
74 * Button in a bordered box.
75 */
76function pill(kit: Kit, key: string, label: string, onPress: () => void, tone: PillTone): RenderElement {
77  if (kit.pill) {
78    return kit.pill(key, label, onPress, tone)
79  }
80  const { Box, Button } = kit.els
81  return (
82    <Box key={`pill-${key}`} borderStyle="round" borderColor={tone === 'on' || tone === 'primary' ? THEME.gold : THEME.line} paddingX={1}>
83      <Button key={key} label={label} plain {...(tone === 'off' ? { dimColor: true } : {})} onPress={onPress} />
84    </Box>
85  )
86}
87
88/** A button: neutral, the gold primary, or the deep red danger. */
89export function button(kit: Kit, key: string, label: string, onPress: () => void, tone: 'neutral' | 'primary' | 'danger' = 'neutral'): RenderElement {
90  return pill(kit, key, label, onPress, tone)
91}
92
93/** A chip: raised in bold when on, muted when off. */
94export function chip(kit: Kit, key: string, label: string, isOn: boolean, onPress: () => void): RenderElement {
95  return pill(kit, key, label, onPress, isOn ? 'on' : 'off')
96}
97
98/** A label: gold capitals, as "AWAKE" and "WHERE IT DRAWS". */
99export function label(kit: Kit, text: string, key = 'label'): RenderElement {
100  const { Text } = kit.els
101  return (
102    <Text key={key} color={THEME.gold}>
103      {text.toUpperCase()}
104    </Text>
105  )
106}
107
108/** The accent rule: about 15 cells, ember to amber to gold, fading out. Thin bars on the desktop, a line of rules in text. */
109export function accentRule(kit: Kit, key = 'rule'): RenderElement {
110  const { Box, Text } = kit.els
111  if (!kit.isRich) {
112    return (
113      <Box key={key} flexDirection="row">
114        {RULE.map((colour, i) => (
115          <Text key={`rule-${i}`} color={colour}>
116            ━━━
117          </Text>
118        ))}
119      </Box>
120    )
121  }
122  return (
123    <Box key={key} flexDirection="row" height={1} alignItems="center">
124      {RULE.map((colour, i) => (
125        <Box key={`rule-${i}`} width={3} height="12%" backgroundColor={colour} />
126      ))}
127    </Box>
128  )
129}
130
131/** The wordmark's scale in the header: twice its own size, so it reads as the screen's name. */
132const WORDMARK_SCALE = 2
133
134/**
135 * The header: Back, then the wordmark at twice its size, and at the right
136 * the screen's main action where it has one (a page's Awaken or Sleep). In
137 * text, the same in bold.
138 */
139export function header(kit: Kit, back: { key: string; onPress: () => void }, action: RenderElement | null = null): RenderElement {
140  const { Box, Text, Svg } = kit.els
141  return (
142    <Box key="head" flexDirection="row" justifyContent="space-between" alignItems="center" flexShrink={0}>
143      <Box key="head-left" flexDirection="row" alignItems="center" gap={2}>
144        {button(kit, back.key, '← Back', back.onPress)}
145        {kit.isRich ? (
146          <Svg key="wordmark" source={wordmarkSvg(THEME.gold)} alt="Eidola" width={WORDMARK_WIDTH * WORDMARK_SCALE} height={WORDMARK_HEIGHT * WORDMARK_SCALE} />
147        ) : (
148          <Text key="wordmark" bold color={THEME.gold}>
149            EIDOLA
150          </Text>
151        )}
152      </Box>
153      {action}
154    </Box>
155  )
156}
157
158/** One choice of a dropdown. */
159export type DropdownOption = { id: string; label: string }
160
161/**
162 * The filter dropdown in text, where no `Client` draws: the chosen option
163 * and a caret as a chip, and, open, the options as chips in the flow under
164 * it. The desktop draws its own (register.tsx), every row a full-width hit.
165 */
166export function dropdown(
167  kit: Kit,
168  input: { key: string; prefix: string; options: readonly DropdownOption[]; value: string; isOpen: boolean; onToggle: () => void; onPick: (id: string) => void },
169): { trigger: RenderElement; menu: RenderElement | null } {
170  const { Box } = kit.els
171  const { key, options, value, isOpen } = input
172  const chosen = options.find(one => one.id === value) ?? options[0]
173  const trigger = chip(kit, `${key}-toggle`, `${input.prefix}: ${chosen?.label ?? ''} ${isOpen ? '▴' : '▾'}`, isOpen, input.onToggle)
174  const menu = isOpen ? (
175    <Box key={`${key}-menu`} flexDirection="row" flexWrap="wrap" gap={1}>
176      {options.map(one => chip(kit, `${key}:${one.id}`, one.label, one.id === value, () => input.onPick(one.id)))}
177    </Box>
178  ) : null
179  return { trigger, menu }
180}
181
182/** A screen's title, bold white, its count label at the right, the accent rule under them. */
183export function titleBlock(kit: Kit, title: string, count: string): RenderElement {
184  const { Box, Text } = kit.els
185  return (
186    <Box key="title" flexDirection="column">
187      <Box key="title-row" flexDirection="row" justifyContent="space-between" alignItems="center">
188        <Text bold color={THEME.white}>
189          {title}
190        </Text>
191        <Text color={THEME.gold}>{count.toUpperCase()}</Text>
192      </Box>
193      {accentRule(kit)}
194    </Box>
195  )
196}
197
198/** A panel: its label at the top left, a link at the top right, rows split by soft dividers. */
199export function panel(kit: Kit, key: string, title: string, link: RenderElement | null, rows: RenderElement[]): RenderElement {
200  const { Box } = kit.els
201  const body: RenderElement[] = []
202  rows.forEach((row, i) => {
203    if (i > 0) {
204      body.push(divider(kit, `${key}-divider-${i}`))
205    }
206    body.push(row)
207  })
208  return (
209    <Box key={key} flexDirection="column" borderStyle="round" borderColor={THEME.line} backgroundColor={THEME.panel} paddingX={kit.isRich ? 2 : 1} paddingY={kit.isRich ? 1 : 0}>
210      <Box key={`${key}-head`} flexDirection="row" justifyContent="space-between" alignItems="center">
211        {label(kit, title)}
212        {link}
213      </Box>
214      {body}
215    </Box>
216  )
217}
218
219/** A soft divider inside a panel or card: a thin line on the desktop, a rule of dashes in text. */
220export function divider(kit: Kit, key: string): RenderElement {
221  const { Box, Text } = kit.els
222  if (!kit.isRich) {
223    return (
224      <Text key={key} color={THEME.lineSoft}>
225        {'─'.repeat(Math.max(4, kit.cols - 6))}
226      </Text>
227    )
228  }
229  return (
230    <Box key={key} height={1} flexDirection="column" justifyContent="center">
231      <Box width="100%" height="8%" backgroundColor={THEME.lineSoft} />
232    </Box>
233  )
234}
235
236// ── Where it draws ─────────────────────────────────────────────────────
237
238/** The surfaces an Engram draws on now, from `whereItDraws` with the pane closed. */
239export function drawingPlaces(surfaces: Surfaces, engram: Engram): string[] {
240  const drawing = whereItDraws(surfaces, engram, false)
241  return [...(drawing.opensPane ? ['Pane'] : []), ...(drawing.band ? ['Band'] : [])]
242}
243
244/** "drawing in Pane and Band", for the awake strip. */
245export function drawingLine(surfaces: Surfaces, engram: Engram): string {
246  const places = drawingPlaces(surfaces, engram)
247  return places.length ? `drawing in ${places.join(' and ')}` : 'drawing nowhere: its surfaces are off'
248}
249
250/** One row of the Where it draws panel: whether it draws on that surface now, and why. */
251type WhereRow = { icon: SurfaceIcon; isOn: boolean; text: string }
252
253/** Where an Engram draws, surface by surface, as `whereItDraws` decides it under the surfaces setting. */
254export function whereRows(surfaces: Surfaces, engram: Engram): WhereRow[] {
255  const shows = engram.vessel.shows
256  const closed = whereItDraws(surfaces, engram, false)
257  const open = whereItDraws(surfaces, engram, true)
258  const pane: WhereRow = !shows.includes('pane')
259    ? { icon: 'pane', isOn: false, text: "Doesn't show in the pane. Opened by hand, the pane draws its band view." }
260    : closed.opensPane
261      ? { icon: 'pane', isOn: true, text: 'Draws in the pane, which opens by itself when it wakes.' }
262      : { icon: 'pane', isOn: false, text: 'The Pane switch is off: the pane opens only when you ask.' }
263  const band: WhereRow = !shows.includes('band')
264    ? { icon: 'band', isOn: false, text: "Doesn't draw in the band." }
265    : !surfaces.band
266      ? { icon: 'band', isOn: false, text: 'The Band switch is off.' }
267      : open.band
268        ? { icon: 'band', isOn: true, text: 'Draws in the band above the prompt.' }
269        : { icon: 'band', isOn: true, text: 'Draws in the band, hidden while the pane is open.' }
270  const shrine: WhereRow = shows.includes('shrine')
271    ? { icon: 'shrine', isOn: false, text: 'Made for the Shrine too, which arrives in a later version.' }
272    : { icon: 'shrine', isOn: false, text: "Doesn't draw in the Shrine." }
273  return [pane, band, shrine]
274}
275
276// ── The page ───────────────────────────────────────────────────────────
277
278const RIGHTS: Record<Engram['rights'], string> = {
279  original: 'Original: made by its author.',
280  licensed: 'Licensed: shared with permission.',
281}
282
283/** A screen's side padding, in cells: roomier on the desktop. */
284export function screenPad(kit: Kit): number {
285  return kit.isRich ? 2 : 1
286}
287
288/** A screen's width inside its padding, in cells. */
289export function screenInner(kit: Kit): number {
290  return kit.cols - 2 * screenPad(kit)
291}
292
293/**
294 * The preview's rows, from the pane's: a pane view about half the pane tall,
295 * a band-only Engram's band strip about a third, each within bounds so it
296 * neither shrinks to a sliver nor pushes the page off the pane.
297 */
298export function previewRows(engram: Engram, paneRows = 0): number {
299  const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n))
300  return engram.vessel.shows.includes('pane') ? clamp(Math.round(paneRows * 0.45), 14, 28) : clamp(Math.round(paneRows * 0.32), 10, 18)
301}
302
303/** What the page draws and what its buttons do, from register.tsx. */
304export type PageInput = {
305  engram: Engram
306  isAwake: boolean
307  surfaces: Surfaces
308  preview: Preview
309  /** The live scene at the preview's mood, `screenInner` wide and `previewRows` tall: desktop only. */
310  scene: RenderElement | null
311  /** The pane's rows: the page fills them, and the preview is sized from them. */
312  rows: number
313  /** The terminal's picture of the preview's mood: its face. */
314  face: string
315  back: { onPress: () => void }
316  onSurfaces: () => void
317  onMood: (mood: Mood) => void
318  onError: () => void
319  onAwaken: () => void
320  onSleep: () => void
321  /** Remix with Claude: on every Engram's page. */
322  onRemix: () => void
323  /** Publish: on the pages of your own Engrams alone. */
324  onPublish: (() => void) | undefined
325}
326
327/**
328 * The preview: the live scene alone, edge to edge, nothing written over it:
329 * the chips under it say which mood it shows. In text, the mood and the face.
330 */
331function hudPreview(kit: Kit, input: PageInput): RenderElement {
332  const { Box, Text } = kit.els
333  if (!kit.isRich || input.scene === null) {
334    const look = input.preview.isError ? FRAME_STATES.error : FRAME_STATES[MOOD_STATE[input.preview.mood]]
335    return (
336      <Box key="preview" flexDirection="column" borderStyle="round" borderColor={THEME.line} paddingX={1}>
337        <Text key="preview-mood" bold color={input.preview.isError ? THEME.errorText : THEME.amber}>
338          {look.name}
339        </Text>
340        <Text key="preview-face" color={THEME.frost}>
341          {input.face}
342        </Text>
343      </Box>
344    )
345  }
346  return (
347    <Box key="preview" width={screenInner(kit)} height={previewRows(input.engram, input.rows)} overflow="hidden" backgroundColor={THEME.preview}>
348      {input.scene}
349    </Box>
350  )
351}
352
353/** A small card of the page: its label, and what it says, with room around both. */
354function factCard(kit: Kit, key: string, title: string, text: string, width: number): RenderElement {
355  const { Box, Text } = kit.els
356  return (
357    <Box key={key} flexDirection="column" width={width} gap={kit.isRich ? 1 : 0} borderStyle="round" borderColor={THEME.line} backgroundColor={THEME.card} paddingX={kit.isRich ? 2 : 1} paddingY={kit.isRich ? 1 : 0}>
358      {label(kit, title, `${key}-label`)}
359      <Text key={`${key}-text`} color={THEME.frost} wrap="wrap">
360        {text}
361      </Text>
362    </Box>
363  )
364}
365
366/**
367 * An Engram's page, filling the pane. Back, and Awaken (gold) or Sleep at
368 * the header's right; the live preview, about half the pane tall; the mood
369 * chips and Error under it, which change the preview only; the name with
370 * Remix with Claude (and Publish, on your own) at its right; what it is; and
371 * three facts: what it draws, where it comes from, its rights.
372 * Nothing is said twice: the action says whether it is awake, the chips say
373 * the preview's mood, the Draws fact says where it draws.
374 */
375export function engramPage(kit: Kit, input: PageInput): RenderElement {
376  const { Box, Text } = kit.els
377  const { engram, preview } = input
378  const id = engram.id
379  const inner = screenInner(kit)
380  const gap = kit.isRich ? 2 : 1
381  const perRow = inner >= 60 ? 3 : inner >= 40 ? 2 : 1
382  const factCols = Math.floor((inner - gap * (perRow - 1)) / perRow)
383  const facts = [
384    factCard(kit, 'fact-draws', 'Draws', `${engram.plugin ? 'its own' : engram.vessel.scene} scene · ${showsLabel(engram)}`, factCols),
385    factCard(
386      kit,
387      'fact-source',
388      'Source',
389      `${engram.plugin ? `Engram plugin ${engram.plugin.name || engram.id}` : 'Bundled with Eidola'} · v${engram.version} · by ${engram.author}`,
390      factCols,
391    ),
392    factCard(kit, 'fact-rights', 'Rights', RIGHTS[engram.rights], factCols),
393  ]
394  const factRows: RenderElement[] = []
395  for (let i = 0; i < facts.length; i += perRow) {
396    factRows.push(
397      <Box key={`facts:${i}`} flexDirection="row" alignItems="stretch" gap={gap}>
398        {facts.slice(i, i + perRow)}
399      </Box>,
400    )
401  }
402  return (
403    <Box key={`page:${id}`} flexDirection="column" width={kit.cols} minHeight={input.rows} paddingX={screenPad(kit)} paddingY={1} gap={gap} backgroundColor={THEME.void}>
404      {header(
405        kit,
406        { key: 'page-back', ...input.back },
407        input.isAwake ? button(kit, 'page-sleep', 'Sleep', input.onSleep, 'danger') : button(kit, 'page-awaken', 'Awaken', input.onAwaken, 'primary'),
408      )}
409      <Box key="hero" flexDirection="column" gap={1}>
410        {hudPreview(kit, input)}
411        <Box key="preview-moods" flexDirection="row" flexWrap="wrap" gap={1}>
412          {PREVIEW_MOODS.map(mood => chip(kit, `preview-mood:${mood}`, MOOD_NAMES[mood], !preview.isError && preview.mood === mood, () => input.onMood(mood)))}
413          {chip(kit, 'preview-error', 'Error', preview.isError, input.onError)}
414        </Box>
415      </Box>
416      <Box key="about" flexDirection="column" gap={1}>
417        <Box key="about-head" flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="center" gap={1}>
418          <Text key="about-name" bold color={THEME.white}>
419            {engram.name}
420          </Text>
421          <Box key="actions" flexDirection="row" flexWrap="wrap" gap={1}>
422            {button(kit, 'page-remix', 'Remix with Claude', input.onRemix)}
423            {input.onPublish ? button(kit, 'page-publish', 'Publish', input.onPublish) : null}
424          </Box>
425        </Box>
426        <Text key="about-description" color={THEME.body} wrap="wrap">
427          {engram.description}
428        </Text>
429      </Box>
430      <Box key="facts" flexDirection="column" gap={gap}>
431        {factRows}
432      </Box>
433    </Box>
434  )
435}
436
hooks/blend-test.ts 51 lines
1// /eidola blend: can a drawing change mood without being replaced?
2//
3// The source never changes; only the drawing's height does, by 0, 1 or 2px.
4// CSS media queries inside it read that height and pick a mood, and CSS
5// transitions carry it there. If the surface only resizes the frame, the
6// disc glides and the colour shifts while the bar keeps filling; if it
7// reloads the frame, the bar and the ring start over.
8
9/** Pixels the drawing loses for each mood: the signal itself. */
10export const BLEND_STEPS = ['idle', 'working', 'attention'] as const
11
12export function blendTestSvg(width: number, height: number): string {
13  const W = Math.round(width)
14  const H = Math.round(height)
15  const cx = W / 2
16  // Height H is mood 0, H - 1 mood 1, H - 2 mood 2.
17  const mq = (k: number) =>
18    k === 0 ? `(min-height:${H - 0.5}px)` : k === 1 ? `(max-height:${H - 0.5}px) and (min-height:${H - 1.5}px)` : `(max-height:${H - 1.5}px)`
19  const looks = [
20    { bg: '#0b2a36', x: -W * 0.28, label: 'idle' },
21    { bg: '#123d24', x: 0, label: 'working' },
22    { bg: '#4a1a12', x: W * 0.28, label: 'attention' },
23  ]
24  const css =
25    // Smooth moves between moods.
26    '.bg{transition:fill 1.2s ease}.disc{transition:transform 1.2s cubic-bezier(.4,0,.2,1)}' +
27    '.lab{display:none}' +
28    looks
29      .map((l, k) => `@media ${mq(k)}{.bg{fill:${l.bg}}.disc{transform:translateX(${Math.round(l.x)}px)}.l${k}{display:inline}}`)
30      .join('') +
31    // Clocks that start over if the frame reloads.
32    '@keyframes fill{from{transform:scaleX(0)}to{transform:scaleX(1)}}' +
33    '.bar{transform-box:fill-box;transform-origin:0 50%;animation:fill 20s linear infinite}' +
34    '@keyframes spin{to{transform:rotate(360deg)}}' +
35    `.ring{transform-origin:${cx}px 200px;animation:spin 6s linear infinite}`
36
37  return (
38    `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">` +
39    `<style>${css}</style>` +
40    `<rect class="bg" width="100%" height="100%" fill="#222"/>` +
41    `<text x="${cx}" y="60" fill="#fff" font-family="sans-serif" font-size="20" text-anchor="middle">Blend test</text>` +
42    looks.map((l, k) => `<text class="lab l${k}" x="${cx}" y="95" fill="#ffd27a" font-family="sans-serif" font-size="26" font-weight="700" text-anchor="middle">${l.label}</text>`).join('') +
43    `<g class="ring"><circle cx="${cx}" cy="200" r="60" fill="none" stroke="#5ff6ff" stroke-width="6" stroke-dasharray="90 287"/></g>` +
44    `<circle class="disc" cx="${cx}" cy="360" r="34" fill="#fff"/>` +
45    `<text x="${cx}" y="450" fill="#aaa" font-family="sans-serif" font-size="13" text-anchor="middle">20s bar: keeps filling = no reload</text>` +
46    `<rect x="${Math.round(W * 0.1)}" y="465" width="${Math.round(W * 0.8)}" height="12" fill="#333"/>` +
47    `<rect class="bar" x="${Math.round(W * 0.1)}" y="465" width="${Math.round(W * 0.8)}" height="12" fill="#5ff6ff"/>` +
48    '</svg>'
49  )
50}
51
hooks/measure.ts 49 lines
1// /eidola measure: what the pane and band report about their size, beside
2// drawings of a known size, so a screenshot gives pixels per cell on each
3// surface. The stage is sized from those numbers, not from a guess.
4
5/** The reference square's side, in CSS pixels. */
6export const REFERENCE_PX = 100
7
8/** A REFERENCE_PX square: a 10px grid, every 50px darker, a red edge. */
9export function referenceSvg(): string {
10  const n = REFERENCE_PX
11  const lines: string[] = []
12  for (let at = 10; at < n; at += 10) {
13    const stroke = at % 50 === 0 ? '#333' : '#bbb'
14    lines.push(`<path d="M${at} 0V${n}M0 ${at}H${n}" stroke="${stroke}" stroke-width="1"/>`)
15  }
16  return (
17    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${n}" width="${n}" height="${n}">` +
18    `<rect width="${n}" height="${n}" fill="#fff"/>` +
19    lines.join('') +
20    `<rect x="1" y="1" width="${n - 2}" height="${n - 2}" fill="none" stroke="#e00" stroke-width="2"/>` +
21    `<text x="${n / 2}" y="${n / 2 + 5}" font-family="sans-serif" font-size="14" text-anchor="middle" fill="#e00">${n}px</text>` +
22    `</svg>`
23  )
24}
25
26/** The lines the pane prints in measure mode. */
27export function paneReport(surface: string, placement: string, bodyColumns: number, bodyRows: number): string[] {
28  return [
29    `Measure · ${surface} · pane (${placement})`,
30    `bodyColumns ${bodyColumns} · bodyRows ${bodyRows}`,
31    'Blue: a Box at height 100%. Yellow: a Box bodyColumns × bodyRows cells.',
32  ]
33}
34
35/** The lines the band prints in measure mode. */
36export function bandReport(surface: string, bodyColumns: number, maxRows: number, bodyRows: number): string[] {
37  return [`Measure · ${surface} · band`, `bodyColumns ${bodyColumns} · maxRows ${maxRows} · bodyRows ${bodyRows}`]
38}
39
40export const MEASURE_HELP =
41  'Measure on. The pane and band show their reported size beside a 100px square:\n' +
42  '  blue fills a Box at height 100%, if the surface honours it\n' +
43  '  yellow outlines a Box sized bodyColumns × bodyRows in cells\n' +
44  'Screenshot the whole window and send it. Run /eidola measure again to turn it off.'
45
46/** The measure view's colours: a blue ground, its box outlined in yellow. */
47export const MEASURE_GROUND = '#1e3a5f'
48export const MEASURE_EDGE = 'yellow'
49
hooks/media-test.ts 48 lines
1// Media test: can a native surface play anything richer than a CSS sprite?
2// Each case wraps a tiny clip (a coloured square that slides, frames
3// numbered 1-8) in an SVG, since Svg is the only picture desktop, VS Code
4// and mobile draw. The base64 strings are generated; regenerate rather than
5// hand-edit.
6
7export const TEST_GIF_BASE64 =
8  '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'
9
10export const TEST_WEBM_BASE64 =
11  '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'
12
13const SIZE = 96
14
15/** An animated GIF inside an SVG <image>. */
16export function gifInSvg(): string {
17  return (
18    `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ` +
19    `viewBox="0 0 32 32" width="${SIZE}" height="${SIZE}">` +
20    `<image width="32" height="32" style="image-rendering:pixelated" ` +
21    `href="data:image/gif;base64,${TEST_GIF_BASE64}" ` +
22    `xlink:href="data:image/gif;base64,${TEST_GIF_BASE64}"/></svg>`
23  )
24}
25
26/** A looping, muted WebM inside an SVG <foreignObject> <video>. */
27export function webmInSvg(): string {
28  return (
29    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="${SIZE}" height="${SIZE}">` +
30    `<foreignObject x="0" y="0" width="32" height="32">` +
31    `<video xmlns="http://www.w3.org/1999/xhtml" autoplay="" muted="" loop="" playsinline="" ` +
32    `width="32" height="32" style="image-rendering:pixelated" ` +
33    `src="data:video/webm;base64,${TEST_WEBM_BASE64}"></video>` +
34    `</foreignObject></svg>`
35  )
36}
37
38export type MediaCase = { key: string; label: string; source: string; isInteractive: boolean }
39
40/** A and B differ only in how the surface draws the Svg; C tries real video. */
41export function mediaCases(): MediaCase[] {
42  return [
43    { key: 'gif-frame', label: 'A · GIF in SVG, sandboxed frame', source: gifInSvg(), isInteractive: true },
44    { key: 'gif-image', label: 'B · GIF in SVG, plain image', source: gifInSvg(), isInteractive: false },
45    { key: 'webm-frame', label: 'C · WebM in SVG, sandboxed frame', source: webmInSvg(), isInteractive: true },
46  ]
47}
48
hooks/net-probe.ts 39 lines
1// Network probes for /eidola: can hook code on this session's host reach
2// the places a Shrine bridge would post to? In a cloud session the host is
3// the cloud machine, so 127.0.0.1 there is the container, not your computer.
4
5// The probe itself (probeLine) lives in register.tsx: the engine follows $
6// only into functions declared in the same file.
7
8export type NetProbe = { label: string; url: string }
9
10export const NET_PROBES: readonly NetProbe[] = [
11  { label: 'eidola.app (hosted relay)', url: 'https://eidola.app/' },
12  { label: 'example.com (control)', url: 'https://example.com/' },
13  { label: 'api.github.com (a host cloud environments usually allow)', url: 'https://api.github.com/' },
14  { label: 'Shrine on this host (127.0.0.1:9743)', url: 'http://127.0.0.1:9743/shrine/' },
15]
16
17export const PROBE_TIMEOUT_MS = 6000
18
19export type Outcome =
20  | { kind: 'status'; status: number }
21  | { kind: 'error'; message: string }
22  | { kind: 'timeout' }
23
24function shorten(text: string, max = 140): string {
25  const one = text.replace(/\s+/g, ' ').trim()
26  return one.length > max ? `${one.slice(0, max - 1)}…` : one
27}
28
29export function describeOutcome(probe: NetProbe, outcome: Outcome): string {
30  switch (outcome.kind) {
31    case 'status':
32      return `${probe.label}: reached, HTTP ${outcome.status}`
33    case 'timeout':
34      return `${probe.label}: no answer in ${PROBE_TIMEOUT_MS / 1000}s`
35    case 'error':
36      return `${probe.label}: failed (${shorten(outcome.message) || 'no reason given'})`
37  }
38}
39
hooks/placement.ts 132 lines
1// Where an Engram draws. One surfaces setting for every Engram, set in
2// /config or with `/eidola place <switch> on|off`: the Pane and Band
3// switches, and "hide the band while the pane is open". An Engram draws on a
4// surface only if its switch is on and the Engram's `shows` lists it.
5// (`shows` may list the Shrine; nothing draws there until the Shrine and its
6// switch arrive.)
7
8import type { PluginOptions } from 'claude-code'
9
10import type { ShowPlace } from './engram-types'
11
12/** The surfaces setting: one switch per surface, and the band's manners. */
13export type Surfaces = {
14  /** The pane: the awake Engram draws there, and the pane opens by itself. */
15  pane: boolean
16  /** The band above the prompt. */
17  band: boolean
18  /** The band steps aside while the pane is open, for an Engram that shows in the pane. */
19  hideBand: boolean
20}
21
22/** Pane on, Band on, the band hidden while the pane is open: 0.6.0's `auto`. */
23export const DEFAULT_SURFACES: Surfaces = { pane: true, band: true, hideBand: true }
24
25/** The switches, in the order `/eidola place` lists them. */
26export const SWITCHES = ['pane', 'band', 'hide'] as const
27export type Switch = (typeof SWITCHES)[number]
28
29/** Each switch's field in the surfaces setting. */
30const FIELDS: Record<Switch, keyof Surfaces> = { pane: 'pane', band: 'band', hide: 'hideBand' }
31
32/** Each switch's `userConfig` option. */
33export const OPTION_KEYS: Record<Switch, string> = { pane: 'pane', band: 'band', hide: 'hideBandWhilePaneOpen' }
34
35export const SWITCH_HELP: Record<Switch, string> = {
36  pane: 'the pane; on, it opens by itself for an Engram that shows there',
37  band: 'the band above the prompt',
38  hide: 'hide the band while the pane is open',
39}
40
41export function isSwitch(value: unknown): value is Switch {
42  return typeof value === 'string' && (SWITCHES as readonly string[]).includes(value)
43}
44
45/** `on` or `off` as a boolean; anything else, undefined. */
46export function readOnOff(value: string): boolean | undefined {
47  return value === 'on' ? true : value === 'off' ? false : undefined
48}
49
50/** A switch's value in the setting. */
51export function switchOf(surfaces: Surfaces, one: Switch): boolean {
52  return surfaces[FIELDS[one]]
53}
54
55/** The surfaces setting from the options; a missing or odd value reads as its default. */
56export function readSurfaces(options: PluginOptions): Surfaces {
57  const flag = (one: Switch): boolean => {
58    const value = options[OPTION_KEYS[one]]
59    return typeof value === 'boolean' ? value : DEFAULT_SURFACES[FIELDS[one]]
60  }
61  return { pane: flag('pane'), band: flag('band'), hideBand: flag('hide') }
62}
63
64export function readStatusLine(options: PluginOptions): boolean {
65  return options['statusLine'] !== false
66}
67
68/** The setting in one line: `pane on · band on (hidden while the pane is open)`. */
69export function surfacesLine(surfaces: Surfaces): string {
70  const onOff = (is: boolean) => (is ? 'on' : 'off')
71  const hidden = surfaces.band && surfaces.hideBand ? ' (hidden while the pane is open)' : ''
72  return `pane ${onOff(surfaces.pane)} · band ${onOff(surfaces.band)}${hidden}`
73}
74
75/** Where an Engram draws, as `whereItDraws` decides it. */
76export type Drawing = {
77  /** The pane opens by itself for it (at session start, on attach, on /awaken). */
78  opensPane: boolean
79  /**
80   * What the pane draws of it when the pane is open, by itself or because you
81   * asked: its pane view where its `shows` lists the pane, else its band view.
82   * An Engram never stops you opening the pane.
83   */
84  paneView: 'pane' | 'band'
85  /** The band draws it now. */
86  band: boolean
87}
88
89/**
90 * Where an Engram draws: on a surface only if that switch is on and its
91 * `shows` lists it; the band steps aside while the pane is open if that option
92 * is on and the Engram shows in the pane; and one that doesn't show in the
93 * pane (band-only) never opens the pane by itself, and keeps its band.
94 */
95export function whereItDraws(
96  surfaces: Surfaces,
97  engram: { vessel: { shows: readonly ShowPlace[] } },
98  isPaneOpen: boolean,
99): Drawing {
100  const shows = engram.vessel.shows
101  const isPane = shows.includes('pane')
102  return {
103    opensPane: surfaces.pane && isPane,
104    paneView: isPane ? 'pane' : 'band',
105    band: surfaces.band && shows.includes('band') && !(surfaces.hideBand && isPaneOpen && isPane),
106  }
107}
108
109/** Every switch on and the band never hidden: where an Engram can draw at all. */
110const EVERYWHERE: Surfaces = { pane: true, band: true, hideBand: false }
111
112/** Where an Engram can draw, of the pane and the band, whatever the switches: the picker's filters. */
113export function drawsIn(engram: { vessel: { shows: readonly ShowPlace[] } }): { pane: boolean; band: boolean } {
114  const drawn = whereItDraws(EVERYWHERE, engram, false)
115  return { pane: drawn.opensPane, band: drawn.band }
116}
117
118/**
119 * The picker's "where it shows" text, from the list form of `shows`: the
120 * places it draws, `pane + band`, or the one place, `band only`. The Shrine
121 * isn't a surface yet, so it is named only for an Engram that shows nowhere
122 * else (`shrine only`).
123 */
124export function showsLabel(engram: { vessel: { shows: readonly ShowPlace[] } }): string {
125  const drawn = drawsIn(engram)
126  const places = (['pane', 'band'] as const).filter(place => drawn[place])
127  if (places.length === 0) {
128    return `${engram.vessel.shows.join(' + ')} only`
129  }
130  return places.length === 1 ? `${places[0]} only` : places.join(' + ')
131}
132