蓝色天空网mbsky.com · 知识 · 实践 · 创造Pi Agent · 本地阅读预览
教程 / AI / 智能开发 / Pi Agent

Pi Agent 主题定制

实际加载、切换、热重载并核对主题及 HTML 导出色。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

从终端默认配色开始

Pi 的交互界面以 JSON 定义颜色角色。固定版 Pi 1.5.0 有51个必填令牌与5个可选令牌,覆盖正文、选择与滚动、消息、工具结果、Markdown、代码和编辑框状态。早期的四个可选项说明少了 scrollbarTrack。

当前内置 system、dark 和 light。缺省使用 system,它会根据终端提供的背景、前景和 ANSI 调色板调整颜色。终端若给不全,会按可用报告使用后备色。打开 /settings 的 Theme,也可在 settings.json 写入 theme。需要按终端背景自动选两套主题时,例如填 light/dark,斜线前后依次是浅色与深色方案。

用名称启用自编主题

在代理配置目录的 themes 子目录保存 JSON,例如 night-study.json,同时在 JSON 的 name 填 night-study。顶层可写 $schema、appearance、vars 和 export,name 与 colors 必填。颜色角色必须来自当前主题规范。只想在一次交互运行中改初始主题可用 --use-theme,--theme 路径负责增加可用主题。

当前活动的用户主题位于配置目录 themes/<主题名>.json 时,Pi 会监听该文件并在有效编辑后重新加载。独立路径、项目和包来源可以通过 /reload 重新读取。项目内主题需要可信项目配置,包测试使用本地主题文件和资源清单。

颜色表示、变量与终端能力

颜色可用三位或六位十六进制 RGB、OKLCH、OKHSL、0 至 255 的数字索引、vars 中的名称或空字符串。变量可以继续引用变量。丢失变量与循环引用会使主题失效。空字符串发送终端默认前景或背景控制序列。24 位终端可直接使用 RGB,256 色终端会把颜色近似到调色板。

选择正确的令牌

先找界面角色,再调整值。例如通用高亮从 accent 开始,编辑区的显眼边框用 borderAccent,弱边框用 borderMuted。明暗、成功和错误状态各自有颜色。

消息与工具通常有独立前景和背景。固定版新增的 scrollbarTrack 是前景色,缺省沿用 muted;scrollbarThumb 同样是前景色,缺省沿用 text。搜索普通命中以 selectedBg 和 text 为后备,当前命中另按交互样式突出。

Markdown 普通标题、链接、行内代码与代码围栏可各自着色。有语言信息的代码块还会使用 syntax 系列令牌给词法元素着色。

不同推理档位可以用编辑框颜色区分。可选的 thinkingMax 缺省沿用 thinkingXhigh。差异工具的新增、删除和上下文颜色各管一类行,bashMode 用于交互 Shell 输入的边框提示。

查看 HTML 导出的实际颜色

在 export 对象可选写 pageBg、cardBg、infoBg,分别控制页面、卡片及信息区域的背景。某项省略时,Pi 基于 userMessageBg 推导对应颜色。HTML 的 OKHSL 需要转成 CSS 可用颜色,实验同时导出两份自编会话主题,检查浏览器实际读取的背景值。

用不同内容复核配色

按实际深浅背景检视文本对比度。颜色可借鉴成熟方案的组织方式。逐次观察用户和扩展消息、工具的三种状态、Markdown、语法高亮以及长行折叠,再决定是否选为日常主题。

固定的浅色与深色选项

名称用途与选用
dark为深色背景提供固定配色。未设置主题时默认采用 system。
light为浅色背景提供固定配色。light/dark 由终端报告决定选哪一套。

Pi 发现主题的入口

入口范围与条件
内置system 随终端颜色计算,dark 和 light 也可直接选择。
<代理配置目录>/themes/*.json供不同项目选择。活动主题同名文件适用监视重载。
.pi/themes/*.json在可信项目发现的主题。
Pi 包中的 themes经包清单或默认资源位置提供;本例只用临时本地目录。
--theme 路径增加该路径的主题资源。--use-theme 名称负责挑选初始主题。

颜色值及其含义

值形式本站示例运行条件
十六进制 RGB#4ad 或 #44aadd短写的每位展开一次,色值可用于 24 位 ANSI。
索引242填 0 至 255 的整数,终端通过自己的调色板显示。
变量名highlight在 vars 定义,可引用另一个已定义变量。
空字符串""按令牌类型选择终端默认前景或背景。

核心界面

令牌用途与条件
accent突出的品牌元素、选中项和光标等前景。
border界面的一般边框前景。
borderAccent强调状态使用的高亮边框。
borderMuted弱化显示的边框。
success成功提示的文字或标记色。
error错误提示的文字或标记色。
warning警告状态的文字或标记色。
muted较低强调级别的文字颜色。
dim需要更淡化的提示文字颜色。
text一般正文前景,可用空字符串继承终端。
thinkingText模型推理块显示文字的前景。

消息、工具状态与全屏标记

令牌用途与条件
selectedBg选中条目的背景。
userMessageBg用户消息区的背景,也参与 HTML 默认色推导。
userMessageText用户消息区的文字前景。
customMessageBg扩展自定义消息区的背景。
customMessageText扩展自定义消息的正文前景。
customMessageLabel扩展自定义消息标签的前景。
toolPendingBg工具等待或运行时的区域背景。
toolSuccessBg工具成功时的区域背景。
toolErrorBg工具失败时的区域背景。
toolTitle工具输出区域中标题的前景。
toolOutput工具输出正文的前景。
scrollbarThumb全屏滚动条滑块前景。可选,默认取 text。
searchMatchBg普通搜索命中文本的背景。可选,默认取 selectedBg。
searchMatchText普通搜索命中文本的前景。可选,默认取 text。

Markdown 显示

令牌用途与条件
mdHeading标题文字的前景。
mdLink链接可读文字的前景。
mdLinkUrl链接地址文字的前景。
mdCode段落中行内代码的前景。
mdCodeBlock代码块没有专门高亮时正文使用的前景。
mdCodeBlockBorder围住 Markdown 代码块的边框前景。
mdQuote引用块文字的前景。
mdQuoteBorder引用块左侧边线的前景。
mdHr水平分隔线的前景。
mdListBullet列表圆点或数字序号的前景。

代码高亮

令牌用途与条件
syntaxComment代码注释。
syntaxKeyword语言关键字。
syntaxFunction被语法高亮识别的函数名。
syntaxVariable被识别的变量名。
syntaxString字符串字面量。
syntaxNumber数字字面量。
syntaxType类型标识。
syntaxOperator运算符。
syntaxPunctuation语法标点。

推理档位的编辑框

令牌用途与条件
thinkingOff推理档位 off。
thinkingMinimal推理档位 minimal。
thinkingLow推理档位 low。
thinkingMedium推理档位 medium。
thinkingHigh推理档位 high。
thinkingXhigh推理档位 xhigh。
thinkingMax推理档位 max。可选,缺省取 thinkingXhigh。

差异与 Shell 输入

令牌用途与条件
toolDiffAdded工具差异视图中新增行的文字色。
toolDiffRemoved工具差异视图中删除行的文字色。
toolDiffContext差异视图上下文行的文字色。
bashModeShell 输入模式在编辑器边框上的提示色。

当前版本增加的令牌

令牌用途默认来源
scrollbarTrack全屏滚动条轨道前景muted

观察终端主题回退和导出的实际背景色

javascript · 阅读源码
import assert from 'node:assert/strict';
import {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
import {setTimeout as delay} from 'node:timers/promises';
import {tmpdir} from 'node:os';
import {basename, dirname, join, resolve} from 'node:path';
import {pathToFileURL} from 'node:url';

const modules = process.argv[2];
if (!modules) throw new Error('Supply the installed node_modules path.');
const packageDir = resolve(modules, '@earendil-works', 'pi-coding-agent');
const moduleUrl = name => pathToFileURL(join(packageDir, 'dist', 'modes', 'interactive', 'theme', name)).href;
const {THEME_TOKENS} = await import(moduleUrl('theme-tokens.js'));
const {validateThemeJson} = await import(moduleUrl('theme-schema.js'));
const {getAvailableThemes, getThemeExportColors, initTheme, loadThemeFromPath, onThemeChange,
  resolveThemeSetting, setRegisteredThemes, setThemeJsonValidator, stopThemeWatcher, SYSTEM_THEME_NAME, theme} =
  await import(moduleUrl('theme.js'));
const agentModule = name => import(pathToFileURL(join(packageDir, 'dist', name)).href);
const {DefaultResourceLoader, SessionManager, SettingsManager} = await agentModule('index.js');
const {colorToHex} = await import(pathToFileURL(resolve(modules, '@earendil-works', 'pi-tui', 'dist', 'index.js')).href);
const {exportSessionToHtml} = await agentModule('core/export-html/index.js');
const {version} = JSON.parse(await readFile(join(packageDir, 'package.json'), 'utf8'));
setThemeJsonValidator(validateThemeJson);
const required = Object.entries(THEME_TOKENS).filter(([, value]) => !value.fallback).map(([key]) => key);
const optional = Object.fromEntries(Object.entries(THEME_TOKENS).filter(([, value]) => value.fallback)
  .map(([name, value]) => [name, value.fallback]));
const results = [];
function check(name, input, expected, actual) {
  assert.deepStrictEqual(actual, expected, name);
  results.push({name, input, expected, actual, passed: true});
}
const base = resolve(tmpdir());
const folder = await mkdtemp(join(base, 'mbsky-pi-palette-'));
assert.equal(dirname(resolve(folder)), base);
assert.ok(basename(folder).startsWith('mbsky-pi-palette-'));
try {
  const themeFile = join(folder, 'night-study.json');
  const save = data => writeFile(themeFile, JSON.stringify(data), 'utf8');
  const draft = {
    name: 'night-study', appearance: 'dark', vars: {ink: '#bed6e5', highlight: 'ink'},
    colors: Object.fromEntries(required.map(name => [name, THEME_TOKENS[name].slot === 'background'
      ? '#202938' : 'ink'])),
  };
  Object.assign(draft.colors, {accent: 'highlight', muted: 242, text: '', thinkingXhigh: '#a873d1'});
  check('current_required_and_optional_tokens', {schema: 'Pi 1.5.0'},
    [51, {scrollbarTrack: 'muted', scrollbarThumb: 'text', searchMatchBg: 'selectedBg',
      searchMatchText: 'text', thinkingMax: 'thinkingXhigh'}],
    [required.length, optional]);
  await save(draft);
  const loaded = loadThemeFromPath(themeFile, 'truecolor');
  check('color_variables_and_indexed_ansi', {accent: 'highlight → ink', muted: 242},
    [true, true], [loaded.fg('accent', 'Q').includes('\x1b[38;2;190;214;229m'),
      loaded.fg('muted', 'Q').includes('\x1b[38;5;242m')]);
  for (const [token, descriptor] of Object.entries(THEME_TOKENS)) {
    const paint = descriptor.slot === 'background' ? loaded.bg.bind(loaded) : loaded.fg.bind(loaded);
    const ansi = paint(token, 'Q');
    const fallback = descriptor.fallback;
    const related = fallback ? paint(fallback, 'Q') : ansi;
    check('paint:' + token, {token, slot: descriptor.slot, fallback: fallback ?? null},
      [true, true], [ansi.includes('Q') && ansi.startsWith('\x1b['), ansi === related]);
  }
  check('missing_optional_tokens_follow_schema_fallbacks', {omitted: Object.keys(optional)},
    Object.values(optional).map(name => loaded.colors[name]), Object.keys(optional).map(name => loaded.colors[name]));
  check('terminal_default_uses_sgr_reset_foreground', {text: ''}, '\x1b[39mQ\x1b[39m', loaded.fg('text', 'Q'));
  const broken = structuredClone(draft);
  delete broken.colors.accent;
  await save(broken);
  assert.throws(() => loadThemeFromPath(themeFile, 'truecolor'), /Missing required color tokens:[\s\S]*accent/);
  results.push({name: 'missing_required_color_is_rejected', input: 'accent omitted',
    expected: 'Missing color accent', actual: 'Missing color accent', passed: true});
  const cycle = {...draft, vars: {ink: 'highlight', highlight: 'ink'}};
  await save(cycle);
  assert.throws(() => loadThemeFromPath(themeFile, 'truecolor'), /Circular variable reference/);
  results.push({name: 'cyclic_color_aliases_are_rejected', input: 'mutual variable references',
    expected: 'Circular variable reference', actual: 'Circular variable reference', passed: true});
  initTheme();
  check('default_system_and_explicit_automatic_pair', {setting: 'light/dark'},
    [SYSTEM_THEME_NAME, 'light', 'dark'], [theme.name, resolveThemeSetting('light/dark', 'light'),
      resolveThemeSetting('light/dark', 'dark')]);
  const getAnsi = value => value.match(/\x1b\[[0-9;]*m/)?.[0];
  await save({...draft, colors: {...draft.colors, accent: '#4ad', mdHeading: 'oklch(62% 0.1 200)',
    border: 'okhsl(250 60% 55%)'}});
  const modern = loadThemeFromPath(themeFile, 'truecolor');
  const reduced = loadThemeFromPath(themeFile, '256color');
  check('modern_formats_and_256_color_approximation', {values: ['#4ad','oklch','okhsl']},
    ['\x1b[38;2;68;170;221m', true, true, true],
    [getAnsi(modern.fg('accent', 'Q')), ...['mdHeading','border'].map(token => getAnsi(modern.fg(token, 'Q')).startsWith('\x1b[38;2;')),
      getAnsi(reduced.fg('accent', 'Q')).startsWith('\x1b[38;5;')]);

  const profile = join(folder, 'profile');
  const cwd = join(folder, 'reading-room');
  const profileThemes = join(profile, 'themes');
  const projectThemes = join(cwd, '.pi', 'themes');
  const packageThemes = join(folder, 'local-theme-package', 'themes');
  for (const dir of [profileThemes, projectThemes, packageThemes]) await mkdir(dir, {recursive: true});
  process.env.PI_CODING_AGENT_DIR = profile;
  const globalPath = join(profileThemes, 'night-study.json');
  const projectPath = join(projectThemes, 'room-only.json');
  const packagePath = join(packageThemes, 'bundle-color.json');
  const explicitPath = join(folder, 'extra-colors.json');
  await writeFile(globalPath, JSON.stringify(draft));
  await writeFile(projectPath, JSON.stringify({...draft, name: 'room-only'}));
  await writeFile(packagePath, JSON.stringify({...draft, name: 'bundle-color'}));
  await writeFile(join(folder, 'local-theme-package', 'package.json'), JSON.stringify({
    name: 'course-theme-fixture', version: '1.0.0', pi: {themes: ['./themes']},
  }));
  await writeFile(explicitPath, JSON.stringify({...draft, name: 'extra-colors'}));
  await writeFile(join(profile, 'settings.json'), JSON.stringify({
    theme: 'night-study', packages: [dirname(packageThemes)],
  }));
  const names = async trusted => {
    const settingsManager = SettingsManager.create(cwd, profile, {projectTrusted: trusted});
    const loader = new DefaultResourceLoader({cwd, agentDir: profile, settingsManager,
      additionalThemePaths: [explicitPath], noContextFiles: true, noExtensions: true, noSkills: true,
      noPromptTemplates: true, disabledBuiltinExtensions: ['mcp']});
    await loader.reload();
    return loader.getThemes().themes.map(t => t.name).sort();
  };
  check('built_in_theme_names_and_saved_preference', {profile: 'isolated'},
    [true, true, true, 'night-study'], ['system', 'dark', 'light'].map(name => getAvailableThemes().includes(name))
      .concat(SettingsManager.create(cwd, profile).getTheme()));
  check('loader_discovers_user_project_package_and_explicit', {projectTrusted: true},
    ['bundle-color', 'extra-colors', 'night-study', 'room-only'], await names(true));
  check('loader_omits_untrusted_project_theme', {projectTrusted: false},
    ['bundle-color', 'extra-colors', 'night-study'], await names(false));

  setRegisteredThemes([]);
  initTheme('night-study', true);
  const startColor = theme.colors.accent;
  let changeCount = 0;
  onThemeChange(() => { changeCount++; });
  const watchUpdate = {...draft, colors: {...draft.colors, accent: '#37cfaa'}};
  try {
    await writeFile(globalPath, JSON.stringify(watchUpdate));
    const deadline = Date.now() + 4000;
    while (changeCount === 0 && Date.now() < deadline) await delay(25);
    check('active_user_theme_reloads_on_disk_change', {file: 'profile/themes/night-study.json'},
      [true, true, '#37cfaa'], [changeCount > 0, startColor !== theme.colors.accent,
        colorToHex(theme.colors.accent)]);
  } finally {
    stopThemeWatcher();
  }
  const output = process.argv[3] ? resolve(process.argv[3]) : folder;
  const exportThemePath = join(profileThemes, 'export-study.json');
  const exportTheme = {...draft, name: 'export-study', export: {
    pageBg: '#172133', cardBg: '#243958', infoBg: '#31496e',
  }};
  await writeFile(exportThemePath, JSON.stringify(exportTheme));
  const plainTheme = {...draft, name: 'derived-study'};
  await writeFile(join(profileThemes, 'derived-study.json'), JSON.stringify(plainTheme));
  const fileSession = SessionManager.create(cwd, join(folder, 'session-output'));
  fileSession.appendMessage({role: 'user', content: 'Choose two labels for a reading room.', timestamp: Date.now()});
  await exportSessionToHtml(fileSession, undefined, {outputPath: join(output, 'explicit-palette.html'), themeName: 'export-study'});
  await exportSessionToHtml(fileSession, undefined, {outputPath: join(output, 'derived-palette.html'), themeName: 'derived-study'});
  const explicit = await readFile(join(output, 'explicit-palette.html'), 'utf8');
  const derived = await readFile(join(output, 'derived-palette.html'), 'utf8');
  const exportVars = content => Object.fromEntries([...content.matchAll(/--export(PageBg|CardBg|InfoBg):\s*([^;]+);/g)]
    .map(match => [match[1], match[2]]));
  check('html_contains_explicit_export_colors', {source: exportTheme.export},
    {PageBg: '#172133', CardBg: '#243958', InfoBg: '#31496e'}, exportVars(explicit));
  check('html_derives_unspecified_export_colors', {userMessageBg: '#202938'},
    {PageBg: 'rgb(22, 29, 39)', CardBg: 'rgb(27, 35, 48)', InfoBg: 'rgb(52, 56, 56)'}, exportVars(derived));
  process.stdout.write(JSON.stringify({nodeVersion: process.version, packageVersion: version, results}) + '\n');
} finally {
  await rm(folder, {recursive: true, force: true});
}
预期结果 · 待实际运行核验
  • 缺少必填令牌时会报告具体名称。缺省 scrollbarThumb 使用 text,主题名称相同的活动用户文件改变后重新加载。导出浏览器读取显式背景和来自用户消息背景的推导值。
观察终端主题回退和导出的实际背景色

所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、pywinpty 3.1.2、离线 Chromium。

当前源码 SHA256:30e22f7da0461426a6ad53edaa71aacb0aaf5af51707aacfdc2505eb5d92e43d

下载本站示例源码

本地复跑

按 README 执行两个自编实验。继续用自己的终端查看配色和消息对比度。

下载 Pi 主题颜色、菜单和 HTML 导出实验

所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、pywinpty 3.1.2、离线 Chromium。

ZIP SHA256:0054d60cc5736d353816b86620cb0ca8ed7a5753c05b80e6c42646c37fee6697

常见错误与边界

  • 主题名称和用户目录中的文件名需要相配才能触发监听。
  • 关注颜色槽位,以免将前景角色与背景角色混用。

练习与解答

想让滚动条轨道更暗,该调整哪个词条?省略时用哪个颜色?

展开参考解答

设置 scrollbarTrack。省略时,Pi 1.5.0 使用 muted 的颜色。

规范与官方依据