feat(cli): the airship binary and its argument parsing

The one package published to npm. `npx airship` in a project with a dev server
running should be the whole setup, so the binary owns argument parsing, terminal
chrome and error messages that name the fix rather than the stack.
This commit is contained in:
Nayan
2026-08-06 09:36:00 +05:30
parent c0bca4b238
commit 90d3bf9dbe
9 changed files with 1226 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
{
"name": "@airshiplabs/cli",
"version": "0.1.0",
"description": "Airship — a visual editor for your running web app, driven by Claude Code, Codex or OpenCode",
"keywords": [
"ai",
"claude",
"codex",
"developer-tools",
"editor",
"opencode",
"visual-editing"
],
"homepage": "https://github.com/0xnyn/airship#readme",
"bugs": {
"url": "https://github.com/0xnyn/airship/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/0xnyn/airship.git",
"directory": "apps/cli"
},
"license": "MIT",
"type": "module",
"bin": {
"airship": "./dist/index.js"
},
"files": [
"dist"
],
"scripts": {
"build": "tsup && node scripts/vendor-assets.mjs",
"clean": "rm -rf dist .turbo",
"dev": "tsup --watch",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.196",
"@clack/prompts": "^1.7.0",
"@jridgewell/trace-mapping": "^0.3.31",
"@openai/codex-sdk": "^0.146.0",
"@opencode-ai/sdk": "^1.18.13",
"bippy": "^0.5.32",
"citty": "^0.2.2",
"diff": "^9.0.0",
"element-source": "^0.0.5",
"picocolors": "^1.1.1",
"ws": "^8.21.0",
"zod": "^4.0.0"
},
"devDependencies": {
"@airship/core": "workspace:*",
"@airship/editor-tokens": "workspace:*",
"@airship/git": "workspace:*",
"@airship/overlay": "workspace:*",
"@airship/protocol": "workspace:*",
"@airship/server": "workspace:*",
"@airship/source": "workspace:*",
"@types/node": "^22.10.0"
},
"engines": {
"node": ">=22.13.0"
},
"publishConfig": {
"access": "public"
}
}
+187
View File
@@ -0,0 +1,187 @@
/**
* The entry point: routing, help, and exit codes.
*
* Dispatch is done here rather than through citty's `subCommands` for two
* reasons. citty runs a parent's `run` *after* the matched subcommand, so a root
* that both serves and has subcommands would launch a server on `airship
* doctor`; and its `runMain` prints the whole usage page and exits 1 for every
* failure, which turns a one-line typo into a screenful and loses the exit code
* a script would branch on. citty stays the parsing and command-definition
* layer; the choke point is here.
*/
import { runCommand } from "citty";
import { DOCTOR_FLAGS, doctor } from "./commands/doctor";
import { INIT_FLAGS, init } from "./commands/init";
import { SERVE_FLAGS, serve } from "./commands/serve";
import { CliError, didYouMean, EXIT, reportError } from "./lib/errors";
import {
isInteractive,
out,
setColorEnabled,
shouldColor,
} from "./lib/terminal";
import { type CommandHelp, renderHelp } from "./lib/usage";
import { VERSION } from "./lib/version";
import { noTtyError, runWizard } from "./lib/wizard";
const TAGLINE =
"airship — visual web-app editor powered by Claude Code, OpenAI Codex or OpenCode";
const SUBCOMMANDS = {
doctor: {
command: doctor,
flags: DOCTOR_FLAGS,
summary: "Check your environment and report what is wrong.",
},
init: {
command: init,
flags: INIT_FLAGS,
summary: "Create an airship.config.json for this project.",
},
} as const;
type CommandName = keyof typeof SUBCOMMANDS;
function isCommandName(value: string): value is CommandName {
return Object.hasOwn(SUBCOMMANDS, value);
}
/** Prose that belongs in help but describes behaviour, not a single flag. */
const SECTIONS = [
{
body: `By default the agent runs unsandboxed — it can write anywhere you can and reach the network. Pass --safe to confine edits to the project directory, cut network access, and screen destructive shell commands.
Only codex confines writes at the OS level. On claude and opencode --safe screens edits by path and commands by pattern, which does not parse shell — a write redirected out of the project is not caught. Neither cuts raw network access; opencode additionally disables its network tools.`,
title: "Sandboxing",
},
{
body: "opencode is a separate install (`brew install sst/tap/opencode`); airship finds it on PATH. Its --model wants the `provider/model` form, and it has no reasoning-effort control, so --effort, --max-turns and --max-budget do not apply.",
title: "Backends",
},
{
body: "Settings resolve in this order, highest first: flags, then AIRSHIP_* environment variables, then airship.config.json (searched upwards from the project, stopping at the repository root). Run `airship init` to write one.",
title: "Configuration",
},
];
const ROOT_HELP: CommandHelp = {
examples: [
{ command: "airship", note: "detect the port, pick an agent, launch" },
{ command: "airship --target 3000", note: "dev server already on :3000" },
{ command: "airship -t 3000 --mode inline" },
{
command: 'airship --exec "pnpm dev"',
note: "start the dev server too, and stop it on exit",
},
{ command: "airship doctor", note: "why is it not working" },
],
flags: SERVE_FLAGS,
sections: SECTIONS,
subcommands: Object.entries(SUBCOMMANDS).map(([name, entry]) => ({
name,
summary: entry.summary,
})),
tagline: TAGLINE,
usage: [
"airship [options]",
"airship --target <port> [options]",
"airship <command> [options]",
],
};
function subcommandHelp(name: CommandName): CommandHelp {
const entry = SUBCOMMANDS[name];
return {
flags: entry.flags,
tagline: `airship ${name} — ${entry.summary}`,
usage: [`airship ${name} [options]`],
};
}
const ALL_DIGITS = /^\d+$/;
/** `--` ends our flags, so a help flag after it belongs to something else. */
function hasFlag(rawArgs: readonly string[], ...names: string[]): boolean {
for (const raw of rawArgs) {
if (raw === "--") {
return false;
}
if (names.includes(raw)) {
return true;
}
}
return false;
}
/**
* A bare invocation at a terminal asks rather than printing help and failing.
* The answers become argv so there is exactly one path into `serve`.
*/
async function wizardArgs(): Promise<string[]> {
if (!isInteractive()) {
throw noTtyError();
}
const answers = await runWizard(process.cwd());
return [
"--target",
String(answers.target),
"--agent",
answers.agent,
"--mode",
answers.mode,
...(answers.safe ? ["--safe"] : []),
];
}
async function main(rawArgs: string[]): Promise<void> {
const [first] = rawArgs;
const command = first && isCommandName(first) ? first : undefined;
if (hasFlag(rawArgs, "--help", "-h")) {
out(renderHelp(command ? subcommandHelp(command) : ROOT_HELP));
return;
}
if (hasFlag(rawArgs, "--version", "-v")) {
out(`${VERSION}\n`);
return;
}
if (command) {
await runCommand(SUBCOMMANDS[command].command, {
rawArgs: rawArgs.slice(1),
});
return;
}
if (first !== undefined && !first.startsWith("-")) {
// A stray positional. The common one is `airship 3000`, which is a real
// intention typed the wrong way, so say what they meant rather than only
// that it is not a command.
const numeric = ALL_DIGITS.test(first);
throw new CliError(`'${first}' is not an airship command`, {
exitCode: EXIT.unknownCommand,
hint: numeric
? `Did you mean \`airship --target ${first}\`?`
: (didYouMean(first, Object.keys(SUBCOMMANDS), "airship ") ??
"Run `airship --help` to see the commands."),
});
}
await runCommand(serve, {
rawArgs: rawArgs.length > 0 ? rawArgs : await wizardArgs(),
});
}
const argv = process.argv.slice(2);
// Set before anything can fail, so an error raised during parsing is styled the
// same as one raised after. Each command re-derives it once it knows --json.
setColorEnabled(shouldColor({ json: argv.includes("--json") }));
main(argv).catch((err: unknown) => {
process.exit(
reportError(err, {
debug: argv.includes("--debug") || Boolean(process.env.AIRSHIP_DEBUG),
})
);
});
+200
View File
@@ -0,0 +1,200 @@
import { describe, expect, it } from "vitest";
import {
assertKnownFlags,
collectRepeated,
requireAmount,
requireEnum,
requireInteger,
requirePort,
} from "./args";
import { CliError, closest, EXIT } from "./errors";
const NAMES = [
"target",
"port",
"mode",
"agent",
"max-turns",
"max-budget",
"codex-config",
"opencode-url",
"safe",
"help",
];
/** Run the call and hand back the CliError it raised, for inspection. */
function thrown(fn: () => unknown): CliError {
try {
fn();
} catch (err) {
if (err instanceof CliError) {
return err;
}
throw err;
}
throw new Error("expected a CliError, but nothing was thrown");
}
describe("assertKnownFlags", () => {
it("accepts long flags, short aliases and values", () => {
expect(() =>
assertKnownFlags(["-t", "3000", "--mode", "inline", "--safe"], NAMES)
).not.toThrow();
});
it("accepts the --flag=value form", () => {
expect(() => assertKnownFlags(["--target=3000"], NAMES)).not.toThrow();
});
it("accepts the camelCase spelling citty also parses", () => {
expect(() => assertKnownFlags(["--maxTurns", "8"], NAMES)).not.toThrow();
});
it("accepts --no- negation of a boolean", () => {
expect(() => assertKnownFlags(["--no-safe"], NAMES)).not.toThrow();
});
it("rejects an unknown flag and suggests the near miss", () => {
const err = thrown(() => assertKnownFlags(["--targt", "3000"], NAMES));
expect(err.message).toBe("Unknown flag --targt");
expect(err.hint).toBe("Did you mean --target?");
expect(err.exitCode).toBe(EXIT.usage);
});
it("falls back to pointing at --help when nothing is close", () => {
const err = thrown(() => assertKnownFlags(["--wombat"], NAMES));
expect(err.hint).toContain("--help");
});
it("rejects an unknown short alias", () => {
expect(() => assertKnownFlags(["-z"], NAMES)).toThrow(CliError);
});
it("accepts a bundle of known short aliases", () => {
expect(() => assertKnownFlags(["-ta"], NAMES)).not.toThrow();
});
it("stops at -- so a passthrough argument is not ours to judge", () => {
expect(() =>
assertKnownFlags(["-t", "3000", "--", "--not-our-flag"], NAMES)
).not.toThrow();
});
it("ignores values that merely look like flags after a value", () => {
expect(() => assertKnownFlags(["--target", "3000"], NAMES)).not.toThrow();
});
});
describe("collectRepeated", () => {
// The regression this exists for: citty calls node:util parseArgs without
// `multiple`, so it keeps only the last occurrence and every earlier pair
// would be dropped silently.
it("keeps every occurrence, not just the last", () => {
expect(
collectRepeated(
["--codex-config", "a=1", "--codex-config", "b=2"],
"codex-config"
)
).toEqual(["a=1", "b=2"]);
});
it("reads the --flag=value form", () => {
expect(collectRepeated(["--codex-config=a=1"], "codex-config")).toEqual([
"a=1",
]);
});
it("mixes both forms", () => {
expect(
collectRepeated(
["--codex-config=a=1", "--codex-config", "b=2"],
"codex-config"
)
).toEqual(["a=1", "b=2"]);
});
it("returns nothing when the flag is absent", () => {
expect(collectRepeated(["-t", "3000"], "codex-config")).toEqual([]);
});
it("does not swallow the next flag as a value", () => {
expect(() =>
collectRepeated(["--codex-config", "--safe"], "codex-config")
).toThrow(CliError);
});
it("stops at --", () => {
expect(
collectRepeated(["--", "--codex-config", "a=1"], "codex-config")
).toEqual([]);
});
});
describe("requireEnum", () => {
it("passes a valid value through", () => {
expect(requireEnum("inline", "mode")).toBe("inline");
});
it("suggests the near miss", () => {
expect(thrown(() => requireEnum("canvs", "mode")).hint).toBe(
"Did you mean canvas?"
);
});
it("lists the options when nothing is close", () => {
expect(thrown(() => requireEnum("zzzzzz", "agent")).hint).toContain(
"claude, codex, opencode"
);
});
});
describe("requirePort", () => {
it("accepts a port in range", () => {
expect(requirePort("3000", "target")).toBe(3000);
});
it.each(["notaport", "0", "65536", "3000.5", "", "-1"])(
"rejects %o",
(value) => {
expect(() => requirePort(value, "target")).toThrow(CliError);
}
);
});
describe("requireInteger", () => {
it("accepts a whole number", () => {
expect(requireInteger("24", "max-turns")).toBe(24);
});
it.each(["0", "-3", "2.5", "many"])("rejects %o", (value) => {
expect(() => requireInteger(value, "max-turns")).toThrow(CliError);
});
});
describe("requireAmount", () => {
it("accepts a fractional amount", () => {
expect(requireAmount("2.50", "max-budget")).toBe(2.5);
});
// --max-budget never had a NaN check, so `--max-budget lots` meant NaN, which
// compares false against every threshold: the cap silently did not exist.
it.each(["lots", "0", "-5", ""])("rejects %o", (value) => {
expect(() => requireAmount(value, "max-budget")).toThrow(CliError);
});
});
describe("closest", () => {
it("matches a one-character typo", () => {
expect(closest("targt", ["target", "port"])).toBe("target");
});
it("declines when nothing is near enough", () => {
expect(closest("xyz", ["target", "port"])).toBeUndefined();
});
it("scales its tolerance to the input length", () => {
// Two edits on a three-letter word is most of the word, so no suggestion.
expect(closest("abc", ["port"])).toBeUndefined();
expect(closest("opencode-ur", ["opencode-url"])).toBe("opencode-url");
});
});
+447
View File
@@ -0,0 +1,447 @@
/**
* The one place a flag is described.
*
* Each spec feeds three consumers — citty's parser, the help renderer, and the
* validators — so a flag cannot exist in the parser but be missing from help, or
* drift out of alignment the way the old hand-padded help string did.
*
* citty is the parsing layer, not the validation layer. Three things it does not
* do that a user notices immediately, and that we therefore do here:
*
* - It accepts unknown flags silently (`--targt 3000` parses as `targt: true`
* with a stray `3000` positional), so `assertKnownFlags` rejects them.
* - It calls `node:util parseArgs` without `multiple`, so a repeated flag keeps
* only its last occurrence. `collectRepeated` reads those from rawArgs.
* - Its enum failures carry hardcoded ANSI, which would corrupt `--json`, so
* enums are declared as strings here and checked by `requireEnum`.
*/
import type { ArgsDef } from "citty";
import { CliError, didYouMean, EXIT } from "./errors";
export const AGENTS = ["claude", "codex", "opencode"] as const;
export const EFFORTS = [
"minimal",
"low",
"medium",
"high",
"xhigh",
"max",
] as const;
/** The user-facing surface names. `canvas` is the protocol's `shell`. */
export const MODES = ["canvas", "inline"] as const;
/**
* Help sections, rendered in this order. GLOBAL is last because it is the same
* on every command and the reader is looking for the command's own flags first.
*/
export const GROUP_ORDER = [
"CORE",
"AGENT",
"SANDBOX",
"BACKEND",
"GLOBAL",
] as const;
export type FlagGroup = (typeof GROUP_ORDER)[number];
export interface FlagSpec {
alias?: string;
/** Shown in help as `(default: …)`; the value itself is applied downstream. */
defaultHint?: string;
group: FlagGroup;
/** One line, unwrapped — the renderer measures and wraps it to the terminal. */
help: string;
/** Placeholder after the flag name: `--target <port>`. */
hint?: string;
/** Repeatable; read from rawArgs rather than the parsed args. */
multiple?: boolean;
name: string;
type: "boolean" | "string";
values?: readonly string[];
}
export const FLAGS: readonly FlagSpec[] = [
{
alias: "t",
group: "CORE",
help: "Port your dev server is already running on. Detected from your package.json when omitted.",
hint: "<port>",
name: "target",
type: "string",
},
{
alias: "p",
defaultHint: "target + 1",
group: "CORE",
help: "Port for the airship proxy.",
hint: "<port>",
name: "port",
type: "string",
},
{
defaultHint: "current directory",
group: "CORE",
help: "Project root for edits.",
hint: "<dir>",
name: "cwd",
type: "string",
},
{
defaultHint: "canvas",
group: "CORE",
help: "Editor surface. canvas puts your app on a pannable canvas, one live frame per device size; inline injects the editor into your own page. Switchable from the editor too.",
hint: "<name>",
name: "mode",
type: "string",
values: MODES,
},
{
group: "CORE",
help: "Start your dev server with this command and stop it when airship exits, instead of running it yourself in another terminal.",
hint: "<command>",
name: "exec",
type: "string",
},
{
group: "CORE",
help: "Open the editor in your browser once it is listening.",
name: "open",
type: "boolean",
},
{
alias: "a",
defaultHint: "claude",
group: "AGENT",
// Comma-joined rather than `a|b|c`: the pipe form has no break point, so a
// narrow terminal cannot wrap it and the line runs past the edge. The
// pipe form still belongs in the placeholder, where it is short.
help: `Coding agent: ${AGENTS.join(", ")}.`,
hint: "<name>",
name: "agent",
type: "string",
values: AGENTS,
},
{
alias: "m",
defaultHint: "the agent's own default",
group: "AGENT",
help: "Model id.",
hint: "<id>",
name: "model",
type: "string",
},
{
group: "AGENT",
help: `Reasoning effort: ${EFFORTS.join(", ")}.`,
hint: "<level>",
name: "effort",
type: "string",
values: EFFORTS,
},
{
defaultHint: "24",
group: "AGENT",
help: "Cap agent turns per edit (claude only).",
hint: "<n>",
name: "max-turns",
type: "string",
},
{
group: "AGENT",
help: "Stop an edit if it exceeds this cost in USD (claude only).",
hint: "<usd>",
name: "max-budget",
type: "string",
},
{
group: "AGENT",
help: "Auto-commit each accepted edit (Conventional Commits).",
name: "commit",
type: "boolean",
},
{
defaultHint: "off",
group: "SANDBOX",
help: "Confine edits to the project directory and cut network access. See Sandboxing below.",
name: "safe",
type: "boolean",
},
{
defaultHint: "bundled",
group: "BACKEND",
help: "Path to the `codex` binary.",
hint: "<path>",
name: "codex-path",
type: "string",
},
{
group: "BACKEND",
help: "Extra `codex --config` pair; repeatable.",
hint: "<k=v>",
multiple: true,
name: "codex-config",
type: "string",
},
{
defaultHint: "found on PATH",
group: "BACKEND",
help: "Path to the `opencode` binary.",
hint: "<path>",
name: "opencode-path",
type: "string",
},
{
group: "BACKEND",
help: "Attach to a running `opencode serve` instead of starting one.",
hint: "<url>",
name: "opencode-url",
type: "string",
},
{
defaultHint: "its own",
group: "BACKEND",
help: "Run as a named opencode agent.",
hint: "<name>",
name: "opencode-agent",
type: "string",
},
{
group: "BACKEND",
help: "JSON file merged into the opencode server config.",
hint: "<file>",
name: "opencode-config",
type: "string",
},
{
group: "GLOBAL",
help: "Machine-readable JSON on stdout, no colour and no banner.",
name: "json",
type: "boolean",
},
{
alias: "q",
group: "GLOBAL",
help: "Suppress the launch banner. Warnings still print.",
name: "quiet",
type: "boolean",
},
{
group: "GLOBAL",
help: "Print stack traces on failure.",
name: "debug",
type: "boolean",
},
{
alias: "h",
group: "GLOBAL",
help: "Show this help.",
name: "help",
type: "boolean",
},
{
alias: "v",
group: "GLOBAL",
help: "Print the version.",
name: "version",
type: "boolean",
},
];
const BY_NAME = new Map(FLAGS.map((flag) => [flag.name, flag]));
const KEBAB_SEGMENT = /-([a-z])/g;
const LEADING_DASHES = /^--(no-)?/;
/** Flags every command accepts, so they are declared in exactly one place. */
export const GLOBAL_FLAGS: readonly string[] = FLAGS.filter(
(flag) => flag.group === "GLOBAL"
).map((flag) => flag.name);
export function specFor(name: string): FlagSpec {
const spec = BY_NAME.get(name);
if (!spec) {
throw new Error(`unknown flag spec: ${name}`);
}
return spec;
}
export function specsFor(names: readonly string[]): FlagSpec[] {
return names.map(specFor);
}
/** Turn the named specs into the shape citty's `defineCommand` wants. */
export function argsFor(names: readonly string[]): ArgsDef {
const out: ArgsDef = {};
for (const spec of specsFor(names)) {
out[spec.name] = {
...(spec.alias ? { alias: spec.alias } : {}),
description: spec.help,
type: spec.type,
...(spec.hint ? { valueHint: spec.hint } : {}),
};
}
return out;
}
/** Every spelling of a flag the parser will accept, for the unknown-flag check. */
function knownTokens(specs: readonly FlagSpec[]): Set<string> {
const known = new Set<string>();
for (const spec of specs) {
known.add(`--${spec.name}`);
// citty aliases every flag to its camelCase form, so `--max-turns` and
// `--maxTurns` both parse and both have to be recognised here.
known.add(
`--${spec.name.replace(KEBAB_SEGMENT, (_, c: string) => c.toUpperCase())}`
);
if (spec.type === "boolean") {
known.add(`--no-${spec.name}`);
}
if (spec.alias) {
known.add(`-${spec.alias}`);
}
}
return known;
}
const SHORT_ALIASES = (specs: readonly FlagSpec[]): Set<string> =>
new Set(specs.flatMap((spec) => (spec.alias ? [spec.alias] : [])));
/**
* Reject a flag this command does not have, with a suggestion when one is close.
*
* Worth doing by hand because the alternative is silence: citty's parser is
* permissive, so a typo'd flag reaches the command as a stray boolean and the
* run proceeds with the wrong settings.
*/
export function assertKnownFlags(
rawArgs: readonly string[],
names: readonly string[]
): void {
const specs = specsFor(names);
const known = knownTokens(specs);
const shorts = SHORT_ALIASES(specs);
// Compared bare and re-dashed in the message: measuring `targt` against
// `--target` costs two edits of pure punctuation and pushes every real typo
// past the threshold.
const suggestions = specs.map((spec) => spec.name);
for (const raw of rawArgs) {
if (raw === "--") {
// Everything after `--` is deliberately not ours to interpret.
return;
}
if (!raw.startsWith("-") || raw === "-") {
continue;
}
const token = raw.split("=")[0] ?? raw;
if (known.has(token)) {
continue;
}
if (!token.startsWith("--")) {
// A single-dash token may be a bundle of short flags (`-tp`); it is only
// unknown if some character in it is.
const chars = [...token.slice(1)];
const bad = chars.find((c) => !shorts.has(c));
if (!bad) {
continue;
}
throw new CliError(`Unknown flag -${bad}`, {
exitCode: EXIT.usage,
hint: "Run `airship --help` to see every flag.",
});
}
throw new CliError(`Unknown flag ${token}`, {
exitCode: EXIT.usage,
hint:
didYouMean(token.replace(LEADING_DASHES, ""), suggestions, "--") ??
"Run `airship --help` to see every flag.",
});
}
}
/**
* Read a repeatable flag straight from argv.
*
* citty hands us only the last occurrence, and silently dropping every earlier
* `--codex-config` would change what the agent is configured with — the kind of
* bug that only shows up as the model behaving oddly.
*/
export function collectRepeated(
rawArgs: readonly string[],
name: string
): string[] {
const values: string[] = [];
const long = `--${name}`;
for (let i = 0; i < rawArgs.length; i += 1) {
const raw = rawArgs[i];
if (raw === "--") {
break;
}
if (raw === long) {
const next = rawArgs[i + 1];
if (next === undefined || next.startsWith("-")) {
throw new CliError(`${long} needs a value`, {
exitCode: EXIT.usage,
hint: `Pass it as ${long} key=value.`,
});
}
values.push(next);
// Skip the value we just consumed, so it is not re-read as a flag.
i += 1;
} else if (raw?.startsWith(`${long}=`)) {
values.push(raw.slice(long.length + 1));
}
}
return values;
}
export function requireEnum(value: string, name: string): string {
const spec = specFor(name);
const allowed = spec.values ?? [];
if (allowed.includes(value)) {
return value;
}
throw new CliError(`Invalid --${name} '${value}'`, {
exitCode: EXIT.usage,
hint:
didYouMean(value, allowed, "") ?? `Use one of: ${allowed.join(", ")}.`,
});
}
const MAX_PORT = 65_535;
export function requirePort(value: string, name: string): number {
const port = Number(value);
if (!Number.isInteger(port) || port < 1 || port > MAX_PORT) {
throw new CliError(`Invalid --${name} '${value}'`, {
exitCode: EXIT.usage,
hint: `A port is a whole number from 1 to ${MAX_PORT}.`,
});
}
return port;
}
export function requireInteger(value: string, name: string): number {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1) {
throw new CliError(`Invalid --${name} '${value}'`, {
exitCode: EXIT.usage,
hint: "Expected a whole number of 1 or more.",
});
}
return parsed;
}
/** `--max-budget` never had a NaN check, so `--max-budget lots` meant no cap. */
export function requireAmount(value: string, name: string): number {
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new CliError(`Invalid --${name} '${value}'`, {
exitCode: EXIT.usage,
hint: "Expected a positive amount in USD, e.g. --max-budget 2.50.",
});
}
return parsed;
}
+109
View File
@@ -0,0 +1,109 @@
/**
* Everything the CLI says at launch.
*
* Kept apart from the command because it is the part that grows with every
* backend and every surface, and because a dropped spend cap or an ignored
* model is the kind of surprise that is only cheap to discover early.
*/
import type { AgentKind, AirshipSurface } from "@airship/server";
import { isGitRepo } from "@airship/server";
import { style } from "./terminal";
/** What `--safe` actually buys on this backend, stated where the user looks. */
export function safetyBanner(agent: AgentKind, safe: boolean): string {
if (!safe) {
return (
` ${style.yellow("⚠ Unsandboxed:")} the agent can write anywhere and reach the network.\n` +
` ${style.dim("Pass --safe to confine it to this project.")}\n`
);
}
if (agent === "codex") {
return ` ${style.green("Sandboxed:")} edits are confined to the project and the network is off.\n`;
}
// claude and opencode share the same guards, and neither cuts the socket.
return (
` ${style.yellow("Screened:")} edits are confined to the project and destructive commands are\n` +
" blocked — but there is no OS sandbox here. Raw network access is not\n" +
" cut, and the command screen does not parse shell redirection.\n"
);
}
/** Everything a backend silently will not do, said once at launch. */
export function warnBackendLimits(o: {
agent: AgentKind;
cwd: string;
effort?: string;
maxBudgetUsd?: number;
maxTurns?: number;
model?: string;
}): void {
const warn = (message: string): void => {
process.stderr.write(`\n ${style.yellow(`⚠ ${message}`)}\n`);
};
// Codex refuses to run outside a git repo, and both non-Claude backends
// reconstruct their diff baseline from git — so this is worth saying before
// the first edit silently produces an empty diff.
if (o.agent !== "claude" && !isGitRepo(o.cwd)) {
warn(
`${o.cwd} is not a git repository. ${o.agent} needs git for its diff baseline, and undo needs git.`
);
}
if (o.agent !== "claude" && o.maxBudgetUsd !== undefined) {
warn(
`--max-budget is ignored with --agent ${o.agent}: it has no budget cap.`
);
}
if (o.agent !== "claude" && o.maxTurns !== undefined) {
warn(
`--max-turns is ignored with --agent ${o.agent}: it runs each turn to completion.`
);
}
if (o.agent === "opencode" && o.effort) {
warn(
"--effort is ignored with --agent opencode: it exposes no reasoning-effort control.\n Set a provider-specific equivalent through --opencode-config."
);
}
// A bare model id cannot be resolved to a provider, so it would be dropped
// silently and the run would quietly use opencode's default instead.
if (o.agent === "opencode" && o.model && !o.model.includes("/")) {
warn(
`--model '${o.model}' is ignored with --agent opencode: it wants the provider/model form (e.g. anthropic/${o.model}).`
);
}
}
/** The one line that differs per surface — what the user is about to see. */
function surfaceLines(surface: AirshipSurface): string {
if (surface === "inline") {
return (
" The editor is injected into your app, in the page itself.\n" +
` ${style.dim("Pick an element and describe a change · switch to the canvas in the bar.")}\n`
);
}
return (
" Your app opens on a canvas — one live frame per device size.\n" +
` ${style.dim("Pick an element and describe a change · ⇧1 fits · space-drag pans.")}\n`
);
}
export function launchBanner(info: {
agent: AgentKind;
cwd: string;
safe: boolean;
surface: AirshipSurface;
targetPort: number;
url: string;
}): string {
return (
`\n ${style.magenta("◆")} ${style.bold("airship")} — editing ${info.cwd} with ${info.agent}\n` +
` → open ${style.cyan(info.url)}\n` +
` ${style.dim(`(proxying your dev server at http://localhost:${info.targetPort})`)}\n\n` +
// Stated at every launch, not just in --help: a tool that can write
// anywhere on disk should say so where the user is actually looking.
`${safetyBanner(info.agent, info.safe)}\n` +
surfaceLines(info.surface) +
` ${style.dim("Ctrl-C to stop.")}\n\n`
);
}
+130
View File
@@ -0,0 +1,130 @@
/**
* The CLI's error taxonomy.
*
* Every failure a user can cause is a `CliError` carrying the one thing a bare
* message never does: what to do next. The old CLI printed a raw stack trace for
* an unknown flag, which told the user nothing and looked like a crash.
*/
import { style } from "./terminal";
/**
* Exit codes, fixed so scripts can branch on them.
*
* `usage` is 2 because that is what every getopt-descended tool returns for a
* malformed command line, and `interrupted` is 130 (128 + SIGINT) because that
* is what a shell reports when the user presses Ctrl-C.
*/
export const EXIT = {
fail: 1,
interrupted: 130,
unknownCommand: 127,
usage: 2,
} as const;
export class CliError extends Error {
readonly exitCode: number;
/** A concrete next action — a command to run, a flag to pass. */
readonly hint?: string;
constructor(
message: string,
opts: { cause?: unknown; exitCode?: number; hint?: string } = {}
) {
super(
message,
opts.cause === undefined ? undefined : { cause: opts.cause }
);
this.name = "CliError";
this.exitCode = opts.exitCode ?? EXIT.fail;
this.hint = opts.hint;
}
}
/**
* Print a failure and return the code to exit with.
*
* Everything goes to stderr so a caller piping stdout gets a clean stream even
* when the run dies. The stack is withheld unless asked for: for the errors
* users actually hit it is noise, and for the ones they do not it is the first
* thing `--debug` should hand them.
*/
export function reportError(
err: unknown,
opts: { debug?: boolean } = {}
): number {
const message = err instanceof Error ? err.message : String(err);
process.stderr.write(`${style.red(`✗ ${message}`)}\n`);
if (err instanceof CliError && err.hint) {
process.stderr.write(`${style.dim(`↳ ${err.hint}`)}\n`);
}
// An error we did not raise ourselves is a bug, not a user mistake, so say so
// rather than letting it read like something they typed wrong.
if (!(err instanceof CliError)) {
process.stderr.write(
`${style.dim("↳ This looks like a bug in airship. Re-run with --debug for the stack.")}\n`
);
}
if (opts.debug && err instanceof Error && err.stack) {
process.stderr.write(`\n${style.dim(err.stack)}\n`);
}
return err instanceof CliError ? err.exitCode : EXIT.fail;
}
function distance(a: string, b: string): number {
// Single-row Levenshtein: only the previous row is ever needed, and these are
// flag names, so the whole table would be wasted allocation.
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
for (let i = 1; i <= a.length; i += 1) {
const row = [i];
for (let j = 1; j <= b.length; j += 1) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
row[j] = Math.min(
(row[j - 1] ?? 0) + 1,
(prev[j] ?? 0) + 1,
(prev[j - 1] ?? 0) + cost
);
}
prev = row;
}
return prev[b.length] ?? 0;
}
/**
* Scale the tolerance to the length of what was typed, so `--targt` matches
* `--target` but a word that is simply not a flag gets no suggestion at all.
* A confidently wrong "did you mean" is worse than none.
*/
function threshold(length: number): number {
return Math.max(2, Math.floor(length / 3));
}
export function closest(
input: string,
candidates: readonly string[]
): string | undefined {
let best: string | undefined;
let bestScore = Number.POSITIVE_INFINITY;
for (const candidate of candidates) {
const score = distance(input, candidate);
if (score < bestScore) {
bestScore = score;
best = candidate;
}
}
return bestScore <= threshold(input.length) ? best : undefined;
}
/** "Did you mean --target?", or nothing when no candidate is close enough. */
export function didYouMean(
input: string,
candidates: readonly string[],
prefix = ""
): string | undefined {
const match = closest(input, candidates);
return match ? `Did you mean ${prefix}${match}?` : undefined;
}
+67
View File
@@ -0,0 +1,67 @@
/**
* Terminal styling and capability detection.
*
* Colour is one global switch, set exactly once per run before anything prints.
* The `style` helpers read that live switch and return the raw string when it is
* off, so `--json` output and piped output stay byte-identical to what a test
* asserts — no ANSI can leak into a value someone is about to parse.
*/
import pc from "picocolors";
let active = pc.createColors(false);
let enabled = false;
export function setColorEnabled(value: boolean): void {
enabled = value;
active = pc.createColors(value);
}
export function colorEnabled(): boolean {
return enabled;
}
/**
* Whether to colourize. `--json` and NO_COLOR force plain output, FORCE_COLOR
* forces colour, and otherwise it takes a real TTY on stdout. Machine mode
* outranks FORCE_COLOR deliberately: a caller parsing our stdout has a stronger
* claim than an env var it probably did not set itself.
*/
export function shouldColor(opts: { json?: boolean } = {}): boolean {
if (opts.json || process.env.NO_COLOR) {
return false;
}
if (process.env.FORCE_COLOR) {
return true;
}
return Boolean(process.stdout.isTTY);
}
/**
* A real human at both ends. Gates every prompt: with this false we must print
* and exit rather than ask, or a CI job hangs forever on an invisible question.
*/
export function isInteractive(): boolean {
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
}
export const style = {
bold: (s: string): string => active.bold(s),
cyan: (s: string): string => active.cyan(s),
dim: (s: string): string => active.dim(s),
gray: (s: string): string => active.gray(s),
green: (s: string): string => active.green(s),
magenta: (s: string): string => active.magenta(s),
red: (s: string): string => active.red(s),
yellow: (s: string): string => active.yellow(s),
};
/** Chrome — banners, prompts, warnings, errors. Never stdout: that is data. */
export function note(text: string): void {
process.stderr.write(text);
}
/** Data — the launch record, `--json` payloads, help. The parseable channel. */
export function out(text: string): void {
process.stdout.write(text);
}
+10
View File
@@ -0,0 +1,10 @@
/**
* Baked in by tsup's `define` at build time — see tsup.config.ts.
*
* Not read from package.json at runtime: the bundle is a single file that gets
* linked and copied around, and resolving a package.json relative to it would
* find whatever happens to sit beside it, or nothing at all.
*/
declare const __AIRSHIP_VERSION__: string;
export const VERSION: string = __AIRSHIP_VERSION__;
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"],
"strictNullChecks": true
},
"include": ["src"]
}