design-cli-output
О программе
Этот навык предоставляет шаблоны для оформления вывода в терминале CLI с такими возможностями, как цветной текст, индикаторы статуса и несколько уровней детализации, включая JSON. Он охватывает архитектуру функций-репортеров, кросс-терминальную совместимость и поддержку единого нарративного стиля. Используйте его при создании или улучшении CLI-инструмента для стандартизации человеко-читаемого и машинно-обрабатываемого вывода.
Быстрая установка
Claude Code
Рекомендуетсяnpx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/design-cli-outputСкопируйте и вставьте эту команду в Claude Code для установки этого навыка
Документация
Design CLI Output
Consistent multi-level terminal output for CLI.
Use When
- New reporter module → CLI
- Warm/narrative alongside transactional
- Std across commands
- JSON machine parallel to human
- Colors, glyphs, verbosity for new tool
In
- Required: CLI name + audience (devs, ops, end users)
- Required: Commands needing formatting
- Optional: Ceremony/narrative variant?
- Optional: Branding (palette, tone)
Do
Step 1: Color palette
chalk → named palette:
Standard (transactional):
let chalk;
try { chalk = (await import('chalk')).default; }
catch { chalk = new Proxy({}, { get: () => (s) => s }); }
// Status colors
const ok = chalk.green; // success
const fail = chalk.red; // errors
const warn = chalk.yellow; // warnings
const info = chalk.cyan; // identifiers, names
const dim = chalk.dim; // secondary info, paths
const bold = chalk.bold; // headers
Warm (ceremony/narrative):
const C = {
flame: chalk.hex('#FF6B35'), // active elements, fire
amber: chalk.hex('#FFB347'), // arriving items, warm highlights
spark: chalk.hex('#FFF4E0'), // individual items (sparks/skills)
ember: chalk.hex('#8B4513'), // cold/dormant states
warm: chalk.hex('#D4A574'), // neutral warm text
dim: chalk.dim, // background, secondary
fail: chalk.red, // errors stay red (honest)
};
Rules:
- No-color fallback (Proxy pattern)
- Hex for custom (
chalk.hex('#FF6B35')) - Fail/err → red regardless
- Name by semantic role not visual
→ Palette obj w/ named entries + no-color fallback.
If err: chalk unavailable (piped, CI) → Proxy returns strings unchanged. Test NO_COLOR=1.
Step 2: Status indicators
Unicode glyphs or ASCII:
ASCII (max compat):
+ created/installed (green)
- removed/deleted (red)
= skipped/unchanged (dim)
! error/warning (red)
Unicode (richer, UTF-8 term):
✦ item/skill/practice (spark)
◉ active/burning state
◎ cooling/embers state
○ cold/dormant state
◌ available/not installed
✗ failed item
✓ success (use sparingly — not all terminals render it well)
Criteria:
- ASCII → CI/piped
- Unicode → interactive
- Both via
--asciiflag orNO_COLOR - Test: macOS Terminal, Windows Terminal, VS Code, SSH
→ Glyph set communicates status at glance w/o color alone.
If err: Glyph renders ? or box → ASCII equiv. +/-/=/! works everywhere.
Step 3: Verbosity levels
Every cmd supports 4:
| Level | Flag | Audience | Content |
|---|---|---|---|
| Default | (none) | Human at terminal | Formatted, colored, informative |
| Verbose | --verbose or --ceremonial | Human wanting detail | Per-item breakdown, arrival sequences |
| Quiet | --quiet | Scripts, CI | Minimal lines, status icons, no decoration |
| JSON | --json | Machine consumers | Structured, parseable, complete |
Pattern:
function output(data, options) {
if (options.json) {
console.log(JSON.stringify(data, null, 2));
return;
}
if (options.quiet) {
for (const item of data.items) {
const icon = item.ok ? '+' : '!';
console.log(`${icon} ${item.id}`);
}
return;
}
// Default (or verbose) human output
printFormatted(data, { verbose: options.verbose });
}
JSON rules:
- Always valid (no mix w/ human text)
- Include all human data + machine fields
- Consistent keys across cmds
- Exit 0 success, 1 err (regardless of mode)
→ 4 clear levels, consistent behavior across cmds.
If err: Verbose too noisy → opt-in (--ceremonial) not graduated.
Step 4: Voice rules
Tone + style. Prevents inconsistency.
Ex (campfire reporter):
- Present tense, active: "mystic arrives" not "mystic has been installed"
- No exclamation: Quiet confidence.
- Metaphor replaces jargon: "practices" not "dependencies" (ceremony only)
- Failures honest, not catastrophic: "A spark was lost" not "ERROR: installation failed with exit code 1"
- Closing line reflects state: Every op ends summary
- No emoji: Unicode glyphs carry visual weight w/o decorative
- Every word info: If no understanding → remove
Standard (non-ceremony):
- Concise, factual lines
- Status icon + item ID + ctx
- Summary line w/ counts
- Err msgs suggest actions
→ 3-7 voice rules output fns follow.
If err: Rules arbitrary → test. Write same output w/ + w/o rule. If no change → rule not needed.
Step 5: Reporter fns
Module w/ focused fns:
// reporter.js — standard output
export function printResults(results) { ... }
export function printItemTable(items) { ... }
export function printDetections(detections) { ... }
export function printAudit(auditResults) { ... }
export function printDryRun() { ... }
export function warn(msg) { ... }
export function error(msg) { ... }
export { chalk };
Each fn:
- Handle empty/null gracefully
- Compute layout (col widths, padding)
- Output w/ palette
- Summary line at bottom
Ceremony → separate module:
// campfire-reporter.js — warm narrative output
export function printArrival({ teamId, agents, results, ceremonial }) { ... }
export function printScatter({ teamId, agents, results }) { ... }
export function printTend(fires) { ... }
export function printCampfireList({ teams, state, reg }) { ... }
export function printFireSummary({ team, fireData, reg }) { ... }
export function printJson(data) { ... }
→ Independent fns, handle own formatting w/o caller state.
If err: Fn >~50 lines → extract helpers. Reviewable in isolation.
Step 6: Test across envs
# With colors (interactive terminal)
node cli/index.js list --domains
# Without colors (piped)
node cli/index.js list --domains | cat
# With NO_COLOR environment variable
NO_COLOR=1 node cli/index.js list --domains
# JSON mode (parseable)
node cli/index.js campfire --json | jq .
# In CI (typically no TTY)
CI=true node cli/index.js audit
Check:
- Colors in interactive
- No ANSI leaks in piped
- JSON valid (
jq .) - Unicode in target terminals
- Col align w/ varying widths
→ Output correct in all 5 contexts.
If err: ANSI leaks → chalk respects NO_COLOR. Unicode breaks → ASCII fallback.
Check
- Palette has no-color fallback
- Status indicators work color + no-color
- All 4 verbosity levels useful
- JSON valid +
jq-parseable - Voice rules docs + followed
- Reporter fns handle empty/null
- Tested: terminal, piped, NO_COLOR, CI
Traps
- Mix human + JSON:
--jsononly valid JSON. Stray line ("DRY RUN") breaks parsers. Suppress human in JSON mode. - Hardcoded col widths: Varies.
Math.max(...items.map(i => i.id.length))dyn. - Color w/o meaning: Color-only → colorblind + piped lose info. Pair w/ text (
+,OK,ERR). - Ceremony wrong ctx: Interactive only. CI/scripts/
--quiet= noise. Gate behind flags. - Forget summary: Users scan last line first. 1-line summary (counts).
→
scaffold-cli-command— cmds using this outputtest-cli-application— test output matchesbuild-cli-plugin— plugins report results
GitHub репозиторий
Похожие навыки
content-collections
МетаЭтот навык предоставляет проверенную в продакшене настройку для Content Collections — TypeScript-ориентированного инструмента, который преобразует файлы Markdown/MDX в типобезопасные коллекции данных с валидацией Zod. Используйте его при создании блогов, сайтов документации или контентных приложений на Vite + React для обеспечения типобезопасности и автоматической проверки содержимого. Он охватывает всё: от настройки плагина Vite и компиляции MDX до оптимизации развертывания и валидации схем.
polymarket
МетаЭтот навык позволяет разработчикам создавать приложения на платформе прогнозных рынков Polymarket, включая интеграцию с API для торговли и получения рыночных данных. Он также обеспечивает потоковую передачу данных в реальном времени через WebSocket для отслеживания текущих сделок и рыночной активности. Используйте его для реализации торговых стратегий или создания инструментов, обрабатывающих обновления рынка в реальном времени.
creating-opencode-plugins
МетаЭтот навык помогает разработчикам создавать плагины OpenCode, которые подключаются к более чем 25 типам событий, таким как команды, файлы и операции LSP. Он предоставляет структуру плагина, спецификации API событий и шаблоны реализации для модулей на JavaScript/TypeScript. Используйте его, когда вам нужно перехватывать, отслеживать или расширять жизненный цикл ассистента OpenCode AI с помощью пользовательской событийно-ориентированной логики.
sglang
МетаSGLang — это высокопроизводительный фреймворк для обслуживания больших языковых моделей (LLM), специализирующийся на быстрой структурированной генерации JSON, regex и рабочих процессов агентов с использованием кэширования префиксов RadixAttention. Он обеспечивает значительно более высокую скорость вывода, особенно для задач с повторяющимися префиксами, что делает его идеальным для сложных структурированных результатов и многократных диалогов. Выбирайте SGLang вместо альтернатив, таких как vLLM, когда вам требуется ограниченное декодирование или вы создаете приложения с интенсивным совместным использованием префиксов.
