feat(cli): config, settings and the setup wizard

Config is optional by design — the wizard exists for the cases detection cannot
settle on its own, and writes the answer so it is asked once.
This commit is contained in:
Nayan
2026-08-07 19:09:00 +05:30
parent fa2bc60655
commit ecd1385ebb
4 changed files with 644 additions and 0 deletions
+190
View File
@@ -0,0 +1,190 @@
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
asBoolean,
asList,
asString,
envSettings,
loadConfig,
mergeSettings,
} from "./config";
import { CliError } from "./errors";
/** Build a throwaway project tree and return its root. */
function fixture(files: Record<string, string>): string {
const root = mkdtempSync(join(tmpdir(), "airship-config-"));
for (const [path, contents] of Object.entries(files)) {
const full = join(root, path);
mkdirSync(join(full, ".."), { recursive: true });
writeFileSync(full, contents);
}
return root;
}
/** The hint on the CliError a call raises, for asserting on the guidance. */
function hintOf(fn: () => unknown): string | undefined {
try {
fn();
} catch (err) {
if (err instanceof CliError) {
return err.hint;
}
throw err;
}
}
describe("loadConfig", () => {
it("reads airship.config.json from the directory itself", () => {
const root = fixture({
"airship.config.json": '{ "target": 3000, "agent": "codex" }',
});
const { source, values } = loadConfig(root);
expect(source).toBe(join(root, "airship.config.json"));
// A JSON number is normalised to the string every validator expects.
expect(values).toEqual({ agent: "codex", target: "3000" });
});
it("walks up to find one in a parent", () => {
const root = fixture({
".git/HEAD": "ref: refs/heads/main\n",
"airship.config.json": '{ "target": 4321 }',
"apps/web/package.json": "{}",
});
expect(loadConfig(join(root, "apps/web")).values.target).toBe("4321");
});
it("stops at the repository root", () => {
// The config sits *above* the repo root, so it belongs to something else.
const root = fixture({
"airship.config.json": '{ "target": 9999 }',
"repo/.git/HEAD": "ref: refs/heads/main\n",
});
expect(loadConfig(join(root, "repo")).values).toEqual({});
});
it("reads an airship key out of package.json", () => {
const root = fixture({
"package.json": '{ "name": "x", "airship": { "mode": "inline" } }',
});
const { source, values } = loadConfig(root);
expect(source).toBe(join(root, "package.json"));
expect(values.mode).toBe("inline");
});
it("prefers airship.config.json over the package.json key", () => {
const root = fixture({
"airship.config.json": '{ "target": 1111 }',
"package.json": '{ "airship": { "target": 2222 } }',
});
expect(loadConfig(root).values.target).toBe("1111");
});
it("accepts camelCase and stores the flag spelling", () => {
const root = fixture({ "airship.config.json": '{ "maxTurns": 8 }' });
expect(loadConfig(root).values["max-turns"]).toBe("8");
});
it("accepts the kebab spelling too", () => {
const root = fixture({ "airship.config.json": '{ "max-turns": 8 }' });
expect(loadConfig(root).values["max-turns"]).toBe("8");
});
it("collects a repeatable setting into a list", () => {
const root = fixture({
"airship.config.json": '{ "codexConfig": ["a=1", "b=2"] }',
});
expect(loadConfig(root).values["codex-config"]).toEqual(["a=1", "b=2"]);
});
it("rejects an unknown key rather than ignoring it", () => {
const root = fixture({ "airship.config.json": '{ "targt": 3000 }' });
expect(() => loadConfig(root)).toThrow(CliError);
expect(hintOf(() => loadConfig(root))).toBe("Did you mean target?");
});
it("rejects a non-boolean for a boolean setting", () => {
const root = fixture({ "airship.config.json": '{ "safe": "yes" }' });
expect(() => loadConfig(root)).toThrow(CliError);
});
it("reports malformed JSON rather than falling through", () => {
const root = fixture({ "airship.config.json": "{ nope" });
expect(() => loadConfig(root)).toThrow(CliError);
});
it("returns nothing when there is no config anywhere", () => {
const root = fixture({ ".git/HEAD": "ref: refs/heads/main\n" });
expect(loadConfig(root)).toEqual({ values: {} });
});
});
describe("envSettings", () => {
it("maps AIRSHIP_* onto flag names", () => {
expect(
envSettings({ AIRSHIP_MAX_TURNS: "8", AIRSHIP_TARGET: "3000" })
).toEqual({ "max-turns": "8", target: "3000" });
});
it.each(["1", "true", "yes", "on"])("reads %o as true", (value) => {
expect(envSettings({ AIRSHIP_SAFE: value }).safe).toBe(true);
});
it.each(["0", "false", "no", "off", ""])("reads %o as false", (value) => {
expect(envSettings({ AIRSHIP_SAFE: value }).safe).toBe(false);
});
it("rejects a boolean it cannot read rather than defaulting to true", () => {
expect(() => envSettings({ AIRSHIP_SAFE: "maybe" })).toThrow(CliError);
});
// A shell profile that exported these would make the CLI unable to run.
it("ignores AIRSHIP_HELP and AIRSHIP_VERSION", () => {
expect(envSettings({ AIRSHIP_HELP: "1", AIRSHIP_VERSION: "1" })).toEqual(
{}
);
});
it("leaves unset variables out entirely", () => {
expect(envSettings({})).toEqual({});
});
});
describe("mergeSettings", () => {
it("lets the later source win", () => {
expect(
mergeSettings({ target: "1" }, { target: "2" }, { target: "3" }).target
).toBe("3");
});
// The whole point of the chain: an unset flag has to fall through, not
// overwrite the config file with nothing.
it("never lets undefined overwrite a real value", () => {
expect(
mergeSettings({ target: "3000" }, { target: undefined }).target
).toBe("3000");
});
it("keeps keys that only one source has", () => {
expect(mergeSettings({ agent: "codex" }, { target: "3000" })).toEqual({
agent: "codex",
target: "3000",
});
});
});
describe("accessors", () => {
it("treats an empty string as absent", () => {
expect(asString({ model: "" }, "model")).toBeUndefined();
});
it("reads only an exact true as true", () => {
expect(asBoolean({ safe: true }, "safe")).toBe(true);
expect(asBoolean({ safe: "true" }, "safe")).toBe(false);
});
it("wraps a lone string as a list", () => {
expect(asList({ "codex-config": "a=1" }, "codex-config")).toEqual(["a=1"]);
});
});
+224
View File
@@ -0,0 +1,224 @@
/**
* Settings resolution: flags > AIRSHIP_* env > config file > defaults.
*
* Before this, every setting was a flag, so a project that always runs on the
* same port with the same agent retyped both on every launch. The precedence is
* the conventional one — the more specific and more deliberate the source, the
* higher it wins, with the command line always last word.
*
* Everything is normalised to the registry's flag names (kebab-case) so the
* three sources merge as plain objects and the rest of the CLI only ever reads
* one shape.
*/
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { FLAGS, type FlagSpec } from "./args";
import { CliError, didYouMean } from "./errors";
export type SettingValue = string | string[] | boolean;
export type Settings = Record<string, SettingValue | undefined>;
export const CONFIG_FILENAME = "airship.config.json";
/** The `airship` key in a package.json, for projects that prefer one file. */
const PACKAGE_KEY = "airship";
export interface LoadedConfig {
/** Absolute path of the file the values came from, when there was one. */
source?: string;
values: Settings;
}
/** `max-turns` ⇄ `maxTurns` — accept either spelling, store the flag's. */
function toFlagName(key: string): string {
return key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
}
function envKey(spec: FlagSpec): string {
return `AIRSHIP_${spec.name.replace(/-/g, "_").toUpperCase()}`;
}
const TRUTHY = new Set(["1", "true", "yes", "on"]);
const FALSY = new Set(["0", "false", "no", "off", ""]);
/**
* Env vars are strings, so a boolean flag needs a spelling convention. Anything
* unrecognised is an error rather than a silent `true`: `AIRSHIP_SAFE=maybe`
* quietly enabling the sandbox is worse than being told it is not a boolean.
*/
function envBoolean(raw: string, name: string): boolean {
const value = raw.trim().toLowerCase();
if (TRUTHY.has(value)) {
return true;
}
if (FALSY.has(value)) {
return false;
}
throw new CliError(`${name} is not a boolean: '${raw}'`, {
hint: "Use 1/true/yes/on or 0/false/no/off.",
});
}
/** Settings from `AIRSHIP_*`, derived from the registry so none can be missed. */
export function envSettings(env: NodeJS.ProcessEnv = process.env): Settings {
const out: Settings = {};
for (const spec of FLAGS) {
// Reading AIRSHIP_HELP or AIRSHIP_VERSION from the environment would make a
// shell profile permanently unable to run anything.
if (spec.name === "help" || spec.name === "version") {
continue;
}
const key = envKey(spec);
const raw = env[key];
if (raw === undefined) {
continue;
}
out[spec.name] = spec.type === "boolean" ? envBoolean(raw, key) : raw;
}
return out;
}
function coerceFileValue(
spec: FlagSpec,
value: unknown,
where: string
): SettingValue {
if (spec.multiple) {
const list = Array.isArray(value) ? value : [value];
return list.map((item) => String(item));
}
if (spec.type === "boolean") {
if (typeof value !== "boolean") {
throw new CliError(`${where}: "${spec.name}" must be true or false`, {
hint: `Got ${JSON.stringify(value)}.`,
});
}
return value;
}
if (typeof value === "string" || typeof value === "number") {
// Ports and turn counts read naturally as JSON numbers; the validators
// downstream all take strings, so normalise here rather than everywhere.
return String(value);
}
throw new CliError(`${where}: "${spec.name}" must be a string`, {
hint: `Got ${JSON.stringify(value)}.`,
});
}
function parseConfigObject(raw: unknown, where: string): Settings {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new CliError(`${where} must contain a JSON object`, {
hint: `Expected something like { "target": 3000, "agent": "claude" }.`,
});
}
const byName = new Map(FLAGS.map((flag) => [flag.name, flag]));
const out: Settings = {};
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
const name = toFlagName(key);
const spec = byName.get(name);
if (!spec) {
// Same reasoning as an unknown flag: a typo'd key that is silently
// ignored looks exactly like a setting that does not work.
throw new CliError(`${where}: unknown setting "${key}"`, {
hint:
didYouMean(
name,
FLAGS.map((flag) => flag.name),
""
) ?? "See `airship --help` for the settings a config file accepts.",
});
}
out[name] = coerceFileValue(spec, value, where);
}
return out;
}
/**
* Walk up from `cwd` looking for a config file.
*
* Stops at the repository root: a config found above it belongs to a different
* project (or to the user's home directory) and would silently change how an
* unrelated app is served.
*/
export function loadConfig(cwd: string): LoadedConfig {
let dir = resolve(cwd);
for (;;) {
const configPath = join(dir, CONFIG_FILENAME);
if (existsSync(configPath)) {
return {
source: configPath,
values: parseConfigObject(readJson(configPath), CONFIG_FILENAME),
};
}
const pkgPath = join(dir, "package.json");
if (existsSync(pkgPath)) {
const pkg = readJson(pkgPath) as Record<string, unknown> | null;
const section = pkg?.[PACKAGE_KEY];
if (section !== undefined) {
return {
source: pkgPath,
values: parseConfigObject(section, `package.json "${PACKAGE_KEY}"`),
};
}
}
if (existsSync(join(dir, ".git"))) {
return { values: {} };
}
const parent = dirname(dir);
if (parent === dir) {
return { values: {} };
}
dir = parent;
}
}
function readJson(path: string): unknown {
try {
return JSON.parse(readFileSync(path, "utf8"));
} catch (err) {
throw new CliError(
`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
{
cause: err,
hint: "Fix the file, or delete it to fall back to flags.",
}
);
}
}
/**
* Merge the sources, highest precedence last.
*
* `undefined` never overwrites: an unset flag has to fall through to the env or
* the file, which is the whole point of having them.
*/
export function mergeSettings(...sources: readonly Settings[]): Settings {
const out: Settings = {};
for (const source of sources) {
for (const [key, value] of Object.entries(source)) {
if (value !== undefined) {
out[key] = value;
}
}
}
return out;
}
export function asString(settings: Settings, name: string): string | undefined {
const value = settings[name];
return typeof value === "string" && value !== "" ? value : undefined;
}
export function asBoolean(settings: Settings, name: string): boolean {
return settings[name] === true;
}
export function asList(settings: Settings, name: string): string[] {
const value = settings[name];
if (Array.isArray(value)) {
return value;
}
return typeof value === "string" ? [value] : [];
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Turning one invocation into the merged settings a command runs on.
*
* Shared by every command so the precedence chain is applied identically —
* `doctor` reporting different values from the ones `serve` would use would
* make it worse than useless.
*/
import { resolve } from "node:path";
import { collectRepeated, specsFor } from "./args";
import {
envSettings,
loadConfig,
mergeSettings,
type Settings,
} from "./config";
import { CliError, EXIT } from "./errors";
export interface ResolvedContext {
/** The config file the values came from, for `doctor` and error messages. */
configSource?: string;
/** Project root for edits, absolute. */
cwd: string;
settings: Settings;
}
/**
* Pull this command's flags out of citty's parsed args.
*
* citty rewrites a string flag given without a value to `""` rather than
* failing, which would read here as "not set" and silently fall through to the
* config file — so an empty string is rejected outright.
*/
function flagSettings(
args: Record<string, unknown>,
rawArgs: readonly string[],
names: readonly string[]
): Settings {
const out: Settings = {};
for (const spec of specsFor(names)) {
if (spec.multiple) {
const values = collectRepeated(rawArgs, spec.name);
if (values.length > 0) {
out[spec.name] = values;
}
continue;
}
const value = args[spec.name];
if (value === undefined) {
continue;
}
if (spec.type === "boolean") {
out[spec.name] = value === true;
continue;
}
if (typeof value !== "string" || value === "") {
throw new CliError(`--${spec.name} needs a value`, {
exitCode: EXIT.usage,
hint: `Pass it as --${spec.name} ${spec.hint ?? "<value>"}.`,
});
}
out[spec.name] = value;
}
return out;
}
export function resolveSettings(opts: {
args: Record<string, unknown>;
names: readonly string[];
rawArgs: readonly string[];
}): ResolvedContext {
const flags = flagSettings(opts.args, opts.rawArgs, opts.names);
const env = envSettings();
// Config discovery starts from --cwd when one was given, so running
// `airship --cwd apps/web` from a repo root finds that app's config rather
// than the root's. Only the two sources that can be known before the file is
// read may steer it, which is why this is a separate merge.
const searchRoot = flags.cwd ?? env.cwd;
const config = loadConfig(
typeof searchRoot === "string" ? resolve(searchRoot) : process.cwd()
);
const settings = mergeSettings(config.values, env, flags);
const { cwd } = settings;
return {
configSource: config.source,
cwd: typeof cwd === "string" ? resolve(cwd) : process.cwd(),
settings,
};
}
+139
View File
@@ -0,0 +1,139 @@
/**
* The interactive launcher, and the prompts `init` reuses.
*
* Running `airship` bare used to print the whole help and exit 1 — a wall of
* text as the answer to "what do I do". At a real terminal it now asks the three
* questions that matter and launches.
*
* Every prompt is gated on a TTY at both ends by the caller. In a pipe or a CI
* job there is nobody to answer, and a prompt there does not fail — it hangs,
* which is the worst failure a CLI has.
*/
import { type AgentKind, checkAuth } from "@airship/server";
import {
cancel,
confirm,
intro,
isCancel,
outro,
select,
spinner,
text,
} from "@clack/prompts";
import { AGENTS, type MODES } from "./args";
import { detectTarget } from "./detect";
import { CliError, EXIT } from "./errors";
import { style } from "./terminal";
export interface WizardAnswers {
agent: AgentKind;
mode: (typeof MODES)[number];
safe: boolean;
target: number;
}
/** Clack returns a symbol when the user hits Ctrl-C; treat it as an exit. */
function unwrap<T>(value: T | symbol): T {
if (isCancel(value)) {
cancel("Cancelled.");
process.exit(EXIT.interrupted);
}
return value;
}
const MAX_PORT = 65_535;
function validatePort(value: string | undefined): string | undefined {
const port = Number(value);
if (!Number.isInteger(port) || port < 1 || port > MAX_PORT) {
return `A port is a whole number from 1 to ${MAX_PORT}.`;
}
}
/**
* Label each agent with whether it is actually usable.
*
* Offering a backend the user has not signed into, and only saying so after
* they pick it and the launch fails, is the mistake this exists to avoid.
*/
async function agentOptions(): Promise<
{ hint: string; label: string; value: AgentKind }[]
> {
return await Promise.all(
AGENTS.map(async (agent) => {
const auth = await checkAuth(agent as AgentKind);
return {
hint: auth.ok ? "ready" : "not available",
label: agent,
value: agent as AgentKind,
};
})
);
}
export async function runWizard(cwd: string): Promise<WizardAnswers> {
intro(style.magenta("◆ airship"));
const probe = spinner();
probe.start("Looking for your dev server");
const detected = await detectTarget(cwd);
const agents = await agentOptions();
probe.stop(
detected?.listening
? `Found a dev server on port ${detected.port}`
: "No dev server running yet"
);
const target = unwrap(
await text({
defaultValue: detected ? String(detected.port) : undefined,
message: "Which port is your dev server on?",
placeholder: detected ? `${detected.port} — ${detected.reason}` : "3000",
validate: validatePort,
})
);
const agent = unwrap(
await select({
message: "Which agent should make the edits?",
options: agents,
})
);
const mode = unwrap(
await select({
message: "Which surface?",
options: [
{
hint: "one live frame per device size",
label: "canvas",
value: "canvas" as const,
},
{
hint: "the editor inside your own page",
label: "inline",
value: "inline" as const,
},
],
})
);
const safe = unwrap(
await confirm({
initialValue: false,
message: "Confine the agent to this project and cut network access?",
})
);
outro(style.dim("Starting…"));
return { agent, mode, safe, target: Number(target) };
}
/** The message a non-interactive bare invocation gets instead of a prompt. */
export function noTtyError(): CliError {
return new CliError("No dev server specified", {
exitCode: EXIT.usage,
hint: "Pass --target <port>, or run airship at a terminal to be asked.",
});
}