effect-v4-cli
Use when building or reviewing a command-line program on Effect v4 — effect/cli in core, its exit-code contract, and @effected/cli-kit, the presentation boundary that decides who the output is for (human, agent, CI), keeps stdout clean, reports failures on stderr, and adds prompts, Ink screens and live progress views — a TUI, wizard, picker or interactive prompt, and the tests that drive them.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 8
- Forks
- 2
01 前言 Front Matter
- name
- effect-v4-cli
- description
- Use when building or reviewing a command-line program on Effect v4 — effect/cli in core, its exit-code contract, and @effected/cli-kit, the presentation boundary that decides who the output is for (human, agent, CI), keeps stdout clean, reports failures on stderr, and adds prompts, Ink screens and live progress views — a TUI, wizard, picker or interactive prompt, and the tests that drive them.
- when_to_use
- effect/cli, Command, Flag, Argument, @effect/cli, exit code, findings exit code, usage error, --format json, --version, stdout vs stderr, stdin, CliLogger, CliRuntime, CliExit, CliColor, CliTest, @effected/cli-kit/testing, NO_COLOR, FORCE_COLOR, TERM=dumb, bin-only package, emitDts false, Command.Environment, ChildProcess vs Command, --agent, --human, --ci, audience, CliAudience, CliEnv, CliTheme, CliMessage, CliLog, Doc, Render, CliFailure, CliPrompt, prompt fallback, interactive, CliUi, @effected/cli-kit/ui, Ink, Select, MultiSelect, Confirm, TextInput, live view, spinner, progress, DocView, UiProvider, CliUiTest, TestTerminal, TUI, terminal UI, wizard, picker, menu, checkbox, interactive prompt, key bindings, KeyTable, useKeys, Tabs, Viewport, CliUi.lazy, jsx react-jsx, React is not defined, CliUi.map, CliUi.lazyView, masked input, secret prompt, span trail, snapshot serializer
02 资源文件 10
- 参考文档references/bin-only-package.md4.5 KB
- 参考文档references/core-framework.md10.4 KB
- 参考文档references/exit-codes.md9.6 KB
- 参考文档references/gotchas.md9.7 KB
- 参考文档references/live-view.md15.2 KB
- 参考文档references/output-and-logging.md9.1 KB
- 参考文档references/presentation.md21.1 KB
- 参考文档references/prompts-and-screens.md22.0 KB
- 参考文档references/recipes.md15.4 KB
- 参考文档references/testing-a-cli.md27.2 KB
03 SKILL.md 正文
Effect v4 CLIs
Core owns parsing: effect/cli is the whole framework — Command, Flag,
Argument, Prompt, help, exit-code mapping. It owns nothing about who reads
the output or how it reaches them. @effected/cli-kit is the presentation
boundary that fills that gap: it decides the audience (a person, an agent,
a CI job), what the terminal can do, the theme, how a document and a failure
are drawn for that audience, and when a run may prompt. Its root is
React-free; interactive Ink screens and live views live behind
@effected/cli-kit/ui, whose ink and react peers are optional. It is
deliberately not a second framework: it adds no parser and no command model.
The one wiring:
const root = Command.make("tool").pipe(
Command.withSharedFlags(CliAudience.flags()),
Command.withSubcommands([init, verify]),
)
NodeRuntime.runMain(
CliRuntime.main(CliAudience.run(root, { version }), {
platform: NodeServices.layer,
env: { audienceEnvVar: "TOOL_AUDIENCE", log: { envVar: "TOOL_LOG_LEVEL" } },
}),
)
| construct | import | reach for it when |
|---|---|---|
Command, Flag, Argument, Prompt |
effect/cli |
declaring the command tree, its flags, positional arguments and core's line prompts |
ChildProcess, ChildProcessSpawner |
effect/process |
building or running a spawned command — not effect/cli's Command, which only declares your own CLI |
CliRuntime.main, CliRuntime.reportFailures |
@effected/cli-kit |
assembling main: platform, environment, failure reporting through your own logger, and the process exit code |
CliAudience |
@effected/cli-kit |
--audience/--human/--agent/--ci on the root, resolved before core parses |
CliEnv |
@effected/cli-kit |
building audience, terminal, theme and links once, and deciding CliInteractive — normally via main's env; CliEnv.layerTest fixes them in a test |
Audience, TerminalEnv, CurrentRuntimeEnv, EnvOverride |
@effected/env |
reading who runs the program and what the terminal can do (colour level, width, hyperlinks) |
CliInteractive |
@effected/cli-kit |
asking whether this run may prompt a person |
CliTheme, Token, Status, Glyphs |
@effected/cli-kit |
painting by token, a typed status vocabulary, Unicode or ASCII glyphs |
CliMessage |
@effected/cli-kit |
a one-line themed outcome ("created 3 files") that no log level silences |
CliLog.status, CliTheme.forAudience |
@effected/cli-kit |
a status glyph that keeps its colour on the log channel; painting your own lines by the kit's audience rule |
Doc, Render, Fmt, CliLinks |
@effected/cli-kit |
building a report once and rendering it plain for agents, ANSI for people, markdown, or a GitHub Actions log |
CliFormat.flag, CliFormat.print, CliFormat.printJson |
@effected/cli-kit |
a --format flag (auto, a renderer by name, or json; plus aliases such as { human: "auto" }, and custom formats the command renders itself) and the one print that honours it: the report built once as a Doc, the data once as a value. print takes no custom format, so branch on it first; printJson alone for a CLI that keeps its own --json |
CliFailure |
@effected/cli-kit |
drawing a failure as a document, or letting an error draw itself (CliDoc); its in: span trail (spans, appModule) |
CliLog |
@effected/cli-kit |
opt-in diagnostics: a level variable, NDJSON for agents and CI, a file sink, components |
CliLog.parseLevel |
@effected/cli-kit |
reading a level from your own flag or config with the answer CliLog.layer would give (Option of the level) |
CliLogger |
@effected/cli-kit |
the plain, level-routed logger on its own, for a program without CliLog |
CliExit |
@effected/cli-kit |
a findings command (a linter that found problems) exiting non-zero by succeeding, never by failing |
CliColor |
@effected/cli-kit |
the stdout colour decision as a boolean, and core's formatter coloured by it, in a program without env |
CliPrompt.fallback |
@effected/cli-kit |
a flag or argument that prompts with core's Prompt when missing — only when interactive |
CliUi, Select, TextInput, MultiSelect, Confirm |
@effected/cli-kit/ui |
an Ink screen from a handler (prompt) or as a fallback (fallback), with a non-interactive default |
CliUi.lazy |
@effected/cli-kit/ui |
mounting a screen of your own whose module holds the JSX, so a non-interactive run never loads React |
CliUi.map |
@effected/cli-kit/ui |
mapping a screen's answer, e.g. a Confirm behind a --yes boolean flag |
CliUi.live, CliUi.lazyView, DocView, UiProvider |
@effected/cli-kit/ui |
progress that redraws in place while work runs, its view loaded lazily and a final document for runs nobody watches, drawing the Doc IR inside Ink |
CliUi.liveDetached |
@effected/cli-kit/ui |
a live view hosted by code not built on Effect (a test reporter, a bundler plugin): Promise handle/close/exit, its render given directly or as an Effect that reads env's services |
CliUi.routeStream |
@effected/cli-kit/ui |
a Writable to hand a library in place of a terminal stream, routing its lines above a live view's frame through printAbove |
KeyTable, useKeys, KeyHelp, Styled, Viewport, Tabs |
@effected/cli-kit/ui |
writing your own screen: keys as data, themed text, a scrolling list, tabs |
CliTest.sandbox/run/spawn, TestTerminal |
@effected/cli-kit/testing |
spawning a built bin hermetically (run waits and returns the result; spawn returns at once for a long-running bin); driving core prompts in a test |
CliUiTest |
@effected/cli-kit/ui/testing |
driving a screen or live view with keys and reading its frames and the terminal's transcript |
MainOptions.distribution |
@effected/cli-kit |
the carrier the bin was installed through: main provides engine's CurrentDistribution and ends --version with its via <name> <version> suffix |
CurrentDistribution, withDistributionVersion, distributionSuffix |
@effected/kit |
reading the carrier inside the program, or decorating a formatVersion without main |
SourceBoundary |
@effected/workspaces/testing |
pinning which files may read process in a CLI's own tests |
Standards
- Build the CLI on
effect/cli, never@effect/cli— its releases still peer oneffect ^3.x. - Wire every program the one way: share
CliAudience.flags()on the root, run it withCliAudience.run, and passenvtoCliRuntime.main. - Give every
Flag.Booleanan explicitFlag.withDefaultorFlag.optional— omission is a usage error, notfalse. - Provide
@effect/platform-node'sNodeServices.layeronce, asmain'splatform, to satisfyCommand.Environment. - Fail a usage error (
Effect.fail(new CliError.UserError(...))); succeed a query that legitimately matches nothing. - Write program output with
Console.logorDoc.print, one-line outcomes withCliMessage, and diagnostics withEffect.log*— the streams must never trade places. CliFormat.flag'smarkdownis the kit'sRender.markdownof your reportDoc, so a CLI that prints its own markdown string offers it under another name incustom(custom: ["markdown"]throws: a built-in name cannot be custom) and branches on it beforeCliFormat.print.- Build a report as a
Docand let the audience pick the renderer; offer--formatwithCliFormat.flagand print throughCliFormat.print; reach forRender.markdownonly for a file or a step summary. - Ask for input only through
CliPrompt.fallback,CliUi.promptorCliUi.fallback, each with a non-interactive default. - Set
"jsx": "react-jsx"for a.tsxscreen, keep each screen in its own module with a default export, and mount it withCliUi.lazy, so JSX never loads in the command module. - Log through
handle.logConsolewhile a live view is drawn, and not at all while a screen is mounted. Forward foreign output (a child's stderr) withhandle.printAbove(stream, line), which returnsfalse, writing nothing, when no frame is mounted. - Paint a status glyph on a diagnostic with
CliLog.status, and apply the audience rule to your own lines withCliTheme.forAudience; never copy the rule or hand-paint a glyph intoEffect.log*(the logger strips it). - Pass
env: { appModule: import.meta.url }toCliRuntime.mainfrom a bin that is installed undernode_modules/@effected/, so the failure report's span trail keeps its own spans. - Give a live view
render: CliUi.lazyView(() => import("./view.js"))and afinaldocument, so--help, agent, CI and piped runs never load React or Ink. - Report findings by succeeding and calling
CliExit.set(code), never by failing or callingprocess.exitin a handler. - Set
emitDts = falseunder[package.build]ineffected.tomlfor a package whoseexportsis"./package.json"only. - Confine every
processread (env,argv,cwd,execPath,isTTY) tobin.ts,main.tsorversion.ts; pass it down as a plain value.
Footguns
- No v4 line of
@effect/cliexists — seecore-framework.md. Flag.Booleanhas no implicitfalse; omission isMissingOption— seecore-framework.md.CliRuntime.mainwithoutenvbuilds no environment:CliInteractivestaysfalseand nothing ever prompts — seepresentation.md.CliAudience.providealone misses fallback prompts and the failure report; useCliAudience.run— seepresentation.md.CliUi.promptwith a realotherwisehasCancelledalone as its error, but without one (or withotherwise: undefined) it keepsNotInteractive; aCliUiTest.sessionis 80 columns and truncates rows;session.layergoes insideCliEnv.layerTest— seeprompts-and-screens.md,testing-a-cli.md.- Top-level
Docblocks print with no blank line between them; wrap inDoc.section(undefined, [...])— seepresentation.md. FORCE_COLORbeatsNO_COLOR, and a terminal with noTERM/COLORTERMgets no colour — seepresentation.md.TERM=dumbis not interactive: it gets what a pipe gets — seepresentation.md.- An agent audience never gets an escape, even from an explicit
Render.ansi— seepresentation.md. - Under
env,main's formatter shadows one the platform sets; override throughenv.formatter— seerecipes.md. - A
Logger.layer([...])of your own besideCliLogreplaces its whole logger set and silences diagnostics — seepresentation.md. - JSX or an
ink/reactimport in the module that declares your commands loads React on every run,--agentand CI included;@effected/cli-kit/uiitself never does — seeprompts-and-screens.md. "jsx": "react"(classic) crashes a screen at mount withReact is not defined— seeprompts-and-screens.md.- A cancel in a fallback prompt is a defect a handler's
catchTagcannot see;mainrenders it, exit130— seeprompts-and-screens.md. - A line written while a screen is mounted tears the frame (
patchConsoleis off) — seeprompts-and-screens.md. - A screen that awaits another
CliUi.rundeadlocks, andConfirm'sotherwiseis a whole{ confirmed, toggles }, never a boolean (wrap it inCliUi.mapfor a boolean flag) — seeprompts-and-screens.md. - Ink delivers a whole stdin read of keys before React re-renders; a handler must step from current state — see
prompts-and-screens.md. - React error boundaries do not catch errors thrown in Ink
useInput/usePastehandlers — seeprompts-and-screens.md. CliUiTest'spress("y")dies (sendtype("y")orpress({ char: "y" })), its waits are real time (it.livefor a test that sleeps), and undermainwithenvthe session'sinteractiveis shadowed byCliEnv— seetesting-a-cli.md.- A
TextInputmaskpredicate latches from its firsttrueuntil the value is emptied; match the giveaway anywhere (/gh[pousr]_|github_pat_/), never as a prefix, and never echo the value in avalidatemessage, which is drawn unmasked — seeprompts-and-screens.md. - A share headline (
1/3 repos) reads a{ one, other }label by the total, a standalone count by its ownn— seepresentation.md. - The failure report's span trail defaults to
spans: "app", which leaves out spans defined undernode_modules/@effected/andnode_modules/effect/; a bin installed there withoutappModuleloses its own spans too — seepresentation.md. - A human whose stream is not a terminal (
tool | grep) gets an unbounded width; to keep one line whole at a narrow terminal, useDoc.line(content, { wrap: false })— seepresentation.md. - Keep a live view's
LiveOptionsin a module the view does not import, or Biome'snoImportCyclesflagsCliUi.lazyView's dynamic import — seelive-view.md. CliUiTest.session'slayeris typedLayer<CliTheme>but also supplies the streams andCliInteractiveas references: provided where a presentation layer shadows it, it falls back quietly to the real streams — seetesting-a-cli.md.PubSub.shutdownand a bare scope close drop a live view's tail; end withhandle.closeorPubSub.end, and host a view outside Effect withCliUi.liveDetached, not by hand — seelive-view.md.- A live view fed a forking stream subscribes late; pass the
PubSub.Subscriptionitself — seelive-view.md. - The default logger and
runMain's failure report both land on stdout, not stderr — seeoutput-and-logging.md. errorReported: falseis what SUPPRESSES the runtime's own log, not what causes it — seeoutput-and-logging.md.Cannot merge zero API modelsmeans the package needsemitDts: false, not anindex.ts— seebin-only-package.md.- A no-match result must succeed; only a usage error may fail — see
exit-codes.md. it.effectstartsTestClockat the epoch, andTestConsole.logLinesaccumulates across a whole test — seetesting-a-cli.md.Command.providebuilds its layer before the handler runs — a handler cannot pre-flight the value the layer depends on — seegotchas.md.Flag.File(name, { mustExist: true })fails at parse time (a usage error, exit1under a barerunMain,64underCliRuntime.main), not as your own infrastructure error — seegotchas.md.- Two optional positionals bind in declaration order — the first one gets a lone argument, not whichever one "makes sense" — see
gotchas.md. Schema.decodeUnknownSyncin a handler throws a defect, invisible tocatchTag— useSchema.decodeUnknownEffect— seegotchas.md.Runtime.getErrorExitCodereturns1for both "marked 1" and "unmarked" — test the marker withRuntime.errorExitCode in error— seegotchas.md.Argument.Pathresolves a relative value against the process's own cwd, at parse time —Flag.Path/File/Directoryshare the same behavior — seegotchas.md.- The built-in global flags (
--help,--version,--wizard,--completions,--log-level) are on by default, program-wide — trim them withCliConfig.layer({ builtIns: [] }), not per command — seegotchas.md.
Additional resources
- presentation.md — the one wiring, audience and
CliInteractive,CliEnvand its options, colour precedence, the theme vocabulary,CliMessage, theDocIR and renderers, the failure report andCliLog. Load when: wiringmain, deciding which channel a line goes to, rendering a report, or customising the failure report or diagnostics. - prompts-and-screens.md — setup (install line, peers,
jsx: react-jsx), keeping React off non-interactive runs withCliUi.lazy,CliPrompt.fallbackvsCliUi, the widgets and their options, aConfirmworked through (whole-ConfirmResultdefault,CliUi.mapfor a boolean flag), writing a screen withKeyTable/useKeys/Viewport/Tabs, and the rules that keep a screen from tearing the terminal. Load when: setting up Ink screens, asking a person for input, or writing or reviewing an Ink screen. - live-view.md —
CliUi.live: runs, subscribing and ending without losing the tail,logConsole, non-interactive modes and thefinaldocument, a lazy view withCliUi.lazyView, a view hosted outside Effect withCliUi.liveDetachedandCliUi.routeStream,DocViewandUiProvider. Load when: drawing progress that updates in place, hosting a live view from a test reporter or bundler plugin, or hosting an Ink tree the kit did not mount. - core-framework.md — the module inventory, PascalCase constructors,
Flag.Boolean's missing default,Command.Environment, and the two differentCommands. Load when: writing or reviewing theCommand/Flag/Argumentdeclaration itself. - output-and-logging.md — the three defaults core gets wrong at a terminal, the
CliLoggerimplementation facts, exit-code reporting, andCliColor. Load when: wiring a logger by hand, or debugging a duplicate or missing failure report. - bin-only-package.md —
emitDts: false, theexports: "./package.json"shape, and whyCannot merge zero API modelsis not an extractor bug. Load when: building a package whose only surface is abin. - exit-codes.md — the exit-code contract,
CliRuntime.main's assembly order, the code table andexitCodesby tag, and how a findings command exits non-zero by succeeding. Load when: deciding whether a code path should fail or succeed, assemblingmain.ts, or handlingCliErrorexhaustively. - testing-a-cli.md — the two false-green traps, the
layerTestdoubles and a capturingConsole,TestTerminal,CliUiTestfor screens and live views (a workedsessiontest of a whole wizard, the harness traps, the snapshot serializer), andCliTestfor spawning a built bin. Load when: writing a test that asserts on CLI output, a prompt, a screen, a wizard, a live view, or a real subprocess's exit code and streams. - gotchas.md — seven traps that pass a type-check and a casual run:
Command.provide's build order,Flag.File's parse-time existence check, positional binding order,decodeUnknownSync's defect, the exit-code marker,Argument.Path/Flag.Pathresolution, and the on-by-default global flags. Load when: a handler isn't seeing the value you expect, or an exit code doesn't match what the handler did. - recipes.md — patterns the kit deliberately does not package: the main-assembly file layout, the version constant and the carrier on
--version, the JSON failure tap, reading stdin safely, process confinement, and an injectable clock. Load when: wiring up a new CLI front end from scratch.
Anchors in this skill and its references cite the vendored tag at
.repos/effect/packages/effect/src/; a consumer without that tree searches
node_modules/effect/src by symbol name instead of by line number.
Related skills
effect-v4-module-index— which core module owns a capability, includingeffect/processand theNodeServices.layerboundary.effect-v4-idioms—PlatformError, typed errors and core patterns.effect-v4-services-layers— providingCommand.Environmentonce at the boundary, and the memoization discipline.effect-v4-testing—TestClock,TestConsole, and proving a suite can fail.effected-packages— the@effected/envand@effected/cli-kitrows and their construct index.
04 同仓库更多 Skills
testing-actions
Use when writing or reviewing tests for @effected/github-actions, @effected/github, @effected/sbom or @effected/commands — stubbing the GitHub API, writing a service's layerTest or makeTest double, testing the pre/main/post lifecycle through Action.run, or debugging why a test hits the real network or hangs.
supply-chain-attestation
Use when generating a CycloneDX SBOM, checking NTIA minimum elements, building an in-toto statement or a SLSA provenance predicate, signing into a Sigstore DSSE bundle, or uploading an attestation to GitHub.
structuring-an-action
Use when laying out a new GitHub Action repository on the @effected suite, deciding where a piece of code belongs (an entry point, a step, a shared service, a shim), or reviewing an existing action's file structure against the canonical shape.
running-commands-and-tools
Use when running a subprocess in Effect v4, spawning a command, capturing stdout/stderr/exit code, checking whether a CLI tool is installed or which copy to run, running a package-manager script through the project's launcher, detaching a background process, or redacting a secret from argv or captured output.
release-and-publish
Use when publishing a package to npm, reading the npm registry from Effect v4, checking whether a version is already published, cutting a release tag or GitHub release from an action, applying a release-age gate, or deriving tracking tags for GitHub Actions distribution.
hardening-a-parser-port
Use when porting or writing a recursive-descent parser, lexer, or tree-walker over untrusted text in the @effected monorepo — the class of hardening the cloud reviewer scans for on every migration. Covers stack-overflow depth guards (on EVERY recursion surface, which a facade has N of — not two), numeric bound guards that must reject NaN and non-integers, code-point range checks scoped to formats with wide escapes, prototype-pollution, control-character rejection, and the invariant that malformed input must fail through the typed error channel, never as an unhandled defect.