@litfamily/litmuse 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/install.mjs CHANGED
@@ -5,11 +5,12 @@ import { preflightDestinations, writeFileAtomic, copyFileAtomic } from './safe-w
5
5
  import { muse, museVersion, installedPlugin } from './muse.mjs';
6
6
  import { stageState, stageBundle, packageVersion } from './bundle.mjs';
7
7
  import { expectedApprovals, approvalStates } from './approvals.mjs';
8
- import { agentFilePlan, installAgentFile } from './agent-file.mjs';
8
+ import { agentFileAsks, agentFilePlan, installAgentFile } from './agent-file.mjs';
9
9
  import { MOVED, movedSkill, installLine } from '../plugin/hooks/lib/moved.mjs';
10
10
  import { SHELF, extensionsNotice, leftoverRuntime } from '../plugin/hooks/lib/extensions.mjs';
11
11
  import { noticeHash, wasShown, recordShown } from './shown.mjs';
12
12
  import { survey, findings, CLI } from './extensions.mjs';
13
+ import { planRows } from './install-cards.mjs';
13
14
 
14
15
  function remedy(state, detail, p) {
15
16
  const saved = `${p.stage}.saved-${new Date().toISOString().slice(0, 10)}`;
@@ -63,53 +64,98 @@ function samePath(a, b) {
63
64
  return real(a) === real(b);
64
65
  }
65
66
 
66
- export async function install({ env = process.env, flags = {}, interactive = false, ask, print = console.log }) {
67
+ const counted = (list) => {
68
+ const of = (kind, word) => {
69
+ const n = list.filter((a) => a.kind === kind).length;
70
+ return n ? [`${n} ${word}${n === 1 ? '' : 's'}`] : [];
71
+ };
72
+ return `${list.length} (${[...of('hook', 'hook'), ...of('agent', 'agent')].join(', ')})`;
73
+ };
74
+
75
+ export async function install({ env = process.env, flags = {}, interactive = false, ask, print = console.log, cards = null }) {
67
76
  const p = paths(env);
68
77
  const version = packageVersion();
69
78
  const scope = flags.scope || 'user';
70
- print(`LitMuse ${version} installer for Muse Code`);
79
+ // With cards, these lines are drawn as rows and panels instead.
80
+ const plain = cards ? () => {} : print;
81
+ let stage = 'Check';
82
+ const fail = (what, ...notes) => {
83
+ if (cards) {
84
+ cards.panel({
85
+ title: 'INSTALL STOPPED', bad: true,
86
+ sections: [{ rows: [
87
+ { mark: 'fail', label: 'Stage', value: stage }, { mark: 'fail', label: 'Reason', value: what },
88
+ { mark: 'note', label: 'Next', value: notes.length ? 'the lines below' : 'fix this, then run the install again' },
89
+ ] }],
90
+ });
91
+ if (notes.length) print('');
92
+ for (const line of notes) print(line);
93
+ } else for (const line of [`FAIL ${what}`, ...notes]) print(line);
94
+ return 1;
95
+ };
96
+ const section = (heading, lines) => {
97
+ if (cards) {
98
+ cards.text(heading, lines);
99
+ return;
100
+ }
101
+ print('');
102
+ print(heading);
103
+ for (const line of lines) print(line);
104
+ };
105
+ plain(`LitMuse ${version} installer for Muse Code`);
106
+ cards?.intro(`Installs into ${p.data}. Your Muse settings are backed up first.`);
71
107
 
72
108
  const major = Number(process.versions.node.split('.')[0]);
73
109
  if (major < 20) {
74
- print(`FAIL Node.js ${process.versions.node} is too old; LitMuse needs Node.js 20 or newer.`);
75
- return 1;
110
+ return fail(`Node.js ${process.versions.node} is too old; LitMuse needs Node.js 20 or newer.`);
76
111
  }
77
112
  const mv = museVersion(env);
78
113
  if (!mv) {
79
- print('FAIL muse was not found on PATH. Install Muse Code first (https://dev.meta.ai/docs/muse-code), sign in once, then run this again.');
80
- return 1;
114
+ return fail('muse was not found on PATH. Install Muse Code first (https://dev.meta.ai/docs/muse-code), sign in once, then run this again.');
81
115
  }
82
- print(`Host: ${mv}`);
116
+ plain(`Host: ${mv}`);
83
117
 
84
118
  const st = preflightDestinations(p) ?? stageState(p);
85
119
  if (['symlinked', 'foreign', 'modified'].includes(st.state)) {
86
- print(`FAIL destination ${st.state}: ${st.detail}`);
87
- print(remedy(st.state, st.detail, p));
88
- if (st.state === 'modified') for (const line of extensionRemedy(st.changed, p)) print(line);
89
- print('No files written.');
90
- return 1;
120
+ return fail(
121
+ `destination ${st.state}: ${st.detail}`,
122
+ remedy(st.state, st.detail, p),
123
+ ...(st.state === 'modified' ? extensionRemedy(st.changed, p) : []),
124
+ 'No files written.',
125
+ );
91
126
  }
92
127
 
93
128
  const existing = installedPlugin(env);
94
129
  const existingSource = existing?.source?.path;
95
130
  if (existingSource && !samePath(existingSource, p.stage)) {
96
- print(`FAIL Muse already has LitMuse ${existing.version ?? ''} installed from ${existingSource}.`.replace(' ', ' '));
97
- print(`This installer manages the copy in ${p.stage}. Remove the other one first with: muse plugins remove litmuse (this also clears its approvals), then run install again.`);
98
- print('No files written.');
99
- return 1;
131
+ return fail(
132
+ `Muse already has LitMuse ${existing.version ?? ''} installed from ${existingSource}.`.replace(' ', ' '),
133
+ `This installer manages the copy in ${p.stage}. Remove the other one first with: muse plugins remove litmuse (this also clears its approvals), then run install again.`,
134
+ 'No files written.',
135
+ );
100
136
  }
101
137
  const installArgs = existing ? ['plugins', 'update', 'litmuse', '--json'] : ['plugins', 'install', p.stage, '--scope', scope, '--json'];
102
138
  const approvals = expectedApprovals();
103
139
 
104
- print('');
105
- print('Plan');
106
- print(` bundle ${p.stage}${st.state === 'owned' ? ` (replaces LitMuse ${st.version})` : ''}`);
107
- print(` backups ${p.backups} (Muse settings.json and installed.json, when present)`);
108
- print(` receipt ${p.receipt}`);
109
- print(` rules file ${agentFilePlan({ env, flags })}`);
110
- print(` muse muse ${installArgs.join(' ')}`);
111
- print(` approvals up to ${approvals.length} capabilities may need your approval in Muse (hooks and agents):`);
112
- for (const a of approvals) print(` ${a.id}`);
140
+ const plan = [
141
+ ['bundle', `${p.stage}${st.state === 'owned' ? ` (replaces LitMuse ${st.version})` : ''}`],
142
+ ['backups', `${p.backups} (Muse settings.json and installed.json, when present)`],
143
+ ['receipt', p.receipt],
144
+ ['rules file', agentFilePlan({ env, flags })],
145
+ ['muse', `muse ${installArgs.join(' ')}`],
146
+ ['approvals', `up to ${approvals.length} capabilities may need your approval in Muse (hooks and agents):`],
147
+ ];
148
+ if (cards) {
149
+ cards.panel({
150
+ title: `LitMuse ${version} install plan`,
151
+ sections: [{ rows: planRows([['Host', mv], ...plan.map(([label, value]) => [label[0].toUpperCase() + label.slice(1), value]).slice(0, -1), ['Approvals', `up to ${counted(approvals)}`]]) }],
152
+ });
153
+ } else {
154
+ print('');
155
+ print('Plan');
156
+ for (const [label, value] of plan) print(` ${label.padEnd(12)}${value}`);
157
+ for (const a of approvals) print(` ${a.id}`);
158
+ }
113
159
 
114
160
  if (flags.dryRun) {
115
161
  print('');
@@ -126,51 +172,77 @@ export async function install({ env = process.env, flags = {}, interactive = fal
126
172
  const leftovers = [leftoverRuntime(p.data)].filter((d) => existsSync(d));
127
173
 
128
174
  const written = [];
175
+ const steps = cards?.work(`Installing LitMuse ${version}`, 'Install steps', [
176
+ ['Backups', 'save your Muse settings'], ['Bundle', 'copy the plugin bundle'], ['Validate', 'muse plugins validate'], ['Muse', `muse plugins ${existing ? 'update' : 'install'}`],
177
+ ]);
178
+ const step = (name) => {
179
+ stage = name;
180
+ steps?.next();
181
+ };
182
+ const stopped = (...told) => {
183
+ steps?.fail();
184
+ return fail(...told);
185
+ };
186
+ step('Backups');
129
187
  written.push(...backupHostFiles(p));
188
+ step('Bundle');
130
189
  stageBundle(p);
131
190
  written.push(p.stage);
132
191
 
192
+ step('Validate');
133
193
  const validation = muse(env, ['plugins', 'validate', p.stage, '--json']);
134
194
  const diagnostics = validation.json?.diagnostics ?? [];
135
195
  if (!validation.ok || validation.json?.valid !== true || diagnostics.length) {
136
- print('FAIL muse plugins validate rejected the bundle:');
137
- for (const d of diagnostics) print(` ${d.code ?? 'diagnostic'}: ${d.message ?? JSON.stringify(d)}`);
138
- if (!diagnostics.length) print(` ${validation.stderr.trim() || validation.stdout.trim()}`);
139
- print('Muse was left unchanged.');
140
- return 1;
196
+ return stopped(
197
+ 'muse plugins validate rejected the bundle:',
198
+ ...diagnostics.map((d) => ` ${d.code ?? 'diagnostic'}: ${d.message ?? JSON.stringify(d)}`),
199
+ ...(diagnostics.length ? [] : [` ${validation.stderr.trim() || validation.stdout.trim()}`]),
200
+ 'Muse was left unchanged.',
201
+ );
141
202
  }
142
203
 
204
+ step('Muse');
143
205
  const result = muse(env, installArgs);
144
206
  if (!result.ok) {
145
- print(`FAIL ${result.command} exited ${result.status}:`);
146
- print(` ${(result.stderr || result.stdout).trim().split('\n').slice(0, 6).join('\n ')}`);
147
- return 1;
207
+ return stopped(`${result.command} exited ${result.status}:`, ` ${(result.stderr || result.stdout).trim().split('\n').slice(0, 6).join('\n ')}`);
148
208
  }
149
209
  const cachePath = result.json?.installed?.cache_path;
150
210
  written.push(p.museInstalled);
151
211
  if (cachePath) written.push(cachePath);
152
- print('');
153
- print(existing
154
- ? `Installed: LitMuse ${version} is updated in Muse from ${p.stage}. Skills and commands are active now.`
155
- : `Installed: LitMuse ${version} is installed in Muse at ${scope} scope. Skills and commands are active now.`);
212
+ const installed = existing
213
+ ? `LitMuse ${version} is updated in Muse from ${p.stage}. Skills and commands are active now.`
214
+ : `LitMuse ${version} is installed in Muse at ${scope} scope. Skills and commands are active now.`;
215
+ plain('');
216
+ plain(`Installed: ${installed}`);
217
+ steps?.done();
156
218
 
157
219
  let states = approvalStates(muse(env, ['plugins', 'inspect', 'litmuse', '--json']).json);
158
220
  const pending = states.filter((s) => s.status !== 'trusted_enabled');
221
+ const named = (s) => ` ${s.id} (${s.what})`;
222
+ const asksApproval = pending.length > 0 && !flags.approve && interactive && Boolean(ask);
223
+ const questions = Number(asksApproval) + Number(agentFileAsks({ env, flags, interactive, ask, version }));
159
224
  if (pending.length) {
160
225
  let approve = Boolean(flags.approve);
161
226
  const decided = approve;
162
- if (!decided) {
163
- print('');
164
- print(`Muse runs plugin hooks and agents only after you approve them (an update re-arms the agent approvals, and the hook approvals whenever hook code changed). ${pending.length} are waiting:`);
165
- for (const s of pending) print(` ${s.id} (${s.what})`);
227
+ if (!decided && !(cards && asksApproval)) {
228
+ section(`Muse runs plugin hooks and agents only after you approve them (an update re-arms the agent approvals, and the hook approvals whenever hook code changed). ${pending.length} are waiting:`, pending.map(named));
166
229
  }
167
- if (!approve && interactive && ask) {
168
- approve = await ask(`Approve these ${pending.length} LitMuse capabilities now? [y/N] `);
230
+ if (asksApproval) {
231
+ approve = await ask(`Approve these ${pending.length} LitMuse capabilities now? [y/N] `, {
232
+ card: {
233
+ tag: `LIT 1/${questions}`,
234
+ title: 'Approvals',
235
+ note: `Muse runs plugin hooks and agents only after you approve them. Yes approves these ${counted(pending)} now; No prints the commands for later.`,
236
+ yes: `approve ${pending.length}`,
237
+ no: 'not now',
238
+ list: { hint: `l list all ${pending.length}`, heading: `${pending.length} LitMuse capabilities are waiting`, lines: pending.map((s) => (s.kind === 'hook' ? named(s) : ` ${s.id}`)) },
239
+ },
240
+ });
169
241
  }
170
242
  if (approve) {
171
243
  if (decided) {
172
- print('');
173
- print(`Approving ${pending.length} LitMuse capabilities...`);
244
+ plain('');
245
+ plain(`Approving ${pending.length} LitMuse capabilities...`);
174
246
  }
175
247
  const failed = [];
176
248
  for (const s of pending) {
@@ -178,32 +250,35 @@ export async function install({ env = process.env, flags = {}, interactive = fal
178
250
  if (!r.ok) failed.push(`${s.id}: ${(r.stderr || r.stdout).trim().split(/\r?\n/)[0]}`);
179
251
  }
180
252
  written.push(`${p.museSettings} (runtime_capabilities for litmuse)`);
181
- for (const f of failed) print(` FAIL approve ${f}`);
253
+ for (const f of failed) {
254
+ if (cards) cards.row('fail', 'Approve', f);
255
+ else print(` FAIL approve ${f}`);
256
+ }
182
257
  states = approvalStates(muse(env, ['plugins', 'inspect', 'litmuse', '--json']).json);
183
258
  const byId = new Map(states.map((s) => [s.id, s]));
184
259
  const approved = pending.filter((s) => byId.get(s.id)?.status === 'trusted_enabled');
185
260
  const still = states.filter((s) => s.status !== 'trusted_enabled');
186
261
  if (approved.length) {
187
- print('');
188
- print(`Approved ${approved.length} LitMuse capabilities:`);
189
- for (const s of approved) print(` ${s.id} (${s.what})`);
190
- }
191
- if (still.length) {
192
- print('');
193
- print(`${still.length} are still waiting:`);
194
- for (const s of still) print(` ${s.id} (${s.what})`);
195
- } else {
196
- print('No capabilities are still waiting for approval.');
262
+ if (cards) cards.row('done', 'Approved', counted(approved));
263
+ else section(`Approved ${approved.length} LitMuse capabilities:`, approved.map(named));
197
264
  }
198
- } else {
199
- print('');
200
- print('Approval needed. Run these when you are ready (or rerun install with --approve):');
201
- for (const s of pending) print(` muse plugins approve ${s.id}`);
265
+ // With cards, the closing card and the commands after it say what is left.
266
+ if (!cards && still.length) section(`${still.length} are still waiting:`, still.map(named));
267
+ else if (!cards) print('No capabilities are still waiting for approval.');
268
+ } else if (!cards) {
269
+ section('Approval needed. Run these when you are ready (or rerun install with --approve):', pending.map((s) => ` muse plugins approve ${s.id}`));
202
270
  }
203
271
  }
204
272
 
205
- print('');
206
- written.push(...await installAgentFile({ env, flags, interactive, ask, print, version, backupDir: p.backups }));
273
+ plain('');
274
+ let rules = null;
275
+ const rulesRow = (line) => {
276
+ const value = line.replace('AGENT_FILE: ', '');
277
+ rules = { mark: /^(created|updated|unchanged)/.test(value) ? 'done' : /^(off|skipped)/.test(value) ? 'note' : 'warn', label: 'Rules file', value };
278
+ };
279
+ written.push(...await installAgentFile({
280
+ env, flags, interactive, ask, print: cards ? rulesRow : print, version, backupDir: p.backups, tag: `LIT ${questions}/${questions}`,
281
+ }));
207
282
 
208
283
  const left = states.filter((s) => s.status !== 'trusted_enabled').length;
209
284
  // A new version (or a first install) arms the one-time notice for the next Muse session; a same-version reinstall
@@ -219,23 +294,50 @@ export async function install({ env = process.env, flags = {}, interactive = fal
219
294
  }, null, 2)}\n`);
220
295
  written.push(p.receipt);
221
296
 
222
- print('');
223
- print('Written:');
224
- for (const w of written) print(` ${w}`);
225
- print('');
297
+ plain('');
298
+ plain('Written:');
299
+ for (const w of written) plain(` ${w}`);
300
+ plain('');
301
+ if (cards) {
302
+ const names = new Map([
303
+ [p.stage, 'Bundle'], [p.museInstalled, 'Muse plugin list'], [cachePath, 'Muse copy'], [p.museRules, 'Rules file'], [p.notice, 'First-run note'], [p.receipt, 'Receipt'], [p.config, 'Config'],
304
+ ]);
305
+ const nameOf = (path) => names.get(path) ?? (path.startsWith(p.backups) ? 'Backup' : 'Muse settings');
306
+ const waiting = states.filter((s) => s.status !== 'trusted_enabled');
307
+ cards.panel({
308
+ title: `LitMuse ${version} is installed`,
309
+ sections: [
310
+ { head: 'Installed', rows: [
311
+ { label: 'Muse plugin', value: `${existing ? 'updated' : `installed at ${scope} scope`}; skills and commands are active now` },
312
+ ...written.filter((path) => path !== p.museRules).map((path) => ({ label: nameOf(path), value: path })),
313
+ ...(rules ? [rules] : []),
314
+ left === 0 ? { label: 'Approvals', value: 'every hook and agent is approved' } : { mark: 'warn', label: 'Approvals', value: `${counted(waiting)} still to approve; the commands are below` },
315
+ ] },
316
+ { head: 'Next', rows: planRows([
317
+ ...(left ? [['Approve', 'run the commands below']] : []),
318
+ ['Start', 'open Muse in a project and begin a prompt with lit'], ['Check', 'npx @litfamily/litmuse doctor'],
319
+ ]) },
320
+ ],
321
+ });
322
+ if (left) cards.text('Approval needed. Run these when you are ready (or rerun install with --approve):', waiting.map((s) => ` muse plugins approve ${s.id}`));
323
+ }
226
324
  // The notice and the fixed line after it are printed once per text; the live count of folders to check always is.
227
325
  const [fixedLine, ...liveLines] = extensionLines(env);
228
326
  const noticeLines = [...extensionsNotice({ leftovers }), fixedLine];
229
327
  const hash = noticeHash(noticeLines.join('\n'));
230
328
  if (wasShown(p.shown, hash)) {
231
- for (const line of liveLines) print(line);
329
+ if (cards && liveLines.length) cards.text('LitFamily extensions', liveLines);
330
+ else for (const line of liveLines) print(line);
232
331
  } else {
233
- for (const line of [...noticeLines, ...liveLines]) print(line);
332
+ if (cards) cards.text(noticeLines[0], [...noticeLines.slice(1), ...liveLines]);
333
+ else for (const line of [...noticeLines, ...liveLines]) print(line);
234
334
  recordShown(p.shown, hash);
235
335
  }
236
- print('');
237
- print(left === 0
238
- ? 'Status: Ready. Start Muse in a project and begin a prompt with `lit`. Check any time with `npx @litfamily/litmuse doctor`.'
239
- : `Status: installed, approval needed for ${left} capabilities. Run the commands above, then \`npx @litfamily/litmuse doctor\`.`);
336
+ if (!cards) {
337
+ print('');
338
+ print(left === 0
339
+ ? 'Status: Ready. Start Muse in a project and begin a prompt with `lit`. Check any time with `npx @litfamily/litmuse doctor`.'
340
+ : `Status: installed, approval needed for ${left} capabilities. Run the commands above, then \`npx @litfamily/litmuse doctor\`.`);
341
+ }
240
342
  return 0;
241
343
  }
package/lib/mark.mjs CHANGED
@@ -100,8 +100,7 @@ const tagline = (width, depth) => {
100
100
 
101
101
  // The mark as printable rows for `cols` cells at `depth`: the art, then one centred tagline.
102
102
  // Below 24 columns it is the single plain line.
103
- export function markRows({ cols = 80, depth = 'none' } = {}) {
104
- const size = markSize(cols);
103
+ export function markRows({ cols = 80, depth = 'none', size = markSize(cols) } = {}) {
105
104
  if (!size) return [FALLBACK];
106
105
  const art = depth === 'none' ? [...MONO_ROWS[size]] : artRows(size, depth);
107
106
  return [...art, tagline(PIXEL_ROWS[size][0].length, depth)];
@@ -257,7 +257,7 @@ const paint = (code, text, color) => (color ? `\u001b[${code}m${text}\u001b[0m`
257
257
 
258
258
  // Waiting on the user: a paused thread, or a lane that reported failure. A turn where the
259
259
  // model asked a question but left no tool state is not visible to the card.
260
- const waitingOf = (card) => (card.threads?.rows ?? []).some((row) => row.status === 'paused')
260
+ export const waitingOf = (card) => (card.threads?.rows ?? []).some((row) => row.status === 'paused')
261
261
  || (card.lanes ?? []).some((lane) => lane.status === 'failed');
262
262
 
263
263
  // With a pill (truecolor TTY only) the pill stands in for the leading `LIT · `.
@@ -272,7 +272,7 @@ const headlineFor = (card, color, pill = null) => {
272
272
 
273
273
  // Canonical review-lane display names, in REVIEW_LANES order; the strip reads the same
274
274
  // list, so the two cannot drift apart.
275
- const REVIEW_LANE_LABELS = Object.freeze({ goal: 'scope', quality: 'package', security: 'security', qa: 'tests+evidence', context: 'surface' });
275
+ export const REVIEW_LANE_LABELS = Object.freeze({ goal: 'scope', quality: 'package', security: 'security', qa: 'tests+evidence', context: 'surface' });
276
276
  const VERDICT_DOT = Object.freeze({ pass: ['32;1', '●'], fail: ['31;1', '●'], running: ['33;1', '◐'], pending: ['33', '○'] });
277
277
 
278
278
  const laneSegment = (id, verdict, color) => {
@@ -292,7 +292,7 @@ const lanesStrip = (card, color) => {
292
292
  // prints one celebratory line until the freshness window passes, then the card settles on
293
293
  // its own. A published release has no signal the card can see.
294
294
  const BURST_FRESH_MS = 15 * 60 * 1000;
295
- const burstOf = (card, now) => {
295
+ export const burstOf = (card, now) => {
296
296
  const plan = card.plan;
297
297
  if (plan && plan.total > 0 && plan.done >= plan.total && Number.isFinite(plan.mtimeMs) && now - plan.mtimeMs <= BURST_FRESH_MS) {
298
298
  return `✨ done: ${plan.file} · ${plan.done}/${plan.total} rows ticked ✨`;
@@ -304,6 +304,16 @@ const burstOf = (card, now) => {
304
304
  return null;
305
305
  };
306
306
 
307
+ // Work is going on: a route is active, its session has not stopped since the record last moved, and something moved
308
+ // in the last quarter hour. Only then does the watched card move.
309
+ export function cardWorking(card, { env = process.env, now = card.now ?? Date.now() } = {}) {
310
+ if (!card.active) return false;
311
+ const live = readLiveness(env).find((rec) => rec.session === card.session);
312
+ const liveAt = live ? Date.parse(live.at) : 0;
313
+ if (live && live.state !== 'alive' && liveAt >= (card.updated ?? 0)) return false;
314
+ return now - Math.max(card.updated ?? 0, liveAt || 0) <= SIBLING_FRESH_MS;
315
+ }
316
+
307
317
  // badge: { text, width } from lib/mark.mjs litPill, or null. It is dropped when the headline
308
318
  // would no longer fit `cols`, so the plain headline stays the fallback at every width.
309
319
  export function renderCard(card, { badge = null, cols = Infinity } = {}) {
package/lib/sunset.mjs ADDED
@@ -0,0 +1,186 @@
1
+ // The status card's sunset, for a person's truecolor terminal only: a half-sunk sun with stars over it and a sea under
2
+ // it, painted only in cells that hold no text.
3
+ // `t` is seconds into the motion; null is the resting pose. Shapes hold still: only colours move, plus the ASCII sea,
4
+ // stars and shooting star.
5
+ import { displayWidth } from '../plugin/lib/rewind/gauge.mjs';
6
+ import { sample } from './mark.mjs';
7
+
8
+ const ESC = '\u001b';
9
+ export const MIN_COLS = 64;
10
+ export const MAX_WIDTH = 120;
11
+ export const SUN_W = 18;
12
+ export const SUN_ROWS = 3;
13
+ // The moment a single print of a working card shows. No shooting star is in flight then.
14
+ export const STILL_T = 4;
15
+ const NEON = Object.freeze(['#ff2d95', '#b48cff', '#8be9fd']);
16
+ export const FAINT = '#30363d';
17
+ const SLIT = '#1a1030';
18
+
19
+ const LOOKS = {
20
+ sunset: { sun: [['#ffd24a', '#fff0a0'], ['#ff8f3c', '#ffc15a'], ['#ff2d8a', '#ff6b8f']], sea: ['#ffdc73', '#ff9a4a', '#ff4f8b', '#b457d6', '#5a46a8'] },
21
+ turn: { sun: [['#ffc95a', '#fff0b8'], ['#ffaf3c', '#ffd98a'], ['#e08a1e', '#ffb95a']], sea: ['#ffd98a', '#ffaf3c', '#e08a1e', '#9a6420', '#5a4020'] },
22
+ };
23
+ const RAINBOW = ['#ff6b6b', '#ffaf5f', '#ffff87', '#87ff9f', '#87d7ff', '#af87ff', '#ff87d7', '#ff6b6b'];
24
+
25
+ // Who sees the scene: truecolor, not a background the terminal says is light, and wide enough.
26
+ export function sceneOn({ depth, env = process.env, cols }) {
27
+ const light = /;(7|15)$/.test(env.COLORFGBG ?? '');
28
+ return depth === 'truecolor' && !light && cols >= MIN_COLS;
29
+ }
30
+
31
+ export const motionOff = (env = process.env) => /^(off|reduced|0)$/i.test(env.LITMUSE_MOTION ?? '');
32
+
33
+ const SGR = /\u001b\[[0-9;]*m/gu;
34
+ const charCells = (ch) => Math.max(displayWidth(ch), /\p{Emoji_Presentation}/u.test(ch) ? 2 : 0);
35
+
36
+ // A row cut into rows of at most `width` cells; the colour in force carries on. Control characters are dropped.
37
+ export function wrapRow(row, width) {
38
+ const out = [];
39
+ let text = '';
40
+ let used = 0;
41
+ let sgr = '';
42
+ for (const [token] of row.matchAll(/\u001b\[[0-9;]*m|[^]/gu)) {
43
+ if (token.startsWith(`${ESC}[`)) {
44
+ sgr = token === `${ESC}[0m` ? '' : sgr + token;
45
+ text += token;
46
+ continue;
47
+ }
48
+ if (/\p{Cc}/u.test(token)) continue;
49
+ const cells = charCells(token);
50
+ if (used + cells > width) {
51
+ out.push(sgr ? `${text}${ESC}[0m` : text);
52
+ text = sgr;
53
+ used = 0;
54
+ }
55
+ text += token;
56
+ used += cells;
57
+ }
58
+ return [...out, text];
59
+ }
60
+
61
+ // Colours mix in eight kept steps, so a frame mixes nothing twice and neighbours merge.
62
+ const kept = new Map();
63
+ export function mix(a, b, k) {
64
+ const step = Math.max(0, Math.min(8, Math.round(k * 8)));
65
+ const key = a + b + step;
66
+ if (kept.size > 4000) kept.clear();
67
+ if (!kept.has(key)) kept.set(key, sample([a, b], step / 8));
68
+ return kept.get(key);
69
+ }
70
+
71
+ const channel = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)).join(';');
72
+ const codes = new Map();
73
+ const codeOf = ({ fg, bg, bold }) => {
74
+ const key = `${fg ?? ''}|${bg ?? ''}${bold ? 'b' : ''}`;
75
+ if (codes.size > 4000) codes.clear();
76
+ if (!codes.has(key)) codes.set(key, [bold && '1', fg && `38;2;${channel(fg)}`, bg && `48;2;${channel(bg)}`].filter(Boolean).join(';'));
77
+ return codes.get(key);
78
+ };
79
+
80
+ // Cells `{ ch, fg?, bg?, bold? }` as one string; a colour is written only where it changes.
81
+ export function ink(cells) {
82
+ let out = '';
83
+ let last = '';
84
+ for (const cell of cells) {
85
+ const code = cell ? codeOf(cell) : '';
86
+ if (code !== last) out += `${ESC}[0${code ? `;${code}` : ''}m`;
87
+ last = code;
88
+ out += cell ? cell.ch : ' ';
89
+ }
90
+ return last ? `${out}${ESC}[0m` : out;
91
+ }
92
+
93
+ // The neon a place on the card takes, pink to violet to cyan.
94
+ export const neon = (k) => (k < 0.5 ? mix(NEON[0], NEON[1], k * 2) : mix(NEON[1], NEON[2], k * 2 - 1));
95
+
96
+ // The dome in eighth blocks, with a thin dark slit over the second row and a thicker one over the third.
97
+ const DOME = [0, 1, 2].map((r) => Array.from({ length: SUN_W }, (_, x) => {
98
+ const d = (x - (SUN_W - 1) / 2) / (SUN_W / 2);
99
+ const fill = Math.max(0, Math.min(8, Math.round(Math.sqrt(1 - d * d) * 24) - (2 - r) * 8));
100
+ if (fill === 0) return null;
101
+ if (fill < 8) return { ch: '▁▂▃▄▅▆▇'[fill - 1] };
102
+ return r === 0 ? { ch: '█' } : { ch: r === 1 ? '▇' : '▆', bg: SLIT };
103
+ }));
104
+ // Stars as [row, cells from the sun's left edge].
105
+ const STARS = [[0, -30], [1, -24], [0, -18], [1, -13], [0, -9], [1, -5], [0, 22], [1, 25], [0, 29], [1, 32], [0, 35]];
106
+ const CLEAR = 3;
107
+
108
+ /**
109
+ * Where the scene goes over rows of cells, where an empty cell is null: the lowest three rows in a run that leave the
110
+ * sun room, as near its usual place as they allow. `top` is null when there is no room anywhere.
111
+ */
112
+ export function place(grid, width) {
113
+ const home = Math.round(width * 0.62);
114
+ const free = (r, from, to) => {
115
+ for (let x = from; x < to; x += 1) if (x < 0 || x >= width || grid[r][x]) return false;
116
+ return true;
117
+ };
118
+ const spots = Array.from({ length: Math.max(0, width - SUN_W - 1) }, (_, i) => i).filter((at) => Math.abs(at - home) <= 14).sort((a, b) => Math.abs(a - home) - Math.abs(b - home));
119
+ for (let top = grid.length - SUN_ROWS; top >= 0; top -= 1) {
120
+ const at = spots.find((x) => [0, 1, 2].every((i) => free(top + i, x - 2, x + SUN_W + 2)));
121
+ if (at !== undefined) return { grid, width, at, top, sea: top + 2 };
122
+ }
123
+ return { grid, width, at: home, top: null, sea: grid.length - 1 };
124
+ }
125
+
126
+ function seaCell(dx, s, stops) {
127
+ const far = Math.abs(dx);
128
+ const wave = Math.sin(far * 0.62 - s * 2.3) + 0.8 * Math.sin(dx * 0.31 + s * 1.1) + 0.6 * Math.sin(dx * 1.37 - s * 0.7);
129
+ const level = wave * 0.62 + 1.05 - far / 34;
130
+ if (level < 0.22) return null;
131
+ const hue = Math.min(3.99, far / 13);
132
+ const base = mix(stops[Math.floor(hue)], stops[Math.floor(hue) + 1], hue % 1);
133
+ return { ch: level > 1 ? '~' : level > 0.55 ? '-' : '.', fg: mix(FAINT, base, Math.min(1, 0.18 + level * 0.55)), bold: level > 1.5 };
134
+ }
135
+
136
+ /**
137
+ * The scene for one moment: a Map from row index to that row's cells, `width` long and holey, and holey wherever the
138
+ * grid holds text. `look` is sunset, turn (amber) or rainbow; `dim` is the resting card's quieter light.
139
+ */
140
+ export function paint(spot, { t = null, look = 'sunset', dim = false } = {}) {
141
+ const { grid, width, at, top, sea } = spot;
142
+ const out = new Map();
143
+ if (top === null && (t === null || sea < 0)) return out;
144
+ const s = t ?? 0;
145
+ const shade = (hex) => (dim ? mix(hex, FAINT, 0.6) : hex);
146
+ const turning = (k) => sample(RAINBOW, (((k + s / 4.8) % 1) + 1) % 1);
147
+ const stops = look === 'rainbow' ? [0, 0.15, 0.3, 0.45, 0.6].map(turning) : LOOKS[look].sea;
148
+ const row = (r) => {
149
+ if (!out.has(r)) out.set(r, new Array(width).fill(null));
150
+ return out.get(r);
151
+ };
152
+ const clear = (r, x) => {
153
+ if (x < 0 || x >= width) return false;
154
+ for (let d = -CLEAR + 1; d < CLEAR; d += 1) if (grid[r][x + d]) return false;
155
+ return true;
156
+ };
157
+ const mid = at + SUN_W / 2 - 0.5;
158
+ if (top !== null) {
159
+ for (const [r, dx] of STARS) {
160
+ const x = at + dx;
161
+ if (!clear(top + r, x)) continue;
162
+ const glow = 0.5 + 0.5 * Math.sin(s * 1.7 + dx * 2.1);
163
+ row(top + r)[x] = { ch: glow > 0.85 ? '*' : glow > 0.45 ? '+' : '.', fg: mix(FAINT, shade(dx % 2 ? '#a99bff' : '#ff9ad5'), 0.35 + 0.65 * glow) };
164
+ }
165
+ const dash = t === null ? 9 : s % 9;
166
+ if (dash < 1.1) {
167
+ const head = Math.round(at + SUN_W + 22 - (dash / 1.1) * 34);
168
+ ['*', '-', '-', '.'].forEach((ch, i) => {
169
+ if (clear(top, head + i)) row(top)[head + i] = { ch, fg: mix('#fff4e0', '#b457d6', i / 3), bold: i === 0 };
170
+ });
171
+ }
172
+ }
173
+ for (let x = 0; x < width; x += 1) {
174
+ const cell = clear(sea, x) ? seaCell(x - mid, s, stops) : null;
175
+ if (cell) row(sea)[x] = { ...cell, fg: shade(cell.fg) };
176
+ }
177
+ if (top !== null) {
178
+ DOME.forEach((line, r) => line.forEach((cell, x) => {
179
+ if (!cell) return;
180
+ const heat = t === null ? 0.25 : 0.5 + 0.5 * Math.sin(s * 2.1 + r * 1.5 + 0.55 * Math.sin(x * 0.8 + s * 1.6));
181
+ const fg = look === 'rainbow' ? mix(turning(x / SUN_W / 2 + r * 0.12), '#ffffff', 0.3 + 0.25 * heat) : mix(...LOOKS[look].sun[r], heat);
182
+ row(top + r)[at + x] = { ...cell, fg: shade(fg) };
183
+ }));
184
+ }
185
+ return out;
186
+ }