pal-code 0.0.20 → 0.0.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.
@@ -0,0 +1,187 @@
1
+ /**
2
+ * github-light — VS Code "GitHub Light Default" aesthetic (Primer palette).
3
+ *
4
+ * The mirror of `github-dark`: every colour is pinned truecolor and the canvas
5
+ * is a light background, so this theme reads correctly only on a light
6
+ * terminal. `auto` mode selects it when the terminal reports a light default
7
+ * background — see `resolveTheme()` in `./index.ts`.
8
+ */
9
+
10
+ import type {EditorTheme, MarkdownTheme} from '../tui/theme-types.js';
11
+ import {highlightCode} from '../tui/render/highlight.js';
12
+ import type {CColors, CodeboxTokens, SurfaceTokens, SyntaxTokens, Theme} from './types.js';
13
+
14
+ const c: CColors = {
15
+ reset: '\x1b[0m',
16
+ bold: '\x1b[1m',
17
+ dim: '\x1b[2m',
18
+ italic: '\x1b[3m',
19
+ underline: '\x1b[4m',
20
+ // GitHub Light Truecolor Mapping (Primer Palette)
21
+ blue: '\x1b[38;2;9;105;218m', // #0969da — GitHub links / accent blue
22
+ green: '\x1b[38;2;26;127;55m', // #1a7f37 — GitHub success / green
23
+ cyan: '\x1b[38;2;27;124;131m', // #1b7c83 — GitHub teal
24
+ yellow: '\x1b[38;2;154;103;0m', // #9a6700 — GitHub yellow / warning
25
+ red: '\x1b[38;2;207;34;46m', // #cf222e — GitHub red / error
26
+ magenta: '\x1b[38;2;130;80;223m', // #8250df — GitHub purple
27
+ bright_red: '\x1b[38;2;207;34;46m', // #cf222e — light has no brighter red
28
+ bright_green: '\x1b[38;2;26;127;55m', // #1a7f37 — already the darkest green
29
+ bright_yellow: '\x1b[38;2;154;103;0m', // #9a6700 — already the darkest yellow
30
+ bright_cyan: '\x1b[38;2;27;124;131m', // #1b7c83
31
+ bright_black: '\x1b[38;2;110;119;129m', // #6e7781 — GitHub muted gray
32
+ bright_white: '\x1b[38;2;31;35;40m', // #1f2328 — GitHub primary text
33
+ };
34
+
35
+ const codebox: CodeboxTokens = {
36
+ surfaceBg: '\x1b[48;2;246;248;250m', // #f6f8fa — GitHub canvas subtle
37
+ borderFg: '\x1b[38;2;208;215;222m', // #d0d7de — GitHub border default
38
+ langFg: '\x1b[38;2;110;119;129m', // #6e7781 — muted text / language tag
39
+ chipBgIdle: '\x1b[48;2;234;238;242m', // #eaeef2 — button background (idle)
40
+ chipBgHover: '\x1b[48;2;208;215;222m', // #d0d7de — button background (hover)
41
+ chipFgIdle: '\x1b[38;2;31;35;40m', // #1f2328 — primary text
42
+ chipFgHover: '\x1b[38;2;9;105;218m', // #0969da — accent on hover
43
+ successFg: '\x1b[38;2;26;127;55m', // #1a7f37 — success green
44
+ gutterFg: '\x1b[38;2;140;149;159m', // #8c959f — dimmer than border #d0d7de
45
+ diffDelBg: '\x1b[48;2;255;235;233m', // #ffebe9 — GitHub red wash
46
+ diffAddBg: '\x1b[48;2;218;251;225m', // #dafbe1 — GitHub green wash
47
+ };
48
+
49
+ const markdownTheme: MarkdownTheme = {
50
+ heading: (text: string) => `${c.bold}${c.blue}${text}${c.reset}`,
51
+ link: (text: string) => `${c.underline}${c.blue}${text}${c.reset}`,
52
+ linkUrl: (text: string) => `${c.bright_black}${text}${c.reset}`,
53
+ code: (text: string) => `${c.red}${text}${c.reset}`, // GitHub inline code
54
+ codeBlock: (text: string) => `${c.bright_white}${text}${c.reset}`,
55
+ codeBlockBorder: (text: string) => `\x1b[38;2;208;215;222m${text}${c.reset}`, // #d0d7de
56
+ quote: (text: string) => `${c.italic}${c.bright_black}${text}${c.reset}`,
57
+ quoteBorder: (text: string) => `${c.bold}${c.blue}${text}${c.reset}`,
58
+ hr: (text: string) => `${c.bright_black}${text}${c.reset}`,
59
+ listBullet: (text: string) => `${c.bold}${c.green}${text}${c.reset}`,
60
+ bold: (text: string) => `${c.bold}${c.bright_white}${text}${c.reset}`,
61
+ italic: (text: string) => `${c.italic}${c.bright_white}${text}${c.reset}`,
62
+ strikethrough: (text: string) => `${c.bright_black}${text}${c.reset}`,
63
+ underline: (text: string) => `${c.underline}${text}${c.reset}`,
64
+ highlightCode,
65
+ };
66
+
67
+ const editorTheme: EditorTheme = {
68
+ borderColor: (s) => `${surface.input.border}${s}${c.reset}`, // #d0d7de GitHub border
69
+ selectList: {
70
+ selectedPrefix: (s) => `${c.bold}${c.blue}${s}${c.reset}`,
71
+ selectedText: (s) => `${c.bold}${c.bright_white}${s}${c.reset}`,
72
+ description: (s) => `${c.bright_black}${s}${c.reset}`,
73
+ scrollInfo: (s) => `${c.bright_black}${s}${c.reset}`,
74
+ noMatch: (s) => `${c.bright_black}${s}${c.reset}`,
75
+ },
76
+ };
77
+
78
+ /** GitHub-aligned agent role colors. */
79
+ const agentColors: Record<string, string> = {
80
+ pal: c.cyan,
81
+ plan: c.red,
82
+ planner: c.red,
83
+ explore: c.green,
84
+ build: c.blue,
85
+ review: c.magenta,
86
+ librarian: c.yellow,
87
+ architect: c.cyan,
88
+ };
89
+
90
+ /** Fallback display labels for roles that don't declare one. */
91
+ const agentLabels: Record<string, string> = {
92
+ pal: 'pal',
93
+ plan: 'plan',
94
+ planner: 'planner',
95
+ explore: 'explore',
96
+ build: 'builder',
97
+ review: 'reviewer',
98
+ librarian: 'librarian',
99
+ architect: 'architect',
100
+ };
101
+
102
+ /** VS Code GitHub Light Default syntax colours (truecolor SGR). */
103
+ const syntax: SyntaxTokens = {
104
+ comment: '\x1b[38;2;110;119;129m', // #6e7781
105
+ string: '\x1b[38;2;10;48;105m', // #0a3069
106
+ number: '\x1b[38;2;5;80;174m', // #0550ae
107
+ keyword: '\x1b[38;2;207;34;46m', // #cf222e
108
+ method: '\x1b[38;2;130;80;223m', // #8250df
109
+ jsonKey: '\x1b[38;2;5;80;174m', // #0550ae
110
+ jsonPrimitive: '\x1b[38;2;10;48;105m', // #0a3069
111
+ plain: '\x1b[38;2;31;35;40m', // #1f2328
112
+ };
113
+
114
+ /** GitHub Light equivalents of each component's palette reads (hex in comments). */
115
+ const surface: SurfaceTokens = {
116
+ window: {
117
+ bg: '#ffffff', // editor.background — light canvas (OSC 11 sync)
118
+ fg: '#1f2328', // editor.foreground (OSC 10 sync)
119
+ border: '\x1b[38;2;208;215;222m', // #d0d7de — GitHub border (reserved)
120
+ },
121
+ input: {
122
+ border: '\x1b[38;2;208;215;222m', // #d0d7de — editor border (editorTheme)
123
+ fg: '\x1b[38;2;31;35;40m', // #1f2328 — primary text (reserved)
124
+ placeholder: '\x1b[38;2;110;119;129m', // #6e7781 — muted placeholder (reserved)
125
+ },
126
+ sidebar: {
127
+ bg: '\x1b[48;2;246;248;250m', // #f6f8fa — subtle panel
128
+ border: '\x1b[38;2;208;215;222m', // #d0d7de — border (reserved)
129
+ title: `${c.bold}${c.blue}`, // sidebar.ts — bold #0969da
130
+ item: c.green, // #1a7f37 status dot
131
+ itemAccent: `${c.bold}${c.green}`, // bold #1a7f37 section headers
132
+ selected: c.blue, // #0969da (reserved — no selection state)
133
+ dim: c.dim, // SGR dim
134
+ },
135
+ statusLine: {
136
+ bg: '\x1b[48;2;246;248;250m', // #f6f8fa — panel fill (same tone as sidebar)
137
+ border: '\x1b[38;2;208;215;222m', // #d0d7de — right-edge segment accent
138
+ flash: c.green, // #1a7f37
139
+ error: c.red, // #cf222e (reserved — no error state today)
140
+ warn: c.yellow, // #9a6700
141
+ info: c.cyan, // #1b7c83
142
+ dim: c.dim, // SGR dim
143
+ },
144
+ overlay: {
145
+ border: '\x1b[38;2;208;215;222m', // #d0d7de (reserved)
146
+ selectedPrefix: c.blue, // #0969da — model/session picker prefix
147
+ selectedText: c.bold, // SGR bold — picker selection
148
+ description: c.dim, // SGR dim — picker description
149
+ scrollInfo: c.dim, // SGR dim
150
+ noMatch: c.dim, // SGR dim
151
+ },
152
+ permission: {
153
+ border: `${c.dim}${c.yellow}`, // dim + #9a6700
154
+ header: `${c.bold}${c.yellow}`, // bold + #9a6700
155
+ allow: c.green, // #1a7f37
156
+ always: c.cyan, // #1b7c83
157
+ deny: c.red, // #cf222e
158
+ dim: c.dim, // SGR dim
159
+ },
160
+ messageBox: {
161
+ border: c.dim, // SGR dim prefix
162
+ dim: c.dim, // SGR dim
163
+ roleFallback: c.cyan, // #1b7c83
164
+ },
165
+ runView: {
166
+ row: c.bright_black, // #6e7781
167
+ elapsed: c.bright_black, // #6e7781
168
+ preview: c.bright_black, // #6e7781
169
+ summary: c.bright_black, // #6e7781
170
+ border: c.bright_black, // #6e7781
171
+ },
172
+ };
173
+
174
+ export const githubLight: Theme = {
175
+ name: 'github-light',
176
+ displayName: 'GitHub Light',
177
+ variant: 'light',
178
+ c,
179
+ codebox,
180
+ syntax,
181
+ markdownTheme,
182
+ editorTheme,
183
+ agentColors,
184
+ agentLabels,
185
+ surface,
186
+ colorByNameFallback: c.blue, // github colorByName() default
187
+ };
@@ -4,33 +4,74 @@
4
4
 
5
5
  import type {Theme} from './types.js';
6
6
  import {githubDark} from './github-dark.js';
7
+ import {githubLight} from './github-light.js';
7
8
  import {vanillaPi} from './vanilla-pi.js';
8
9
 
9
- export type {CColors, CodeboxTokens, SurfaceTokens, SyntaxTokens, Theme} from './types.js';
10
+ export type {CColors, CodeboxTokens, SurfaceTokens, SyntaxTokens, Theme, ThemeVariant} from './types.js';
10
11
 
11
12
  /** Registered themes, keyed by the id used on the command line. */
12
13
  export const themes: Record<string, Theme> = {
13
14
  'vanilla-pi': vanillaPi,
14
15
  'github-dark': githubDark,
16
+ 'github-light': githubLight,
15
17
  };
16
18
 
17
19
  /** The default theme — used whenever no registered name resolves. */
18
20
  export const DEFAULT_THEME = 'vanilla-pi';
19
21
 
22
+ /**
23
+ * The pseudo-theme id that follows the terminal's own scheme.
24
+ *
25
+ * It is not an entry in `themes` — it resolves to a real theme at startup from
26
+ * the terminal's reported default background (OSC 11), so `/theme auto` is
27
+ * accepted by `resolveTheme` but never by `setTheme`.
28
+ */
29
+ export const AUTO_THEME = 'auto';
30
+
20
31
  /** Registered theme ids in registration order. */
21
32
  export function listThemes(): string[] {
22
33
  return Object.keys(themes);
23
34
  }
24
35
 
36
+ /** Every value `/theme` accepts: the real themes plus the `auto` mode. */
37
+ export function listThemeChoices(): string[] {
38
+ return [...listThemes(), AUTO_THEME];
39
+ }
40
+
41
+ /** The dark/light half of `auto` — what the terminal's background decides. */
42
+ export type DetectedScheme = 'dark' | 'light';
43
+
25
44
  /**
26
45
  * Pure theme-name resolution — no I/O.
27
46
  *
28
- * Priority: `env` (PAL_THEME) when it names a registered theme, then
29
- * `pal.theme` (the `theme` key of ~/.pal/config.json) when it is a registered
30
- * string, then DEFAULT_THEME. Unknown values fall through to the next source.
47
+ * Priority: `env` (PAL_THEME) when it names a registered theme or `auto`, then
48
+ * `pal.theme` (the `theme` key of ~/.pal/config.json) under the same rule,
49
+ * then DEFAULT_THEME. Unknown values fall through to the next source.
50
+ *
51
+ * `auto` maps to `github-light` when `detected` is `'light'`, and `github-dark`
52
+ * otherwise — including when detection is unavailable (`undefined`), because
53
+ * guessing dark is the safe half: a dark palette on a light terminal is ugly,
54
+ * a light palette on a dark terminal is unreadable.
31
55
  */
32
- export function resolveTheme(pal: {theme?: unknown}, env: string | undefined): string {
33
- if (typeof env === 'string' && Object.hasOwn(themes, env)) return env;
34
- if (typeof pal.theme === 'string' && Object.hasOwn(themes, pal.theme)) return pal.theme;
35
- return DEFAULT_THEME;
56
+ export function resolveTheme(
57
+ pal: {theme?: unknown},
58
+ env: string | undefined,
59
+ detected?: DetectedScheme,
60
+ ): string {
61
+ const named = (value: unknown): string | null =>
62
+ typeof value === 'string' && (Object.hasOwn(themes, value) || value === AUTO_THEME)
63
+ ? value
64
+ : null;
65
+ const choice = named(env) ?? named(pal.theme) ?? DEFAULT_THEME;
66
+ if (choice !== AUTO_THEME) return choice;
67
+ return detected === 'light' ? 'github-light' : 'github-dark';
68
+ }
69
+
70
+ /** Whether the resolved configuration asks to follow the terminal scheme. */
71
+ export function wantsAutoTheme(pal: {theme?: unknown}, env: string | undefined): boolean {
72
+ const named = (value: unknown): boolean =>
73
+ typeof value === 'string' && (Object.hasOwn(themes, value) || value === AUTO_THEME);
74
+ const envWins = named(env);
75
+ if (envWins) return env === AUTO_THEME;
76
+ return named(pal.theme) ? pal.theme === AUTO_THEME : false;
36
77
  }
@@ -194,12 +194,25 @@ export interface SurfaceTokens {
194
194
  };
195
195
  }
196
196
 
197
+ /**
198
+ * Which terminal background a theme is designed to sit on.
199
+ *
200
+ * - `'dark'` / `'light'` — the theme pins its own canvas (truecolor fills and
201
+ * syntax colours), so it only reads correctly on that scheme. These are the
202
+ * themes the `auto` mode picks between.
203
+ * - `'adaptive'` — every colour defers to the terminal (ANSI fg + no fixed
204
+ * fills), so it reads correctly on BOTH schemes and never needs detecting.
205
+ */
206
+ export type ThemeVariant = 'dark' | 'light' | 'adaptive';
207
+
197
208
  /** A complete, self-contained theme. */
198
209
  export interface Theme {
199
210
  /** Registry key used on the command line, e.g. `vanilla-pi`. */
200
211
  name: string;
201
212
  /** Human-readable name shown by `/theme`. */
202
213
  displayName: string;
214
+ /** Terminal scheme this palette is built for (absent = `'adaptive'`). */
215
+ variant?: ThemeVariant;
203
216
  c: CColors;
204
217
  codebox: CodeboxTokens;
205
218
  syntax: SyntaxTokens;
@@ -1,8 +1,15 @@
1
1
  /**
2
2
  * vanilla-pi — the original pal-code palette (16-colour ANSI, Gemini-web
3
- * code-box identity). DEFAULT theme: byte-for-byte identical to the palette
4
- * `theme.ts` shipped at baseline HEAD 38e7670, so a fresh config renders
5
- * exactly what shipped before the theme system existed.
3
+ * code-box identity). DEFAULT theme.
4
+ *
5
+ * ADAPTIVE by construction: every colour here is either an ANSI SGR code
6
+ * (which the terminal resolves against its own light/dark palette) or the
7
+ * default-foreground code. There is deliberately NOT a single hardcoded
8
+ * `\x1b[48;2;…` / `\x1b[38;2;…` truecolor value, because those do not follow
9
+ * the terminal's scheme: a fixed dark fill plus a light-scheme ANSI foreground
10
+ * is exactly what made code blocks unreadable after a night → light flip.
11
+ * Anything that needs a pinned canvas lives in github-dark / github-light and
12
+ * is selected by the `auto` theme mode instead.
6
13
  */
7
14
 
8
15
  import type {EditorTheme, MarkdownTheme} from '../tui/theme-types.js';
@@ -29,11 +36,8 @@ const c: CColors = {
29
36
  bright_white: '\x1b[97m',
30
37
  };
31
38
 
32
- /** Readable mid-gray for code text (#8b949e — github-dark's muted tone). */
33
- const codeGray = '\x1b[38;2;139;148;158m';
34
-
35
39
  const codebox: CodeboxTokens = {
36
- surfaceBg: '\x1b[48;2;24;27;31m', // subtle dark fill (#181b1f)
40
+ surfaceBg: '', // no fill — the code box sits on the terminal canvas (adaptive)
37
41
  borderFg: c.cyan, // cyan hue kept; faint (SGR 2) removed for contrast
38
42
  langFg: c.cyan, // earlier language-tag color
39
43
  chipBgIdle: '', // no chip rectangle — label is plain fg text
@@ -41,9 +45,9 @@ const codebox: CodeboxTokens = {
41
45
  chipFgIdle: c.green, // earlier green copy label
42
46
  chipFgHover: `${c.bold}${c.green}`, // hover: bold green label, still bg-free
43
47
  successFg: c.green, // success label `✓ copied` stays green, bg-free
44
- gutterFg: '\x1b[38;2;74;118;120m', // muted teal — dimmer shade of cyan border (#4a7678)
45
- diffDelBg: '\x1b[48;2;61;34;38m', // dark red wash behind removed diff lines (#3d2226)
46
- diffAddBg: '\x1b[48;2;30;58;42m', // dark green wash behind added diff lines (#1e3a2a)
48
+ gutterFg: c.dim, // SGR 2 on the default fg — dimmer in either scheme
49
+ diffDelBg: '', // no wash — the `-` role foreground already carries the meaning
50
+ diffAddBg: '', // no wash — the `+` role foreground already carries the meaning
47
51
  };
48
52
 
49
53
  const markdownTheme: MarkdownTheme = {
@@ -51,8 +55,8 @@ const markdownTheme: MarkdownTheme = {
51
55
  link: (text: string) => `${c.underline}${c.cyan}${text}${c.reset}`,
52
56
  linkUrl: (text: string) => `${c.dim}${text}${c.reset}`,
53
57
  code: (text: string) => `${c.bold}${c.magenta}${text}${c.reset}`,
54
- codeBlock: (text: string) => `${codeGray}${text}${c.reset}`,
55
- codeBlockBorder: (text: string) => `${codeGray}${text}${c.reset}`,
58
+ codeBlock: (text: string) => `${c.dim}${text}${c.reset}`,
59
+ codeBlockBorder: (text: string) => `${c.dim}${text}${c.reset}`,
56
60
  quote: (text: string) => `${c.italic}${c.dim}${text}${c.reset}`,
57
61
  quoteBorder: (text: string) => `${c.bold}${c.cyan}${text}${c.reset}`,
58
62
  hr: (text: string) => `${c.dim}${text}${c.reset}`,
@@ -100,18 +104,20 @@ const agentLabels: Record<string, string> = {
100
104
  };
101
105
 
102
106
  /**
103
- * Highlighter roles with their current c-based values — the default visual is
104
- * unchanged: `keyword` is cyan+bold exactly as `${c.cyan}${c.bold}` painted it.
107
+ * Highlighter roles. Every value is ANSI or default-fg, so a syntax-coloured
108
+ * code block re-colours itself when the terminal switches scheme — including
109
+ * `plain`/`comment`, which used to pin the github-dark mid-gray #8b949e and
110
+ * went dark-on-dark on a light canvas.
105
111
  */
106
112
  const syntax: SyntaxTokens = {
107
- comment: codeGray, // highlight.ts:268,274,282,286
113
+ comment: c.dim, // highlight.ts:268,274,282,286 — SGR 2 on the default fg
108
114
  string: c.green, // highlight.ts:299,352
109
115
  number: c.magenta, // highlight.ts:308,356
110
116
  keyword: `${c.cyan}${c.bold}`, // highlight.ts:320
111
117
  method: c.yellow, // highlight.ts:323
112
118
  jsonKey: c.cyan, // highlight.ts:350
113
119
  jsonPrimitive: c.magenta, // highlight.ts:354
114
- plain: codeGray, // highlight.ts:236,248
120
+ plain: '\x1b[39m', // highlight.ts:236,248 — terminal default foreground
115
121
  };
116
122
 
117
123
  /** Values equivalent to today's c.* reads in each component (no visual change). */
@@ -136,7 +142,7 @@ const surface: SurfaceTokens = {
136
142
  dim: c.dim, // sidebar.ts:72,85,92,102
137
143
  },
138
144
  statusLine: {
139
- bg: '\x1b[48;2;32;36;44m', // #20242c — status tier fill, a step lighter than code fill
145
+ bg: '', // no fill — the status tier sits on the terminal canvas (adaptive)
140
146
  border: c.dim, // consumed by status-line.ts right-edge segment accent
141
147
  flash: c.green, // index.ts:816
142
148
  error: c.red, // reserved — no error state today
@@ -176,7 +182,8 @@ const surface: SurfaceTokens = {
176
182
 
177
183
  export const vanillaPi: Theme = {
178
184
  name: 'vanilla-pi',
179
- displayName: 'Vanilla Pi',
185
+ displayName: 'Vanilla Pi (adaptive)',
186
+ variant: 'adaptive', // ANSI-only palette — correct on both light and dark
180
187
  c,
181
188
  codebox,
182
189
  syntax,
@@ -100,3 +100,82 @@ export function buildCanvasRestore(
100
100
  if (payload === '') return '';
101
101
  return wrapTmuxOsc(payload, env);
102
102
  }
103
+
104
+ /**
105
+ * Parse one OSC 10/11 colour payload into a linearised brightness in 0..1.
106
+ *
107
+ * Accepts the two forms terminals actually answer with: `#rrggbb` (also
108
+ * `#rgb`) and X11 `rgb:RRRR/GGGG/BBBB` where each channel is 1–4 hex digits
109
+ * scaled to 0..ffff. Returns null for `?`, empty or malformed payloads.
110
+ *
111
+ * The channels are weighted 0.299/0.587/0.114 (Rec. 601 luma) in *sRGB* space
112
+ * — not linearised — because that is what matches human perception of a
113
+ * terminal background closely enough to pick light vs dark.
114
+ */
115
+ export function luminanceOf(payload: string | undefined): number | null {
116
+ if (payload === undefined || payload === '' || payload === '?') return null;
117
+
118
+ const hex = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(payload);
119
+ if (hex) {
120
+ const digits = hex[1] ?? '';
121
+ const expand = digits.length === 3 ? digits.split('').map((d) => d + d).join('') : digits;
122
+ const r = Number.parseInt(expand.slice(0, 2), 16);
123
+ const g = Number.parseInt(expand.slice(2, 4), 16);
124
+ const b = Number.parseInt(expand.slice(4, 6), 16);
125
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
126
+ }
127
+
128
+ const rgb = /^rgba?:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})$/.exec(payload);
129
+ if (rgb) {
130
+ const channel = (s: string | undefined): number => {
131
+ const v = Number.parseInt(s ?? '', 16);
132
+ const max = 16 ** (s ?? '').length - 1;
133
+ return max > 0 ? (v / max) * 255 : 0;
134
+ };
135
+ return (0.299 * channel(rgb[1]) + 0.587 * channel(rgb[2]) + 0.114 * channel(rgb[3])) / 255;
136
+ }
137
+
138
+ return null;
139
+ }
140
+
141
+ /**
142
+ * Classify a terminal background payload as dark or light.
143
+ *
144
+ * Returns null when the payload cannot be parsed, so callers can fall back to
145
+ * their own default rather than being silently told "dark".
146
+ */
147
+ export function detectScheme(payload: string | undefined): 'dark' | 'light' | null {
148
+ const luma = luminanceOf(payload);
149
+ if (luma === null) return null;
150
+ return luma > 0.5 ? 'light' : 'dark';
151
+ }
152
+
153
+ /**
154
+ * DECSET 2031 — subscribe to the terminal's light/dark *scheme* changes.
155
+ *
156
+ * Terminals that support it (Windows Terminal, VS Code, iTerm2, kitty,
157
+ * WezTerm, Ghostty) push `CSI ? 997 ; 1 n` for dark and `CSI ? 997 ; 2 n` for
158
+ * light whenever the OS flips, instead of requiring a fresh OSC 11 query.
159
+ * Terminals that don't simply ignore the sequence, so this is always safe.
160
+ *
161
+ * The `? 2031 h/l` pair goes through the same tmux pass-through as the canvas
162
+ * sequences: tmux otherwise swallows it and the real terminal never subscribes.
163
+ */
164
+ export function buildSchemeSubscribe(
165
+ on: boolean,
166
+ env: Record<string, string | undefined> = process.env,
167
+ ): string {
168
+ return wrapTmuxOsc(`\x1b[?2031${on ? 'h' : 'l'}`, env);
169
+ }
170
+
171
+ /**
172
+ * Parse a `CSI ? 997 ; 1 n` / `CSI ? 997 ; 2 n` scheme report out of raw bytes.
173
+ *
174
+ * Returns null when the bytes carry no such report, so the caller can tell
175
+ * "no scheme event" apart from "event said dark".
176
+ */
177
+ export function parseSchemeReport(bytes: string): 'dark' | 'light' | null {
178
+ const match = /\x1b\[\?997;([12])n/.exec(bytes);
179
+ if (!match) return null;
180
+ return match[1] === '2' ? 'light' : 'dark';
181
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * OSC 7501 — the Program Status Protocol.
3
+ *
4
+ * Lets pal tell the terminal what it is doing (`working`, `blocked`, `done`,
5
+ * `error`, `idle`) so an agent inbox such as Herdr can list it beside every
6
+ * other agent. The terminal never guesses and never scrapes the screen: the
7
+ * program that knows its own state is the one reporting it.
8
+ *
9
+ * Spec: https://www.superlogical.com/rex/docs/build/program-status (v0.4)
10
+ *
11
+ * Everything here is pure — the exact bytes for a status, in order — so it is
12
+ * testable without a terminal. The caller only decides *when* to report.
13
+ *
14
+ * Grammar (the parts that bite):
15
+ *
16
+ * OSC 7501 ; [key=value (":" key=value)*] ST
17
+ * key := [a-z]+
18
+ * value := [A-Za-z0-9_.,+/=-]*
19
+ *
20
+ * - The separator is `:` and nothing else. `;` between pairs makes the whole
21
+ * report unparseable, which is the mistake the herdr-plus notes record.
22
+ * - `state` is required; an unrecognized value discards the entire report, so
23
+ * a state from a newer revision never silently degrades to `idle`.
24
+ * - Free text (`msg`, `title`) is base64 UTF-8 and MUST NOT contain control
25
+ * characters, newline or tab. A report whose decoded text holds one is
26
+ * dropped whole, so {@link encodeStatusText} flattens before encoding.
27
+ * - Each report *replaces* its record completely. A key omitted from this
28
+ * report is gone from the record afterwards, which is why every report here
29
+ * repeats `app`.
30
+ * - Terminators: `BEL` and `ST` (`ESC \`) are both legal. `BEL` matches the
31
+ * `\u0007` form pal's other OSC builders use (see `osc52.ts`).
32
+ */
33
+
34
+ /** The states a program may report. `clear` is not a state — see {@link buildOscStatusClear}. */
35
+ export type ProgramStatusState = 'idle' | 'working' | 'done' | 'blocked' | 'error';
36
+
37
+ /** Why a `blocked` program cannot continue. Ignored for any other state. */
38
+ export type ProgramStatusKind = 'permission' | 'question' | 'auth';
39
+
40
+ /**
41
+ * The stable program identifier pal registers under.
42
+ *
43
+ * Matches the `app` value Herdr shows as the agent's identity and the key
44
+ * herdr-plus writes into `programs.json`, so the name, icon and tile resolve.
45
+ */
46
+ export const PAL_APP_NAME = 'pal';
47
+
48
+ /** A status report, before encoding. */
49
+ export interface ProgramStatus {
50
+ state: ProgramStatusState;
51
+ /** Defaults to {@link PAL_APP_NAME} at build time. */
52
+ app?: string;
53
+ /** Only meaningful with `state: 'blocked'`. */
54
+ kind?: ProgramStatusKind;
55
+ /** 0–100, only meaningful with `working`/`blocked`. Absent means indeterminate. */
56
+ progress?: number;
57
+ /** One human-readable line. Base64-encoded on the wire. */
58
+ msg?: string;
59
+ }
60
+
61
+ /**
62
+ * Flatten free text to a single control-character-free line.
63
+ *
64
+ * The spec discards the whole report if decoded `msg`/`title` contains
65
+ * `U+0000`–`U+001F` or `U+007F`–`U+009F`, so a stray newline in an error
66
+ * message would silently cost the status update. Collapse every run of
67
+ * whitespace to one space instead of dropping the report.
68
+ */
69
+ export function encodeStatusText(text: string): string {
70
+ const flat = text
71
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the point is to strip them.
72
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ')
73
+ .trim();
74
+ return Buffer.from(flat, 'utf8').toString('base64');
75
+ }
76
+
77
+ /** Clamp to the spec's 0–100 integer range, or `undefined` when not a usable number. */
78
+ function normaliseProgress(progress: number | undefined): number | undefined {
79
+ if (progress === undefined || !Number.isFinite(progress)) return undefined;
80
+ return Math.min(100, Math.max(0, Math.round(progress)));
81
+ }
82
+
83
+ /**
84
+ * Normalise a candidate `app` value to the spec's `[A-Za-z0-9_.+-]{1,32}`.
85
+ *
86
+ * An out-of-charset value is *treated as absent* by a conforming terminal,
87
+ * which would quietly strip pal's identity and leave the pane labelled by its
88
+ * process name. Sanitise instead of dropping.
89
+ */
90
+ function normaliseApp(app: string): string {
91
+ const cleaned = app.replace(/[^A-Za-z0-9_.+-]/g, '').slice(0, 32);
92
+ return cleaned.length > 0 ? cleaned : PAL_APP_NAME;
93
+ }
94
+
95
+ /**
96
+ * Build the OSC 7501 report for `status`.
97
+ *
98
+ * Pairs are emitted in a stable order (`state` first, since it is required)
99
+ * so the output is diffable in tests and logs.
100
+ */
101
+ export function buildOscStatus(status: ProgramStatus): string {
102
+ const pairs: string[] = [`state=${status.state}`];
103
+
104
+ // Present on every report: a report replaces its record, so omitting `app`
105
+ // would erase pal's identity from the record on the next update.
106
+ pairs.push(`app=${normaliseApp(status.app ?? PAL_APP_NAME)}`);
107
+
108
+ if (status.state === 'blocked' && status.kind !== undefined) {
109
+ pairs.push(`kind=${status.kind}`);
110
+ }
111
+
112
+ if (status.state === 'working' || status.state === 'blocked') {
113
+ const progress = normaliseProgress(status.progress);
114
+ if (progress !== undefined) pairs.push(`progress=${progress}`);
115
+ }
116
+
117
+ if (status.msg !== undefined && status.msg.length > 0) {
118
+ pairs.push(`msg=${encodeStatusText(status.msg)}`);
119
+ }
120
+
121
+ return `\x1b]7501;${pairs.join(':')}\x07`;
122
+ }
123
+
124
+ /**
125
+ * Build the report that removes pal's records.
126
+ *
127
+ * Sent on exit so a pane that is no longer running pal does not leave a stale
128
+ * `done` badge behind. Without an `id` this clears every record on the
129
+ * terminal, which is correct: pal is the only program reporting through its
130
+ * own tty.
131
+ */
132
+ export function buildOscStatusClear(app?: string): string {
133
+ if (app === undefined) return '\x1b]7501;state=clear\x07';
134
+ return `\x1b]7501;state=clear:app=${normaliseApp(app)}\x07`;
135
+ }
136
+
137
+ /**
138
+ * Build the feature-detection query (`OSC 7501;?ST`).
139
+ *
140
+ * Detection is optional, and a program that cannot read replies may skip it —
141
+ * unknown OSCs are ignored by every well-behaved terminal. Exported because
142
+ * `pal doctor` (and a future protocol-version check) wants to ask.
143
+ */
144
+ export function buildOscStatusQuery(): string {
145
+ return '\x1b]7501;?\x07';
146
+ }
147
+
148
+ /** Human-readable `state`/`kind` for the status line and `pal doctor` output. */
149
+ export function describeStatus(state: ProgramStatusState, kind?: ProgramStatusKind): string {
150
+ switch (state) {
151
+ case 'working':
152
+ return 'working';
153
+ case 'blocked':
154
+ return kind === undefined ? 'needs you' : `needs you (${kind})`;
155
+ case 'done':
156
+ return 'done';
157
+ case 'error':
158
+ return 'error';
159
+ default:
160
+ return 'idle';
161
+ }
162
+ }
163
+
164
+ /**
165
+ * The state to report once a turn settles.
166
+ *
167
+ * `done` is not "idle with extra steps": the spec says it means *finished, and
168
+ * the user has not looked yet*, and that it survives the shell prompt that
169
+ * follows. That is exactly what an agent inbox is for — it is how a pane that
170
+ * finished while you were in another tab asks for attention.
171
+ *
172
+ * An interrupted turn is `idle`, not `error`: the spec's own rule is that when
173
+ * the user cancels, report `idle`. The user knows what they did; a red badge
174
+ * on a deliberate stop is noise.
175
+ */
176
+ export function settledStatus(interrupted: boolean): ProgramStatusState {
177
+ return interrupted ? 'idle' : 'done';
178
+ }