Building Node.js CLIs for coding agents with clipact

• 12 min read

cover

Coding agents run command-line tools through a shell all day, and most CLIs fail them in predictable ways. Claude Code, Codex, and Gemini CLI merge stdout and stderr into one stream, so a spinner or an update banner corrupts JSON output. Gemini CLI runs commands inside a PTY by default, so code that checks process.stdout.isTTY turns on interactive prompts that wait forever for input. When a tool cancels a run, Codex waits 50 ms after SIGTERM before it sends SIGKILL, and Gemini CLI waits 200 ms. A signal handler has no time to save state before the process dies.

Error handling breaks agents too. Some CLIs write errors as prose to stderr, so the model has to guess what went wrong. Others invent incompatible exit codes. Exit 2 means a usage error in Bash and cobra, an auth failure in Google Workspace CLI, and a blocked action in Claude Code hooks. When confirmation fails without a TTY, some CLIs print “Aborted” and exit 0, and agents treat the run as a success.

To solve these problems once, I wrote CLI guidelines for agents from existing CLIs and agent shell runners. Then I built clipact, a TypeScript framework for Node.js 24 and newer. It implements those guidelines by default, so every command in a CLI gets the same output contract, error registry, offline schema discovery, confirmation gate, and startup profile.

One output contract and two exit codes

In machine mode, every invocation writes one compact JSON object to stdout in a single write call, after all stderr output. When an agent shell runner merges stdout and stderr, no progress line lands inside the JSON.

The result envelope is closed and has three possible keys:

Every result has data or error, and never both. There is no ok field because a second status field can disagree with the payload. A failed command returns no data either, so recovery context belongs in error.details and next.

Exit codes follow the same split. A command exits 0 when the result has data and 1 when the result has error. Agent shell runners show exit codes as bare numbers and do not map them to meanings. The JSON result already carries the error code. Using only 0 and 1 also avoids exit 2, which Claude Code hooks treat as a signal to block an action. When a signal aborts ctx.signal and the handler rejects, clipact writes the error result and re-raises the signal so the shell sees 128 + N.

Each entry in next marks by as agent or user. An agent can run a by: "agent" command itself. A by: "user" step tells the agent to stop and ask a human to sign in, approve spending, confirm a deletion, or change external state. Here is a failure from the launchpad example when a domain needs a DNS record, formatted across lines:

{
"error": {
"code": "verification_pending",
"message": "1 domain(s) need a DNS TXT record before they serve traffic.",
"retryable": false,
"details": {
"domains": [
{
"name": "blog.example",
"verified": true,
"txtRecord": "launchpad-verify=site_1"
},
{
"name": "shop.com",
"verified": false,
"txtRecord": "launchpad-verify=site_1"
}
]
}
},
"next": [
{
"by": "user",
"description": "Add a TXT record on shop.com with the value \"launchpad-verify=site_1\""
},
{
"by": "agent",
"command": "launchpad sites domains add my-blog shop.com",
"description": "Recheck verification after the DNS change (safe to repeat)"
}
]
}

You declare every application error code once in defineCli({ errors }), with a one-sentence description and an optional schema for details. Each command lists the codes it can return in its errors array, and schema <command> publishes those codes and their details schemas. An agent learns what a code means before it sees one.

retryable defaults to false. When a handler throws rate_limited, service_unavailable, or timeout and leaves retryable unset, clipact sets retryable to true only if the command is marked readOnly or idempotent. A repeated non-idempotent command can duplicate side effects, so its transient errors stay non-retryable and point to an inspect or resume step in next.

Agent detection changes presentation only

clipact picks the output format from the first rule that matches:

  1. An explicit --json flag, or --format set to json or human. If you pass both --json and --format human, clipact returns invalid_input.
  2. The environment variable <PREFIX>_OUTPUT, set to json or human.
  3. A detected coding agent, which selects json.
  4. A non-TTY stdout, which selects json. Otherwise, the format is human.

Agent detection checks AI_AGENT and AGENT first, then 11 vendor variables including CLAUDECODE, CODEX_THREAD_ID, GEMINI_CLI, CURSOR_AGENT, OPENCODE, and COPILOT_AGENT_SESSION_ID. --agent, --no-agent, and <PREFIX>_AGENT override detection. CI and TERM do not signal an agent.

Detection is a heuristic, because a human can open a terminal inside an IDE that sets CLAUDECODE=1. For that reason, detection changes presentation defaults only:

BehaviorHuman defaultAgent default
Output formatText on a TTYCompact JSON, even in a PTY
Color and status linesOn a TTY, respects NO_COLOR and FORCE_COLOROff
PromptsOnly when stdin and stdout are TTYs, outside agents and CINever
Help textDescription and usage firstExamples, output fields, error codes, and schema pointer first
Usage errorsShort usage line on stderrFull command help on stderr before the JSON result
ProgressRewritten status linePlain stderr lines, with elapsed-time repeats on quiet waits

Detection never changes permissions, exit codes, the JSON shape, or which operation runs. An agent cannot skip a confirmation gate. When a command’s confirm callback returns a reason and --yes is absent, a human on a TTY gets a Continue? [y/N] prompt on stderr. An agent or non-interactive caller gets confirmation_required with exit code 1 and a by: "user" step that repeats the exact command line with --yes, formatted across lines here:

{
"error": {
"code": "confirmation_required",
"message": "Replaces the live production site \"my-blog\". Confirm with --yes.",
"retryable": false,
"details": { "reason": "Replaces the live production site \"my-blog\"." }
},
"next": [
{
"by": "user",
"command": "launchpad deploys create my-blog ./dist --prod --yes",
"description": "Approve this action, then run it with --yes"
}
]
}

One definition drives parsing, validation, help, and discovery

Each command splits across two modules. The definition module imports only the schema library and clipact. The handler module imports SDKs and loads through a dynamic import() only when that command runs.

commands/put.ts
import { defineCommand } from 'clipact'
import * as z from 'zod'
export const put = defineCommand({
name: 'put',
description: 'Publish a file and return a link',
examples: ['acme artifacts put ./report.pdf'],
input: z.strictObject({
path: z.string().describe('File to publish'),
copies: z
.number()
.int()
.min(1)
.max(5)
.default(2)
.describe('Committed copies'),
network: z
.enum(['mainnet', 'calibration'])
.default('calibration')
.describe('Target network'),
privateKey: z.string().describe('Signing key'),
}),
positionals: ['path'],
env: { network: 'ACME_NETWORK', privateKey: 'ACME_PRIVATE_KEY' },
secrets: ['privateKey'],
output: z.object({ ref: z.string(), url: z.url() }),
errors: ['insufficient_funds'],
confirm: (input) =>
input.network === 'mainnet'
? `Spends mainnet funds for ${input.copies} copies.`
: undefined,
dryRun: true,
handler: () => import('./put.run.js'),
})
commands/put.run.ts
import { CliError, defineHandler } from 'clipact'
import { put } from './put.js'
import { upload } from './sdk.js'
export default defineHandler(put, async (ctx) => {
const { path, copies, network, privateKey } = ctx.input
if (ctx.dryRun) {
return ctx.ok({ ref: 'dry-run', url: 'https://example.com/dry-run' })
}
ctx.progress({ phase: 'upload', message: `Uploading ${path}` })
const ref = await upload({
path,
copies,
network,
privateKey,
signal: ctx.signal,
})
if (!ref) {
throw new CliError({
code: 'insufficient_funds',
message: 'The payer cannot cover the lockup.',
next: [
{ by: 'user', command: 'acme auth fund', description: 'Add funds' },
],
})
}
return ctx.ok({ ref, url: `https://example.com/${ref}` })
})

One object schema handles every input source in this order: command-line flags and positionals, --input JSON from a file or stdin, env fallbacks, and schema defaults. Every field is a kebab-case flag, so privateKey becomes --private-key. If a caller passes the same field as a flag and inside --input, clipact returns invalid_input instead of silently picking one.

Secrets never appear on the command line. Any field in secrets must map to an env variable, fails as invalid_input if passed as a flag or in --input, prints as <redacted> under --debug, and omits defaults and examples from schema.

Validation reports all problems at once with each value’s source, such as flag, positional, input, or env:ACME_NETWORK. When an argument misses an enum value or a subcommand name, the issue includes an expected array of allowed values, so an agent does not parse prose to recover.

The same definitions drive --help, schema --list, and schema <command> with JSON Schema 2020-12 output. They also generate dynamic shell completions through completion bash, completion zsh, and completion fish. Each completion script calls the hidden __complete command on Tab, which reads the definitions and loads no handlers.

clipact parses arguments with node:util parseArgs instead of Commander, Stricli, or Gunshi. Those libraries each have their own parameter model, help renderer, and error types. If you wrap one, you translate definitions in and errors back out. For schemas, clipact accepts any library that implements StandardSchemaV1 and StandardJSONSchemaV1. zod v4 is the default because it implements both interfaces directly and produces detailed validation issues, while Valibot is the faster option when bundle size matters most.

Long-running work, signals, and startup speed

Long-running commands must survive interruption. ctx.checkpoint({ id, next }) prints the job ID to stderr before side effects start, so the ID appears in the output even if SIGKILL arrives 50 ms later. On the first SIGINT, SIGTERM, or SIGHUP, clipact aborts ctx.signal. Pass ctx.signal to SDK calls, fetch, timers, and child processes. When the handler rejects after that abort, clipact writes an interrupted result with the checkpoint’s next steps and re-raises the signal so the shell sees 130, 143, or 129. A handler that ignores ctx.signal can keep running until SIGKILL arrives without writing a result.

Handlers report state changes with ctx.progress({ phase, message }). In human mode on a TTY, clipact rewrites one status line. In machine mode or under an agent, it writes each event as a plain stderr line. When stderr stays quiet for 15 seconds, clipact repeats the latest event with elapsed time, then repeats it every 30 seconds until new output arrives. Those lines keep inactivity timers from stopping long runs, such as Gemini CLI’s 300-second quiet timeout, so handlers do not run timers of their own.

Agents often run several short commands in a row, so every millisecond of startup time repeats on each call. Because handlers, SDKs, mapError, and iso-conf load through dynamic imports, --version, --help, and schema never import SDK code. To stay within the startup budget, bundle the CLI as ESM with code splitting and point bin at a four-line shim that enables Node.js’s compile cache before it imports the bundle:

#!/usr/bin/env node
import module from 'node:module'
module.enableCompileCache?.()
await import('../dist/main.js')

A static import loads before enableCompileCache() runs, so the dynamic import() matters. On Node.js v26.10.0 with a warm compile cache, a bundled two-command zod CLI runs --version in +9 ms, --help in +8 ms, schema <command> in +10 ms, and a command in +14 ms over the node -e '' baseline. Import zod as import * as z from 'zod' rather than import { z } from 'zod', because the named import imports every locale and increases the bundle from 89 KB to 443 KB.

Built-in skills, storage, telemetry, and contract tests

Beyond routing and validation, clipact ships four services that most agent-facing CLIs rebuild:

What clipact leaves out

clipact keeps its scope small on purpose. The package has two dependencies, @standard-schema/spec for types and iso-conf loaded on demand for the store, and leaves several common features out:

Try it

clipact requires Node.js 24 or newer and works with any Standard Schema library such as zod v4:

Terminal window
pnpm add clipact zod

filecoin already runs on clipact, and the repository includes launchpad, a complete mock deployment CLI with contract tests and an esbuild bundle. The remaining milestones are a startup-budget check in CI and an NDJSON --events mode.

Read the documentation and source:

Back to blog