herdr-gentle-shell 1.7.0 → 1.8.1

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.
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // The Pi -> Herdr palette projection: the pure half of theme sync (S3/S4).
5
+ //
6
+ // Herdr keeps its theme in a fixed vocabulary of tokens, and this module is the
7
+ // only place that translates Pi's theme tokens into it. It is pure on purpose:
8
+ // the extension converts Pi's colour values to hex strings before calling in, so
9
+ // this file needs no host import, no filesystem and no network — the caller owns
10
+ // every side effect and the projection can be asserted byte for byte.
11
+ //
12
+ // Only the tokens a sidebar actually paints are projected. Herdr's surface
13
+ // tokens (sidebar_bg, panel_bg, active_row_bg, selection_bg, surface*) keep
14
+ // their base-theme values because Pi has no equivalent surface concept: a Pi
15
+ // theme names foregrounds and accents, not panel backgrounds, so inventing one
16
+ // here would put colours on screen that the user never chose. The one exception
17
+ // is the fixed Gentleman.Dots table below, which is not invented here: it is the
18
+ // palette the user's own Herdr profiles already use.
19
+ //
20
+ // Looked up by Pi theme NAME, exactly like the reference table: the Gentle themes
21
+ // are the only ones whose surface colours we know.
22
+ //
23
+ // Ported from gentle-herdr lib/herdr-theme-projection.ts
24
+ // (https://github.com/MarsSall/gentle-herdr, MIT License, Copyright (c) MarsSall).
25
+ const DOTS_CUTE = Object.freeze({
26
+ panel_bg: '#000000',
27
+ surface0: '#241822',
28
+ surface1: '#342230',
29
+ surface_dim: '#20161E',
30
+ overlay0: '#B99AA9',
31
+ });
32
+ // Sexy shares Cute's surfaces and only differs in the accent: Herdr draws
33
+ // unfocused session names with subtext0 and branches with overlay0 (mauve when
34
+ // focused), so Sexy gets fuchsia names, grayish pink branches and a wine row.
35
+ const DOTS_SEXY = Object.freeze({
36
+ ...DOTS_CUTE,
37
+ subtext0: '#FF4F9A',
38
+ mauve: '#B99AA9',
39
+ active_row_bg: '#2E0F1F',
40
+ selection_bg: '#2E0F1F',
41
+ });
42
+ const DOTS_FIXED = Object.freeze({
43
+ 'Gentleman-Cute': DOTS_CUTE,
44
+ 'Gentleman-Sexy': DOTS_SEXY,
45
+ Gentle: Object.freeze({ panel_bg: '#06080f' }),
46
+ });
47
+
48
+ const HERDR_BASE_THEME = 'one-dark';
49
+
50
+ // The Herdr themes a stored selection may name, exactly the set Herdr ships.
51
+ const HERDR_BASE_THEMES = Object.freeze([
52
+ 'catppuccin',
53
+ 'terminal',
54
+ 'tokyo-night',
55
+ 'dracula',
56
+ 'nord',
57
+ 'gruvbox',
58
+ 'one-dark',
59
+ 'solarized',
60
+ 'kanagawa',
61
+ 'rose-pine',
62
+ 'vesper',
63
+ ]);
64
+
65
+ // Herdr's own token order. A projected `[theme.custom]` table is written in this
66
+ // order so the managed block stays diff-stable, which is why a token may appear
67
+ // here without a Pi source: `peach` and the surface tokens are part of the
68
+ // vocabulary, not part of this projection.
69
+ const HERDR_TOKEN_ORDER = Object.freeze([
70
+ 'sidebar_bg',
71
+ 'panel_bg',
72
+ 'active_row_bg',
73
+ 'selection_bg',
74
+ 'accent',
75
+ 'text',
76
+ 'red',
77
+ 'green',
78
+ 'subtext0',
79
+ 'overlay0',
80
+ 'overlay1',
81
+ 'mauve',
82
+ 'yellow',
83
+ 'peach',
84
+ 'blue',
85
+ 'teal',
86
+ 'surface0',
87
+ 'surface1',
88
+ 'surface_dim',
89
+ ]);
90
+
91
+ // The only Pi theme tokens this projection reads, and exactly the reference's
92
+ // eight: working/done status and notification colours (yellow, teal, blue,
93
+ // peach) stay with Herdr's native base theme, because mapping them here
94
+ // recoloured statuses the user never asked to repaint. `subtext0` and `overlay0`
95
+ // share Pi's `muted`: a single Pi role paints two Herdr surfaces, and the
96
+ // emitted pair follows the source, so they are never half-applied.
97
+ const HERDR_ROLE_SOURCES = Object.freeze({
98
+ accent: 'accent',
99
+ text: 'text',
100
+ red: 'error',
101
+ green: 'success',
102
+ subtext0: 'muted',
103
+ overlay0: 'muted',
104
+ overlay1: 'thinkingText',
105
+ mauve: 'borderAccent',
106
+ });
107
+
108
+ const HEX_PATTERN = /^#[0-9a-fA-F]{6}$/;
109
+
110
+ const THEME_OFF_LABEL = 'Off';
111
+
112
+ function isConcreteHex(value) {
113
+ return typeof value === 'string' && HEX_PATTERN.test(value);
114
+ }
115
+
116
+ // A stored theme value is either an assigned name or nothing at all. Trimming is
117
+ // the only normalisation; a blank, non-string or otherwise odd value is `null`
118
+ // (unassigned) rather than a guess at what the user meant.
119
+ function normalizeThemeName(value) {
120
+ if (typeof value !== 'string') return null;
121
+ const trimmed = value.trim();
122
+ return trimmed === '' ? null : trimmed;
123
+ }
124
+
125
+ // The panel label for a stored value: an unusable value reads as the inert
126
+ // choice instead of surfacing the raw garbage in the UI.
127
+ function themeChoiceLabel(name) {
128
+ return normalizeThemeName(name) ?? THEME_OFF_LABEL;
129
+ }
130
+
131
+ function requireColors(input) {
132
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
133
+ throw new TypeError('projectPalette expects an object with a `colors` record');
134
+ }
135
+ const { colors } = input;
136
+ if (typeof colors !== 'object' || colors === null || Array.isArray(colors)) {
137
+ throw new TypeError('projectPalette expects `colors` to be a record of Pi theme tokens to hex strings');
138
+ }
139
+ return colors;
140
+ }
141
+
142
+ // The Herdr custom table for a Pi palette, in Herdr token order. A token whose
143
+ // source is not a concrete hex is omitted rather than defaulted: an empty string
144
+ // means "terminal default" in Pi, which has no hex spelling, and a guessed one
145
+ // would repaint the sidebar in a colour nobody picked. A DOTS_FIXED value for the
146
+ // same token wins over the mapped one: those surfaces are known from the user's
147
+ // Herdr profiles, while the mapped colour is an approximation of them.
148
+ function customTokens(name, colors) {
149
+ const themeName = normalizeThemeName(name);
150
+ const fixed = Object.hasOwn(DOTS_FIXED, themeName ?? '') ? DOTS_FIXED[themeName] : {};
151
+ const custom = {};
152
+ for (const token of HERDR_TOKEN_ORDER) {
153
+ if (Object.hasOwn(fixed, token)) {
154
+ custom[token] = fixed[token].toLowerCase();
155
+ continue;
156
+ }
157
+ const source = HERDR_ROLE_SOURCES[token];
158
+ if (source === undefined) continue;
159
+ const hex = colors[source];
160
+ if (!isConcreteHex(hex)) continue;
161
+ custom[token] = hex.toLowerCase();
162
+ }
163
+ return custom;
164
+ }
165
+
166
+ function projectPalette(input) {
167
+ const colors = requireColors(input);
168
+ const custom = customTokens(input.name, colors);
169
+ const theme = { name: HERDR_BASE_THEME };
170
+ // An empty custom table is omitted, not written empty: Herdr would still treat
171
+ // the block as an override, and S7 wants an untouched palette to stay one.
172
+ if (Object.keys(custom).length > 0) theme.custom = custom;
173
+ return { theme };
174
+ }
175
+
176
+ // A stable identity for "this palette", used to notice an in-place theme change
177
+ // (same name, different colours) without diffing documents. Roles are sorted so
178
+ // the fingerprint never depends on the order the caller built its record in.
179
+ function paletteFingerprint(input) {
180
+ const colors = requireColors(input);
181
+ const name = normalizeThemeName(input.name);
182
+ const pairs = Object.entries(customTokens(name, colors)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
183
+ return JSON.stringify([name, pairs]);
184
+ }
185
+
186
+ module.exports = {
187
+ HERDR_BASE_THEME,
188
+ HERDR_BASE_THEMES,
189
+ HERDR_TOKEN_ORDER,
190
+ HERDR_ROLE_SOURCES,
191
+ DOTS_FIXED,
192
+ THEME_OFF_LABEL,
193
+ isConcreteHex,
194
+ projectPalette,
195
+ paletteFingerprint,
196
+ themeChoiceLabel,
197
+ normalizeThemeName,
198
+ };
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // The persisted theme switch: whether Herdr follows Pi's active theme (S1/S2)
5
+ // and, with the sync off, the one theme the user assigned (S4).
6
+ //
7
+ // This file is the only persisted truth the customize panel reads and writes, so
8
+ // it is deliberately one small JSON document with inert defaults: a fresh
9
+ // install writes NOTHING, and a document this module cannot read is a refusal
10
+ // rather than a guess, because guessing here would silently repaint Herdr with a
11
+ // palette the user never chose (S7).
12
+ //
13
+ // One document, one directory: `themeStateDir` must resolve the SAME plugin state
14
+ // dir the Moshi flag already uses, or the panel toggles two places and the switch
15
+ // reads as missing — and a missing switch means "off", so a stored `sync: true`
16
+ // would go unnoticed.
17
+
18
+ const fs = require('node:fs');
19
+ const os = require('node:os');
20
+ const path = require('node:path');
21
+ const { randomUUID } = require('node:crypto');
22
+
23
+ const { normalizeThemeName } = require('./theme-projection.js');
24
+
25
+ const THEME_FILE_NAME = 'gentle-theme.json';
26
+ const STORED_SEGMENT = 'herdr-gentle-agents';
27
+ const ACTIVE_PLUGIN_ID = 'herdr-gentle-shell';
28
+ const OWNED_DIR_NAMES = [ACTIVE_PLUGIN_ID, STORED_SEGMENT];
29
+
30
+ // The same known-file family every state-dir consumer declares, kept byte-equal
31
+ // on purpose: a consumer that does not recognise a file another one writes picks
32
+ // a different directory on the next launch and splits the state (see
33
+ // tools/state-dir-known-files.test.js). `gentle-theme.json` is deliberately NOT
34
+ // in it — this module must resolve the directory exactly like the Moshi flag
35
+ // does, and adding a file here would make the resolution diverge from the very
36
+ // function it reproduces.
37
+ const KNOWN_FILES = [
38
+ 'gentle-sidebar-mode.json',
39
+ 'gentle-moshi.json',
40
+ 'pi-extension-exclusion-owned',
41
+ 'gentle-status.pid',
42
+ 'gentle-interruptions.json',
43
+ 'installer-state',
44
+ 'gentle-worktree-mode.json',
45
+ 'gentle-plugin-tools.json',
46
+ ];
47
+
48
+ // Reproduces `sidebarEffectiveDir()` in extensions/gentle-herdr-state.ts:1806
49
+ // (with `sidebarStoredDir()` at :1747 and `sidebarActiveDir()`/`sidebarCanonicalDir()`
50
+ // above it). Duplicating it is deliberate: the extension is TypeScript and cannot
51
+ // require this module, and both sides of the feature must agree on one file, so
52
+ // the decision order is copied verbatim — explicit `GENTLE_STATUS_STATE_DIR`
53
+ // override, then the stored canonical dir, then the active-id dir when only it
54
+ // holds a file of ours, then the stored dir as the final fallback. Change that
55
+ // function and this one in the same commit.
56
+ //
57
+ // It takes `env` instead of reading process.env only so the resolution is
58
+ // assertable; every value and every ordering rule is the extension's.
59
+ function themeStateDir(env = process.env) {
60
+ const explicit = env.GENTLE_STATUS_STATE_DIR;
61
+ if (typeof explicit === 'string' && explicit.length > 0) return explicit;
62
+ const stored = storedStateDir(env);
63
+ // An explicit-but-empty (or otherwise invalid non-nullish) value ignores every
64
+ // other candidate and uses the stored default; only an omitted explicit falls
65
+ // through to the active-id dir.
66
+ if (explicit !== undefined && explicit !== null) return stored;
67
+ const active = activeStateDir(env);
68
+ if (active === stored) return stored;
69
+ try {
70
+ if (dirHasKnownFiles(stored)) return stored;
71
+ if (dirHasKnownFiles(active)) return active;
72
+ } catch {
73
+ // Fall through to the stored canonical dir on unexpected failure.
74
+ }
75
+ return stored;
76
+ }
77
+
78
+ function themeStatePath(env = process.env) {
79
+ return path.join(themeStateDir(env), THEME_FILE_NAME);
80
+ }
81
+
82
+ function pluginsDir(env) {
83
+ const base = env.XDG_STATE_HOME
84
+ ? path.join(env.XDG_STATE_HOME, 'herdr')
85
+ : path.join(os.homedir(), '.local', 'state', 'herdr');
86
+ return path.join(base, 'plugins');
87
+ }
88
+
89
+ function storedStateDir(env) {
90
+ return path.join(pluginsDir(env), STORED_SEGMENT);
91
+ }
92
+
93
+ // Two spellings name the same directory when their canonical forms match. A path
94
+ // that does not exist yet has no realpath, so the deepest existing ancestor is
95
+ // resolved and the missing tail re-appended, which keeps a symlinked or relative
96
+ // spelling from being rejected as a different directory.
97
+ function canonicalDir(dir) {
98
+ const absolute = path.resolve(dir);
99
+ const tail = [];
100
+ let current = absolute;
101
+ for (;;) {
102
+ try {
103
+ const real = fs.realpathSync(current);
104
+ return tail.length ? path.join(real, ...tail) : real;
105
+ } catch {
106
+ const parent = path.dirname(current);
107
+ if (parent === current) return absolute;
108
+ tail.unshift(path.basename(current));
109
+ current = parent;
110
+ }
111
+ }
112
+ }
113
+
114
+ // The active plugin id dir: the Herdr-injected one only when it IS the directory
115
+ // this package derives for that name under the resolved state home. Any other
116
+ // basename — or an owned basename under another root — is ignored, because
117
+ // honouring it selects a directory the rest of the package never writes.
118
+ function activeStateDir(env) {
119
+ const base = pluginsDir(env);
120
+ const injected = env.HERDR_PLUGIN_STATE_DIR;
121
+ if (typeof injected === 'string' && injected.length > 0) {
122
+ const name = path.basename(injected);
123
+ if (OWNED_DIR_NAMES.includes(name) && canonicalDir(injected) === canonicalDir(path.join(base, name))) {
124
+ return injected;
125
+ }
126
+ }
127
+ return path.join(base, ACTIVE_PLUGIN_ID);
128
+ }
129
+
130
+ function dirHasKnownFiles(dir) {
131
+ for (const name of KNOWN_FILES) {
132
+ try {
133
+ if (fs.existsSync(path.join(dir, name))) return true;
134
+ } catch {
135
+ // A single unreadable entry never decides; keep scanning.
136
+ }
137
+ }
138
+ return false;
139
+ }
140
+
141
+ // Pi strips a single leading BOM before parsing; do the same.
142
+ function stripBom(text) {
143
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
144
+ }
145
+
146
+ // A missing file is an inert document (S7: a fresh install writes nothing, so
147
+ // nothing is what it reads). A file that cannot be read or parsed is a refusal:
148
+ // the caller records "not read" with the inert defaults instead of trusting a
149
+ // partially understood switch.
150
+ function readThemeState(env = process.env) {
151
+ const file = themeStatePath(env);
152
+ const inert = { ok: false, sync: false, theme: null, updatedAt: null };
153
+ let raw;
154
+ try {
155
+ raw = fs.readFileSync(file, 'utf8');
156
+ } catch (err) {
157
+ if (err && err.code === 'ENOENT') return { ok: true, sync: false, theme: null, updatedAt: null };
158
+ return { ...inert, error: `cannot read ${file}: ${err.message}` };
159
+ }
160
+ let doc;
161
+ try {
162
+ doc = JSON.parse(stripBom(raw));
163
+ } catch (err) {
164
+ return { ...inert, error: `cannot parse ${file}: ${err.message}` };
165
+ }
166
+ if (typeof doc !== 'object' || doc === null || Array.isArray(doc)) {
167
+ return { ...inert, error: `cannot parse ${file}: top-level JSON must be an object` };
168
+ }
169
+ // The switch is on only when the document literally says so; an unusable theme
170
+ // is unassigned, never the nearest name.
171
+ return {
172
+ ok: true,
173
+ sync: doc.sync === true,
174
+ theme: normalizeThemeName(doc.theme),
175
+ updatedAt: typeof doc.updatedAt === 'string' ? doc.updatedAt : null,
176
+ };
177
+ }
178
+
179
+ // Atomic and mode-preserving, so a crash mid-write cannot leave a half document
180
+ // for the panel to read (same pattern as `writeSettingsDoc` in
181
+ // extensions/gentle-herdr-state.ts:2417). The temp file is created next to the
182
+ // resolved target, which also keeps a symlinked target's link intact.
183
+ function writeThemeState(env, input) {
184
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
185
+ throw new TypeError('writeThemeState expects an object with `sync` and `theme`');
186
+ }
187
+ if (typeof input.sync !== 'boolean') {
188
+ throw new TypeError('writeThemeState expects `sync` to be a boolean');
189
+ }
190
+ if (input.theme !== null && input.theme !== undefined && typeof input.theme !== 'string') {
191
+ throw new TypeError('writeThemeState expects `theme` to be a string or null');
192
+ }
193
+ const doc = {
194
+ sync: input.sync,
195
+ theme: normalizeThemeName(input.theme),
196
+ // Stamped here: the document always records when the switch was last
197
+ // changed, and a caller can never write a timestamp it made up.
198
+ updatedAt: new Date().toISOString(),
199
+ };
200
+ const file = themeStatePath(env);
201
+ const dir = path.dirname(file);
202
+ fs.mkdirSync(dir, { recursive: true });
203
+ let target = file;
204
+ try {
205
+ target = fs.realpathSync(file);
206
+ } catch {
207
+ // Missing or dangling: write where the path points.
208
+ }
209
+ let mode = 0o600;
210
+ try {
211
+ mode = fs.statSync(target).mode & 0o777;
212
+ } catch {
213
+ // Fresh file.
214
+ }
215
+ const temp = path.join(path.dirname(target), `.${THEME_FILE_NAME}.gentle-${randomUUID().slice(0, 8)}.tmp`);
216
+ try {
217
+ fs.writeFileSync(temp, `${JSON.stringify(doc, null, 2)}\n`, { mode });
218
+ fs.renameSync(temp, target);
219
+ } catch (error) {
220
+ try {
221
+ fs.rmSync(temp, { force: true });
222
+ } catch {
223
+ /* best effort: a failure here is non-fatal */
224
+ }
225
+ throw error;
226
+ }
227
+ return { path: file };
228
+ }
229
+
230
+ module.exports = { themeStateDir, themeStatePath, readThemeState, writeThemeState };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-gentle-shell",
3
- "version": "1.7.0",
3
+ "version": "1.8.1",
4
4
  "description": "Pi package for Herdr sidebar states: the Pi extension sidecar that publishes session facts as Herdr pane-metadata tokens, the optional Moshi notification channel, and the Pi-side helpers the Herdr Gentle Shell plugin drives.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -35,7 +35,8 @@
35
35
  "pi": {
36
36
  "extensions": [
37
37
  "./extensions/gentle-herdr-state.ts",
38
- "./extensions/herdr-session-open.ts"
38
+ "./extensions/herdr-session-open.ts",
39
+ "./extensions/herdr-theme-sync.ts"
39
40
  ]
40
41
  }
41
42
  }