diff --git a/apps/cli/src/commands/init.ts b/apps/cli/src/commands/init.ts index b69ab40..1519253 100644 --- a/apps/cli/src/commands/init.ts +++ b/apps/cli/src/commands/init.ts @@ -12,7 +12,8 @@ import { join, relative } from "node:path"; import { confirm, isCancel } from "@clack/prompts"; import { defineCommand } from "citty"; import { argsFor, assertKnownFlags, GLOBAL_FLAGS } from "../lib/args"; -import { asBoolean, CONFIG_FILENAME } from "../lib/config"; +import { readOpencodeConfig } from "../lib/backends"; +import { asBoolean, asString, CONFIG_FILENAME } from "../lib/config"; import { CliError, EXIT } from "../lib/errors"; import { resolveSettings } from "../lib/settings"; import { @@ -24,7 +25,23 @@ import { } from "../lib/terminal"; import { runWizard } from "../lib/wizard"; -export const INIT_FLAGS: readonly string[] = ["cwd", ...GLOBAL_FLAGS]; +/* + * The opencode knobs are here because `init` probes for models, and probing + * opencode *starts a server* — at `--opencode-path`, or against a running one at + * `--opencode-url`, with `--opencode-config` applied. Without them the wizard + * booted a default server the project may not use and then reported it as + * unreachable, with no flag available to say otherwise. + * + * `--safe` for the same reason: it changes what the probe is allowed to do. + */ +export const INIT_FLAGS: readonly string[] = [ + "cwd", + "safe", + "opencode-path", + "opencode-url", + "opencode-config", + ...GLOBAL_FLAGS, +]; export const init = defineCommand({ args: argsFor(INIT_FLAGS), @@ -61,7 +78,17 @@ export const init = defineCommand({ } } - const answers = await runWizard(cwd); + const answers = await runWizard(cwd, { + askModel: true, + probe: { + opencode: { + config: readOpencodeConfig(asString(settings, "opencode-config")), + opencodePath: asString(settings, "opencode-path"), + url: asString(settings, "opencode-url"), + }, + safe: asBoolean(settings, "safe"), + }, + }); // Only the answers worth persisting. `safe: false` is the default, so // writing it would state a posture the user did not actually choose. const config: Record = { @@ -72,6 +99,14 @@ export const init = defineCommand({ if (answers.safe) { config.safe = true; } + // Keyed to the backend it was chosen for, never the bare `model`. The + // overlay's picker can move to another harness mid-session, and a flat + // `model` would follow it there and hand Codex an id only Claude answers to. + // Same rule as `safe` above: absent means "the backend decides", so an + // unanswered prompt writes nothing. + if (answers.model) { + config[`${answers.agent}Model`] = answers.model; + } writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`); note( diff --git a/apps/cli/src/commands/serve.test.ts b/apps/cli/src/commands/serve.test.ts new file mode 100644 index 0000000..2761f6e --- /dev/null +++ b/apps/cli/src/commands/serve.test.ts @@ -0,0 +1,128 @@ +/** + * `toServeOptions` — where merged settings become validated options. + * + * The function has carried "Exported for the tests" since it was split out of + * `main`, and until now there were none: nothing in the repo imported it. That + * was survivable while it only read strings across; it stopped being so once it + * grew the per-backend model fallback, which is real logic with three inputs + * and a precedence order, and which no other layer re-checks. + */ + +import { describe, expect, it } from "vitest"; +import { mergeSettings, type Settings } from "../lib/config"; +import { CliError } from "../lib/errors"; +import { toServeOptions } from "./serve"; + +const CWD = "/tmp/airship-serve-test"; + +/** Settings as the merge chain would hand them over. */ +function settings(values: Record): Settings { + return mergeSettings(values as Settings); +} + +function optionsFor(values: Record) { + return toServeOptions(settings(values), CWD); +} + +/** The message on the CliError a call raises. */ +function errorFrom(fn: () => unknown): CliError | undefined { + try { + fn(); + } catch (err) { + if (err instanceof CliError) { + return err; + } + throw err; + } +} + +describe("toServeOptions — models", () => { + it("leaves every backend unset when no model flag is given", () => { + const { model, models } = optionsFor({}); + expect(model).toBeUndefined(); + // Not `{}`: the keys exist and hold `undefined`, which is what the server + // reads as "this backend has no configured default". + expect(models.claude).toBeUndefined(); + expect(models.codex).toBeUndefined(); + expect(models.opencode).toBeUndefined(); + }); + + it("spreads a bare --model to all three backends", () => { + const { models } = optionsFor({ model: "sonnet" }); + expect(models).toEqual({ + claude: "sonnet", + codex: "sonnet", + opencode: "sonnet", + }); + }); + + it("lets a per-backend model outrank --model, for that backend only", () => { + const { models } = optionsFor({ "claude-model": "opus", model: "sonnet" }); + expect(models.claude).toBe("opus"); + // The whole point of the split: switching the picker to Codex must not + // carry Claude's id across. + expect(models.codex).toBe("sonnet"); + expect(models.opencode).toBe("sonnet"); + }); + + it("takes all three per-backend models independently", () => { + const { models } = optionsFor({ + "claude-model": "opus", + "codex-model": "gpt-5.3-codex", + "opencode-model": "anthropic/claude-sonnet-5", + }); + expect(models).toEqual({ + claude: "opus", + codex: "gpt-5.3-codex", + opencode: "anthropic/claude-sonnet-5", + }); + }); + + it("keeps --model on `model` as well, for the launch banner", () => { + // `model` is not superseded by `models` — the banner reads it, and dropping + // it would break a surface that has nothing to do with the picker. + expect(optionsFor({ model: "sonnet" }).model).toBe("sonnet"); + expect(optionsFor({ "claude-model": "opus" }).model).toBeUndefined(); + }); + + it("rejects an --opencode-model with no provider", () => { + const err = errorFrom(() => optionsFor({ "opencode-model": "sonnet" })); + expect(err?.message).toContain("opencode-model"); + // The hint has to show the shape, not just name it: the fix is invisible + // otherwise, since the id itself is perfectly valid for another backend. + expect(err?.hint).toContain("anthropic/sonnet"); + }); + + it("accepts an --opencode-model that names its provider", () => { + expect( + optionsFor({ "opencode-model": "anthropic/x" }).models.opencode + ).toBe("anthropic/x"); + }); + + it("does not validate a bare --model, which reaches all three", () => { + // A bare id is correct for two of the three backends, so this cannot be an + // error. `banner.ts` warns at launch instead, once the agent is known. + expect(optionsFor({ model: "sonnet" }).models.opencode).toBe("sonnet"); + }); +}); + +describe("toServeOptions — the surrounding validation still holds", () => { + it("defaults the agent and rejects an unknown one", () => { + expect(optionsFor({}).agent).toBe("claude"); + expect(errorFrom(() => optionsFor({ agent: "gemini" }))?.message).toContain( + "agent" + ); + }); + + it("rejects a port outside the range", () => { + expect(errorFrom(() => optionsFor({ port: "70000" }))?.message).toContain( + "port" + ); + }); + + it("rejects a non-numeric budget", () => { + expect( + errorFrom(() => optionsFor({ "max-budget": "lots" }))?.message + ).toContain("max-budget"); + }); +}); diff --git a/apps/cli/src/commands/serve.ts b/apps/cli/src/commands/serve.ts index c418742..dc81a65 100644 --- a/apps/cli/src/commands/serve.ts +++ b/apps/cli/src/commands/serve.ts @@ -24,6 +24,7 @@ import { requireAmount, requireEnum, requireInteger, + requireModelRef, requirePort, } from "../lib/args"; import { parseCodexConfig, readOpencodeConfig } from "../lib/backends"; @@ -54,6 +55,9 @@ export const SERVE_FLAGS: readonly string[] = [ "max-budget", "commit", "safe", + "claude-model", + "codex-model", + "opencode-model", "codex-path", "codex-config", "opencode-path", @@ -74,6 +78,8 @@ export interface ServeOptions { maxBudgetUsd?: number; maxTurns?: number; model?: string; + /** Per-backend model defaults, each already falling back to `model`. */ + models: Partial>; open: boolean; opencode: OpencodeSettings; port?: number; @@ -98,6 +104,8 @@ export function toServeOptions(settings: Settings, cwd: string): ServeOptions { const turns = asString(settings, "max-turns"); const budget = asString(settings, "max-budget"); const codexConfig = parseCodexConfig(asList(settings, "codex-config")); + const model = asString(settings, "model"); + const opencodeModel = asString(settings, "opencode-model"); return { agent: (agent ? requireEnum(agent, "agent") : "claude") as AgentKind, @@ -112,7 +120,18 @@ export function toServeOptions(settings: Settings, cwd: string): ServeOptions { json: asBoolean(settings, "json"), maxBudgetUsd: budget ? requireAmount(budget, "max-budget") : undefined, maxTurns: turns ? requireInteger(turns, "max-turns") : undefined, - model: asString(settings, "model"), + model, + // The fallback collapses here rather than in the server so there is one + // place that decides it, and one place the tests have to cover. Only the + // opencode entry is validated: that flag names its backend, so a bare id + // is unambiguously wrong. `model` reaches all three and cannot be. + models: { + claude: asString(settings, "claude-model") ?? model, + codex: asString(settings, "codex-model") ?? model, + opencode: opencodeModel + ? requireModelRef(opencodeModel, "opencode-model") + : model, + }, open: asBoolean(settings, "open"), opencode: { agent: asString(settings, "opencode-agent"), @@ -262,7 +281,10 @@ export const serve = defineCommand({ effort: opts.effort, maxBudgetUsd: opts.maxBudgetUsd, maxTurns: opts.maxTurns, - model: opts.model, + // The resolved per-backend map, not the raw `--model`. The opencode + // warning reads `models.opencode`, so passing only `model` left it reading + // `undefined` and the warning could never fire. + models: opts.models, }); let dev: DevServer | undefined; @@ -286,6 +308,7 @@ export const serve = defineCommand({ maxBudgetUsd: opts.maxBudgetUsd, maxTurns: opts.maxTurns, model: opts.model, + models: opts.models, opencode: opts.opencode, port, safe: opts.safe, @@ -306,6 +329,10 @@ export const serve = defineCommand({ agent: opts.agent, cwd: opts.cwd, mode: opts.surface, + // The resolved model for the backend that will run, so a scripted + // caller can read back which of the four model flags won rather + // than re-deriving the precedence itself. + model: opts.models?.[opts.agent], port, safe: opts.safe, targetPort, @@ -320,6 +347,7 @@ export const serve = defineCommand({ launchBanner({ agent: opts.agent, cwd: opts.cwd, + model: opts.models?.[opts.agent], safe: opts.safe, surface: opts.surface, targetPort, diff --git a/apps/cli/src/lib/args.test.ts b/apps/cli/src/lib/args.test.ts index 4edba85..1405960 100644 --- a/apps/cli/src/lib/args.test.ts +++ b/apps/cli/src/lib/args.test.ts @@ -5,6 +5,7 @@ import { requireAmount, requireEnum, requireInteger, + requireModelRef, requirePort, } from "./args"; import { CliError, closest, EXIT } from "./errors"; @@ -148,6 +149,29 @@ describe("requireEnum", () => { }); }); +describe("requireModelRef", () => { + it("passes a provider/model reference through", () => { + expect(requireModelRef("anthropic/claude-sonnet-5", "opencode-model")).toBe( + "anthropic/claude-sonnet-5" + ); + }); + + // opencode drops an id it cannot attribute to a provider, so a bare one is + // not "close enough" — it means the turn silently runs on something else. + it.each(["sonnet", "", "/sonnet", "anthropic/", "anthropic//x"])( + "rejects %o", + (value) => { + expect(() => requireModelRef(value, "opencode-model")).toThrow(CliError); + } + ); + + it("shows the shape rather than only naming it", () => { + expect( + thrown(() => requireModelRef("sonnet", "opencode-model")).hint + ).toContain("anthropic/sonnet"); + }); +}); + describe("requirePort", () => { it("accepts a port in range", () => { expect(requirePort("3000", "target")).toBe(3000); diff --git a/apps/cli/src/lib/args.ts b/apps/cli/src/lib/args.ts index 310825b..aa9f37d 100644 --- a/apps/cli/src/lib/args.ts +++ b/apps/cli/src/lib/args.ts @@ -126,7 +126,7 @@ export const FLAGS: readonly FlagSpec[] = [ alias: "m", defaultHint: "the agent's own default", group: "AGENT", - help: "Model id.", + help: "Model id for whichever agent runs. Per-backend flags outrank it.", hint: "", name: "model", type: "string", @@ -167,6 +167,30 @@ export const FLAGS: readonly FlagSpec[] = [ name: "safe", type: "boolean", }, + { + defaultHint: "--model, then the agent's own", + group: "BACKEND", + help: "Model for the claude backend. Takes an alias or a full id.", + hint: "", + name: "claude-model", + type: "string", + }, + { + defaultHint: "--model, then the agent's own", + group: "BACKEND", + help: "Model for the codex backend.", + hint: "", + name: "codex-model", + type: "string", + }, + { + defaultHint: "--model, then the agent's own", + group: "BACKEND", + help: "Model for the opencode backend. Needs the provider/model form.", + hint: "", + name: "opencode-model", + type: "string", + }, { defaultHint: "bundled", group: "BACKEND", @@ -410,6 +434,30 @@ export function requireEnum(value: string, name: string): string { }); } +/** + * An opencode model reference, which must name its provider. + * + * `modelRefFor` splits on the first slash and drops an id it cannot attribute, + * so `--opencode-model sonnet` would be silently ignored and the turn would run + * on the server's default — the user having explicitly asked for something else. + * + * A hard error is right *here* and wrong for `--model`, and the difference is + * which backend the flag is aimed at. This one names opencode, so a bare id can + * only be a mistake. `--model` applies to whichever agent the picker lands on, + * where a bare id is correct for two of the three, so that one keeps the launch + * warning in `banner.ts` instead. + */ +export function requireModelRef(value: string, name: string): string { + const [provider, ...rest] = value.split("/"); + if (provider && rest.length > 0 && rest.every(Boolean)) { + return value; + } + throw new CliError(`Invalid --${name} '${value}'`, { + exitCode: EXIT.usage, + hint: `opencode resolves a model through its provider, so it needs the provider/model form — try 'anthropic/${value}' or run \`opencode models\` to list what you have configured.`, + }); +} + const MAX_PORT = 65_535; export function requirePort(value: string, name: string): number { diff --git a/apps/cli/src/lib/banner.test.ts b/apps/cli/src/lib/banner.test.ts new file mode 100644 index 0000000..e5e0d83 --- /dev/null +++ b/apps/cli/src/lib/banner.test.ts @@ -0,0 +1,177 @@ +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { warnBackendLimits } from "./banner"; +import { setColorEnabled } from "./terminal"; + +/* + * The launch warnings, which are the only thing standing between a user and a + * flag that is being silently dropped. + * + * This file exists because there was no `banner.test.ts` when `warnBackendLimits` + * was switched from reading `--model` to reading the resolved per-backend map. + * Its one caller was never updated to pass that map, so the opencode warning read + * `undefined` forever and could not fire — and `airship --agent opencode --model + * sonnet`, which opencode cannot resolve and drops on the floor, launched clean. + * Nothing failed, because nothing was looking. + * + * `cwd` is this repo throughout, so the unrelated "not a git repository" warning + * never fires and each case asserts on the one line it is about. + */ + +const REPO = process.cwd(); + +/** Everything written to stderr while `run` executes. */ +function stderrFrom(run: () => void): string { + let out = ""; + const spy = vi + .spyOn(process.stderr, "write") + .mockImplementation((chunk: string | Uint8Array) => { + out += String(chunk); + return true; + }); + try { + run(); + } finally { + spy.mockRestore(); + } + return out; +} + +describe("warnBackendLimits", () => { + beforeAll(() => { + // Assertions match on characters, not on ANSI. + setColorEnabled(false); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("a bare model id on opencode", () => { + it("warns, naming the id and the form it needed", () => { + const out = stderrFrom(() => + warnBackendLimits({ + agent: "opencode", + cwd: REPO, + models: { opencode: "sonnet" }, + }) + ); + + expect(out).toContain("sonnet"); + expect(out).toContain("provider/model"); + // The suggestion has to be actionable, not just a complaint. + expect(out).toContain("anthropic/sonnet"); + }); + + it("stays quiet once the id names its provider", () => { + const out = stderrFrom(() => + warnBackendLimits({ + agent: "opencode", + cwd: REPO, + models: { opencode: "anthropic/claude-sonnet-5" }, + }) + ); + + expect(out).toBe(""); + }); + + it("stays quiet on the backends that take a bare id", () => { + for (const agent of ["claude", "codex"] as const) { + const out = stderrFrom(() => + warnBackendLimits({ + agent, + cwd: REPO, + models: { [agent]: "sonnet" }, + }) + ); + + expect(out).toBe(""); + } + }); + + it("reads the entry for the running backend, not another one", () => { + // The map always carries all three, because `--model` fills every entry + // it does not override. Warning off claude's copy while codex runs would + // fire on every `airship --agent codex --model sonnet`. + const out = stderrFrom(() => + warnBackendLimits({ + agent: "codex", + cwd: REPO, + models: { + claude: "sonnet", + codex: "gpt-5.3-codex", + opencode: "sonnet", + }, + }) + ); + + expect(out).toBe(""); + }); + }); + + describe("claude-only knobs", () => { + it("warns that --max-budget is dropped elsewhere", () => { + const out = stderrFrom(() => + warnBackendLimits({ agent: "codex", cwd: REPO, maxBudgetUsd: 5 }) + ); + + expect(out).toContain("--max-budget"); + }); + + it("warns that --max-turns is dropped elsewhere", () => { + const out = stderrFrom(() => + warnBackendLimits({ agent: "opencode", cwd: REPO, maxTurns: 24 }) + ); + + expect(out).toContain("--max-turns"); + }); + + it("keeps both for claude itself", () => { + const out = stderrFrom(() => + warnBackendLimits({ + agent: "claude", + cwd: REPO, + maxBudgetUsd: 5, + maxTurns: 24, + }) + ); + + expect(out).toBe(""); + }); + }); + + describe("--effort", () => { + it("warns that opencode has no reasoning-effort control", () => { + const out = stderrFrom(() => + warnBackendLimits({ agent: "opencode", cwd: REPO, effort: "high" }) + ); + + expect(out).toContain("--effort"); + expect(out).toContain("--opencode-config"); + }); + + it("stays quiet for the two backends that honour it", () => { + for (const agent of ["claude", "codex"] as const) { + const out = stderrFrom(() => + warnBackendLimits({ agent, cwd: REPO, effort: "high" }) + ); + + expect(out).toBe(""); + } + }); + }); + + it("says nothing at all when every flag is one the backend honours", () => { + const out = stderrFrom(() => + warnBackendLimits({ + agent: "claude", + cwd: REPO, + effort: "high", + maxBudgetUsd: 5, + maxTurns: 24, + models: { claude: "opus" }, + }) + ); + + expect(out).toBe(""); + }); +}); diff --git a/apps/cli/src/lib/banner.ts b/apps/cli/src/lib/banner.ts index 82d9836..1401edc 100644 --- a/apps/cli/src/lib/banner.ts +++ b/apps/cli/src/lib/banner.ts @@ -36,7 +36,9 @@ export function warnBackendLimits(o: { effort?: string; maxBudgetUsd?: number; maxTurns?: number; - model?: string; + /** The *resolved* per-backend models, as `serve.ts` collapses them. Not the + * raw `--model`: what a turn will actually send is what is worth warning on. */ + models?: Partial>; }): void { const warn = (message: string): void => { process.stderr.write(`\n ${style.yellow(`⚠ ${message}`)}\n`); @@ -67,9 +69,16 @@ export function warnBackendLimits(o: { } // 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("/")) { + // + // Read off the *resolved* per-backend value, not `--model`: that is what a + // turn will actually send. It also makes this unreachable via + // `--opencode-model`, which `requireModelRef` already rejects outright — a + // flag that names its backend can be a hard error, and only the catch-all + // `--model` is left needing a warning. + const opencodeModel = o.models?.opencode; + if (o.agent === "opencode" && opencodeModel && !opencodeModel.includes("/")) { warn( - `--model '${o.model}' is ignored with --agent opencode: it wants the provider/model form (e.g. anthropic/${o.model}).` + `--model '${opencodeModel}' is ignored with --agent opencode: it wants the provider/model form (e.g. anthropic/${opencodeModel}).\n Set --opencode-model to give opencode its own.` ); } } @@ -91,13 +100,21 @@ function surfaceLines(surface: AirshipSurface): string { export function launchBanner(info: { agent: AgentKind; cwd: string; + /** The resolved model for `agent`, when one was configured. */ + model?: string; safe: boolean; surface: AirshipSurface; targetPort: number; url: string; }): string { + // Four flags can name a model — `--model`, the three per-backend ones — and + // they resolve in an order. Without this the only way to learn which one won + // was to run a turn and read the transcript. Omitted rather than guessed when + // nothing was configured: the backend picks in that case, and naming a default + // airship did not choose would be a claim it cannot make. + const on = info.model ? ` on ${info.model}` : ""; return ( - `\n ${style.magenta("◆")} ${style.bold("airship")} — editing ${info.cwd} with ${info.agent}\n` + + `\n ${style.magenta("◆")} ${style.bold("airship")} — editing ${info.cwd} with ${info.agent}${on}\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 diff --git a/apps/cli/src/lib/config.test.ts b/apps/cli/src/lib/config.test.ts index 5cb196c..13ae4b9 100644 --- a/apps/cli/src/lib/config.test.ts +++ b/apps/cli/src/lib/config.test.ts @@ -104,6 +104,33 @@ describe("loadConfig", () => { expect(hintOf(() => loadConfig(root))).toBe("Did you mean target?"); }); + // The per-backend model keys are not declared anywhere in this module: they + // exist in `airship.config.json` only because they are flags, and the schema + // is the flag registry. These three assert that pipe end to end, which is + // also what makes `airship init` writing `claudeModel` safe. + it.each([ + ["claudeModel", "claude-model"], + ["codexModel", "codex-model"], + ["opencodeModel", "opencode-model"], + ])("reads %s as %s", (written, flag) => { + const root = fixture({ + "airship.config.json": `{ "${written}": "some-model" }`, + }); + expect(loadConfig(root).values[flag]).toBe("some-model"); + }); + + it("accepts the kebab spelling of a per-backend model too", () => { + const root = fixture({ + "airship.config.json": '{ "claude-model": "opus" }', + }); + expect(loadConfig(root).values["claude-model"]).toBe("opus"); + }); + + it("suggests the near miss on a mistyped model key", () => { + const root = fixture({ "airship.config.json": '{ "claudModel": "opus" }' }); + expect(hintOf(() => loadConfig(root))).toBe("Did you mean claude-model?"); + }); + it("rejects a non-boolean for a boolean setting", () => { const root = fixture({ "airship.config.json": '{ "safe": "yes" }' }); expect(() => loadConfig(root)).toThrow(CliError); diff --git a/apps/cli/src/lib/wizard.ts b/apps/cli/src/lib/wizard.ts index 1d57034..940b66f 100644 --- a/apps/cli/src/lib/wizard.ts +++ b/apps/cli/src/lib/wizard.ts @@ -2,15 +2,24 @@ * 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 + * text as the answer to "what do I do". At a real terminal it now asks the few * questions that matter and launches. * + * What counts as "matters" differs by caller, which is what `WizardOptions` is + * for: a bare launch settles only what it needs to start, while `init` is + * writing a file meant to outlive the session and can afford to ask more. + * * 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 { + type AgentKind, + checkAuth, + listModels, + type ModelProbeOptions, +} from "@airship/server"; import { cancel, confirm, @@ -29,10 +38,35 @@ import { style } from "./terminal"; export interface WizardAnswers { agent: AgentKind; mode: (typeof MODES)[number]; + /** Absent means "whatever that backend picks", which is the common answer. */ + model?: string; safe: boolean; target: number; } +export interface WizardOptions { + /** + * Ask which model, after the agent is chosen. + * + * Off by default, and the default is the point: a bare `airship` already asks + * four questions before it launches, and a fifth paid on every start to + * settle something most runs are happy to leave alone is a bad trade. + * `airship init` turns it on, because that call is writing a file whose whole + * purpose is to stop the flags being retyped. + */ + askModel?: boolean; + /** + * Passed through to the model probe. + * + * The opencode probe *starts a server* — at `--opencode-path`, or against a + * running one at `--opencode-url`, with `--opencode-config` applied. Called + * without these it ignored every one of them, so a project that reaches + * opencode any way but the default got a probe that asked the wrong thing and + * then reported "not signed in" for it. + */ + probe?: ModelProbeOptions; +} + /** Clack returns a symbol when the user hits Ctrl-C; treat it as an exit. */ function unwrap(value: T | symbol): T { if (isCancel(value)) { @@ -72,7 +106,79 @@ async function agentOptions(): Promise< ); } -export async function runWizard(cwd: string): Promise { +/** The sentinel for "do not write a model", distinct from any real id. */ +const MODEL_DEFAULT = "\u0000default"; +/** The sentinel for "let me type one", distinct from any real id. */ +const MODEL_CUSTOM = "\u0000custom"; + +/** + * Which model, for the agent just chosen. + * + * Asks the backend rather than offering a list from memory, so what is on + * screen is what that machine can actually run — `listModels` reports Claude's + * account-scoped set and OpenCode's configured providers, and falls back to the + * seed for Codex, which can enumerate nothing. + * + * Leaving it on the default is the first option and the likely answer, so it + * costs one Enter. The escape hatch is last, for a model too new to be listed. + */ +async function askForModel( + agent: AgentKind, + cwd: string, + opts: ModelProbeOptions = {} +): Promise { + const probe = spinner(); + probe.start(`Asking ${agent} which models it offers`); + const group = await listModels(agent, cwd, opts); + probe.stop( + group.note + ? `${agent}: ${group.note}` + : `${agent} offers ${group.models.length} models` + ); + + const choice = unwrap( + await select({ + message: "Which model?", + options: [ + { + hint: group.default ?? "whatever the backend picks", + label: "default", + value: MODEL_DEFAULT, + }, + ...group.models.map((m) => ({ + hint: m.hint, + label: m.label, + value: m.id, + })), + { hint: "type an id", label: "something else…", value: MODEL_CUSTOM }, + ], + }) + ); + + if (choice === MODEL_DEFAULT) { + return; + } + if (choice !== MODEL_CUSTOM) { + return choice; + } + const typed = unwrap( + await text({ + message: "Model id", + placeholder: + agent === "opencode" ? "anthropic/claude-sonnet-5" : "claude-opus-5", + validate: (value) => + agent === "opencode" && value && !value.includes("/") + ? "opencode needs the provider/model form, e.g. anthropic/claude-sonnet-5." + : undefined, + }) + ); + return typed?.trim() || undefined; +} + +export async function runWizard( + cwd: string, + options: WizardOptions = {} +): Promise { intro(style.magenta("◆ airship")); const probe = spinner(); @@ -101,6 +207,13 @@ export async function runWizard(cwd: string): Promise { }) ); + // Straight after the agent, because the answer only means anything against + // one: a model id is per backend, and asking before would have nothing to + // list. + const model = options.askModel + ? await askForModel(agent, cwd, options.probe) + : undefined; + const mode = unwrap( await select({ message: "Which surface?", @@ -127,7 +240,7 @@ export async function runWizard(cwd: string): Promise { ); outro(style.dim("Starting…")); - return { agent, mode, safe, target: Number(target) }; + return { agent, mode, model, safe, target: Number(target) }; } /** The message a non-interactive bare invocation gets instead of a prompt. */