Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

refactor(cli): model exact command intents

kashorinb40bde0894d1
diff --git a/packages/cli/README.md b/packages/cli/README.md
index f7a9b355..d3586cb2 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -15,10 +15,12 @@ Human output is compact by default. `--json` emits a stable, bounded command vie
compiler, Runtime or Repository objects. `--verbose` adds bounded operational detail; it never turns
the command into an internal state dump.
-The implementation follows those same boundaries: argument parsing and option ownership live in
-`arguments.ts`; project Result browsing/export lives under `commands/results.ts`; Runtime,
+The implementation follows those same boundaries: `command.ts` defines the exact semantic command
+union, while argument parsing and option ownership live in `arguments.ts`; project Result
+browsing/export lives under `commands/results.ts`; Runtime,
credential, package and deployment operations live under `commands/environment.ts`; active Build
observation is read-only code in `observation.ts`; and human rendering is separate from the explicit
-machine-view union. `main.ts` resolves project context and dispatches these command groups. Result
+machine-view union. `main.ts` resolves project and selected Runtime context separately from parsed
+syntax, then dispatches these command groups. Result
commands cannot silently construct a Runtime, and the generic CLI cannot silently choose a physical
Result Store or a Provider-specific login flow.
diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.ts
index 314ec4d3..db11c85a 100644
--- a/packages/cli/src/arguments.ts
+++ b/packages/cli/src/arguments.ts
@@ -1,79 +1,369 @@
import { resolve } from "node:path";
-import type { CliColorMode } from "./output.js";
+import type {
+ AuthCommand,
+ CliCommand,
+ EnvironmentCommand,
+ ExecutionCommand,
+ ProgramsCommand,
+ ProjectOption,
+ ProjectResultCommand,
+ RuntimeOperationCommand,
+ RuntimeOption,
+ RuntimeSelectionCommand,
+} from "./command.js";
+import type { CliColorMode, CliOutputOptions } from "./output.js";
-export type CliCommandName =
- | "check" | "plan" | "build"
- | "builds" | "history" | "inspect" | "get" | "status" | "activity" | "cancel" | "result"
- | "runtime" | "programs" | "packages" | "auth" | "doctor" | "paths"
- | "_worker";
-
-export type ParsedArgs = {
- readonly command: string | undefined;
- readonly action: string | undefined;
- readonly file: string | undefined;
- readonly workspaceRoot: string | undefined;
+type RawOptions = {
+ readonly presentation: CliOutputOptions;
+ readonly workspaceRoot?: string;
readonly assetRoots: readonly string[];
- readonly packageRoot: string | undefined;
- readonly runtime: string | undefined;
+ readonly packageRoot?: string;
+ readonly runtimeProfile?: string;
readonly follow: boolean;
- readonly maxWaitMs: number | undefined;
- readonly output: string | undefined;
- readonly title: string | undefined;
- readonly note: string | undefined;
+ readonly maxWaitMs?: number;
+ readonly outputName?: string;
+ readonly title?: string;
+ readonly note?: string;
readonly highlightedOutputs: readonly string[];
readonly clearTitle: boolean;
readonly clearNote: boolean;
readonly clearHighlights: boolean;
readonly limit: number;
readonly lines: number;
- readonly before: string | undefined;
- readonly to: string | undefined;
- readonly json: boolean;
- readonly color: CliColorMode;
- readonly verbose: boolean;
+ readonly before?: string;
+ readonly destination?: string;
readonly watch: boolean;
- readonly jsonl: boolean;
- readonly readyFile: string | undefined;
- readonly workerOwner: string | undefined;
- readonly reason: string | undefined;
- readonly slot: string | undefined;
- readonly from: string | undefined;
- readonly source: string | undefined;
+ readonly readyFile?: string;
+ readonly workerOwner?: string;
+ readonly reason?: string;
+ readonly slot?: string;
+ readonly credentialFile?: string;
+ readonly source?: string;
readonly seenOptions: readonly string[];
};
-const scopedCommands = new Set(["programs", "runtime", "auth", "result", "packages"]);
-const positionalOptionalCommands = new Set(["builds", "history", "activity", "paths", "programs", "runtime", "doctor"]);
-const knownCommands = new Set<CliCommandName>([
- "check", "plan", "build", "builds", "history", "inspect", "get", "status", "activity", "cancel",
- "result", "runtime", "programs", "packages", "auth", "doctor", "paths", "_worker",
-]);
+const commonOptions = ["--json", "--color", "--no-color", "--verbose", "--debug"] as const;
-export function isKnownCommand(value: string | undefined): value is CliCommandName {
- return value !== undefined && knownCommands.has(value as CliCommandName);
+export function parseCommand(argv: readonly string[]): CliCommand {
+ const [command, ...tail] = argv;
+ switch (command) {
+ case "check":
+ case "plan": {
+ const [source, rest] = requiredPositional(tail, `${command} requires one Source`);
+ const options = commandOptions(command, rest,
+ "--runtime", "--package-root", "--workspace", "--asset-root", "--limit");
+ return {
+ command,
+ source,
+ presentation: options.presentation,
+ assetRoots: options.assetRoots,
+ limit: options.limit,
+ ...optionalProject(options),
+ ...optionalRuntime(options),
+ ...optionalPackageRoot(options),
+ };
+ }
+ case "build": {
+ const [source, rest] = requiredPositional(tail, "build requires one Run Source");
+ const options = commandOptions(command, rest,
+ "--runtime", "--package-root", "--workspace", "--asset-root", "--follow", "--max-wait-ms", "--title", "--limit");
+ return {
+ command,
+ source,
+ presentation: options.presentation,
+ assetRoots: options.assetRoots,
+ limit: options.limit,
+ follow: options.follow,
+ ...optionalProject(options),
+ ...optionalRuntime(options),
+ ...optionalPackageRoot(options),
+ ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }),
+ ...(options.title === undefined ? {} : { title: options.title }),
+ };
+ }
+ case "builds": {
+ const options = commandOptions(command, tail, "--workspace", "--limit", "--before");
+ return {
+ command,
+ presentation: options.presentation,
+ limit: options.limit,
+ ...optionalProject(options),
+ ...(options.before === undefined ? {} : { before: options.before }),
+ };
+ }
+ case "history": {
+ const [outputName, rest] = requiredPositional(tail, "history requires one exact Output name");
+ const options = commandOptions(command, rest, "--workspace", "--source", "--limit", "--before");
+ return {
+ command,
+ outputName,
+ presentation: options.presentation,
+ limit: options.limit,
+ ...optionalProject(options),
+ ...(options.source === undefined ? {} : { source: options.source }),
+ ...(options.before === undefined ? {} : { before: options.before }),
+ };
+ }
+ case "inspect": {
+ const [build, rest] = requiredPositional(tail, "inspect requires one Build id");
+ const options = commandOptions(command, rest, "--workspace", "--output", "--limit");
+ return {
+ command,
+ build,
+ presentation: options.presentation,
+ limit: options.limit,
+ ...optionalProject(options),
+ ...(options.outputName === undefined ? {} : { outputName: options.outputName }),
+ };
+ }
+ case "get": {
+ const [build, rest] = requiredPositional(tail, "get requires one Build id");
+ const options = commandOptions(command, rest, "--workspace", "--output", "--to");
+ if (options.outputName === undefined) throw new Error("get requires --output with one public Output name");
+ if (options.destination === undefined) throw new Error("get requires --to with the export destination");
+ return {
+ command,
+ build,
+ outputName: options.outputName,
+ destination: options.destination,
+ presentation: options.presentation,
+ ...optionalProject(options),
+ };
+ }
+ case "status": {
+ const [build, rest] = requiredPositional(tail, "status requires one Build id");
+ const options = commandOptions(command, rest, "--runtime", "--watch", "--max-wait-ms", "--limit");
+ if (!options.watch && options.maxWaitMs !== undefined) {
+ throw new Error("--max-wait-ms applies to status --watch");
+ }
+ return {
+ command,
+ build,
+ presentation: options.presentation,
+ watch: options.watch,
+ limit: options.limit,
+ ...optionalRuntime(options),
+ ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }),
+ };
+ }
+ case "activity": {
+ const options = commandOptions(command, tail, "--runtime", "--watch", "--jsonl", "--limit");
+ if (options.presentation.jsonl === true && !options.watch) {
+ throw new Error("--jsonl applies only to activity --watch");
+ }
+ if (options.watch && options.presentation.json && options.presentation.jsonl !== true) {
+ throw new Error("activity --watch is a stream; use --jsonl instead of --json");
+ }
+ return {
+ command,
+ presentation: options.presentation,
+ watch: options.watch,
+ limit: options.limit,
+ ...optionalRuntime(options),
+ };
+ }
+ case "cancel": {
+ const [build, rest] = requiredPositional(tail, "cancel requires one Build id");
+ const options = commandOptions(command, rest, "--runtime", "--reason");
+ return {
+ command,
+ build,
+ presentation: options.presentation,
+ ...optionalRuntime(options),
+ ...(options.reason === undefined ? {} : { reason: options.reason }),
+ };
+ }
+ case "result": return parseResultCommand(tail);
+ case "runtime": return parseRuntimeCommand(tail);
+ case "programs": return parseProgramsCommand(tail);
+ case "packages": return parsePackagesCommand(tail);
+ case "auth": return parseAuthCommand(tail);
+ case "doctor": {
+ const [profile, rest] = optionalPositional(tail);
+ const options = commandOptions(command, rest, "--workspace", "--limit");
+ return {
+ command,
+ presentation: options.presentation,
+ limit: options.limit,
+ ...optionalProject(options),
+ ...runtimeOption(profile),
+ };
+ }
+ case "paths": {
+ const options = commandOptions(command, tail, "--runtime");
+ return { command, presentation: options.presentation, ...optionalRuntime(options) };
+ }
+ case "_worker": {
+ const [profile, rest] = requiredPositional(tail, "internal Worker launch is incomplete");
+ const options = commandOptions(command, rest, "--ready-file", "--worker-owner", "--package-root");
+ if (options.readyFile === undefined || options.workerOwner === undefined) {
+ throw new Error("internal Worker launch is incomplete");
+ }
+ return {
+ command,
+ profile,
+ readyFile: options.readyFile,
+ workerOwner: options.workerOwner,
+ presentation: options.presentation,
+ ...optionalPackageRoot(options),
+ };
+ }
+ default: throw new Error(usage());
+ }
}
-export function commandAllowsMissingPositional(value: string | undefined): boolean {
- return value !== undefined && positionalOptionalCommands.has(value);
+function parseResultCommand(tail: readonly string[]): ProjectResultCommand | ExecutionCommand {
+ const [action, ...values] = tail;
+ if (action !== "finish" && action !== "discard" && action !== "edit") {
+ throw new Error("result accepts finish, discard or edit");
+ }
+ const [build, rest] = requiredPositional(values, `result ${action} requires one Build id`);
+ if (action === "finish" || action === "discard") {
+ const options = commandOptions(`result ${action}`, rest, "--runtime");
+ return { command: "result", action, build, presentation: options.presentation, ...optionalRuntime(options) };
+ }
+ const options = commandOptions("result edit", rest,
+ "--workspace", "--title", "--note", "--highlight", "--clear-title", "--clear-note", "--clear-highlights", "--limit");
+ if (options.title !== undefined && options.clearTitle) throw new Error("--title and --clear-title are mutually exclusive");
+ if (options.note !== undefined && options.clearNote) throw new Error("--note and --clear-note are mutually exclusive");
+ if (options.highlightedOutputs.length > 0 && options.clearHighlights) {
+ throw new Error("--highlight and --clear-highlights are mutually exclusive");
+ }
+ if (options.title === undefined && options.note === undefined && options.highlightedOutputs.length === 0
+ && !options.clearTitle && !options.clearNote && !options.clearHighlights) {
+ throw new Error("result edit requires a presentation change");
+ }
+ return {
+ command: "result",
+ action,
+ build,
+ presentation: options.presentation,
+ highlightedOutputs: options.highlightedOutputs,
+ clearTitle: options.clearTitle,
+ clearNote: options.clearNote,
+ clearHighlights: options.clearHighlights,
+ limit: options.limit,
+ ...optionalProject(options),
+ ...(options.title === undefined ? {} : { title: options.title }),
+ ...(options.note === undefined ? {} : { note: options.note }),
+ };
}
-export function parseArgs(argv: readonly string[]): ParsedArgs {
- const [command, ...tail] = argv;
- const scoped = command !== undefined && scopedCommands.has(command);
- const action = scoped ? tail[0] : undefined;
- const positional = scoped ? tail.slice(1) : tail;
- const noFile = command === "builds" || command === "activity" || command === "paths";
- const hasFile = !noFile && positional[0] !== undefined && !positional[0]!.startsWith("--");
- const file = hasFile ? positional[0] : undefined;
- const rest = noFile || !hasFile ? positional : positional.slice(1);
+function parseRuntimeCommand(tail: readonly string[]): RuntimeSelectionCommand | RuntimeOperationCommand {
+ const [action, ...values] = tail;
+ if (action !== "use" && action !== "unset" && action !== "up" && action !== "down"
+ && action !== "status" && action !== "logs") {
+ throw new Error("runtime takes use, unset, up, down, status or logs");
+ }
+ if (action === "use") {
+ const [profile, rest] = requiredPositional(values, "runtime use requires a Runtime Profile");
+ const options = commandOptions("runtime use", rest, "--workspace");
+ return { command: "runtime", action, profile, presentation: options.presentation, ...optionalProject(options) };
+ }
+ if (action === "unset") {
+ const options = commandOptions("runtime unset", values, "--workspace");
+ return { command: "runtime", action, presentation: options.presentation, ...optionalProject(options) };
+ }
+ const [profile, rest] = optionalPositional(values);
+ const allowed = action === "up" || action === "down"
+ ? ["--runtime", "--max-wait-ms"] as const
+ : action === "status"
+ ? ["--runtime", "--limit"] as const
+ : ["--runtime", "--lines"] as const;
+ const options = commandOptions(`runtime ${action}`, rest, ...allowed);
+ rejectDuplicateProfile("runtime", profile, options.runtimeProfile);
+ const runtime = runtimeOption(profile ?? options.runtimeProfile);
+ const common = {
+ command: "runtime" as const,
+ action,
+ presentation: options.presentation,
+ ...runtime,
+ };
+ if (action === "up" || action === "down") {
+ return { ...common, action, ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) };
+ }
+ if (action === "status") return { ...common, action, limit: options.limit };
+ return { ...common, action, lines: options.lines };
+}
+
+function parseProgramsCommand(tail: readonly string[]): ProgramsCommand {
+ const [action, ...values] = tail;
+ if (action !== "up" && action !== "down" && action !== "status") {
+ throw new Error("programs takes up, down or status");
+ }
+ const [profile, rest] = optionalPositional(values);
+ const options = commandOptions(`programs ${action}`, rest,
+ "--runtime", "--limit", "--max-wait-ms");
+ if (action !== "up" && options.maxWaitMs !== undefined) {
+ throw new Error("--max-wait-ms applies to programs up");
+ }
+ rejectDuplicateProfile("programs", profile, options.runtimeProfile);
+ const runtime = runtimeOption(profile ?? options.runtimeProfile);
+ const common = {
+ command: "programs" as const,
+ action,
+ presentation: options.presentation,
+ limit: options.limit,
+ ...runtime,
+ };
+ return action === "up"
+ ? { ...common, action, ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) }
+ : { ...common, action };
+}
+
+function parsePackagesCommand(tail: readonly string[]): EnvironmentCommand {
+ const [action, ...values] = tail;
+ if (action !== "install" && action !== "status") throw new Error("packages takes install or status");
+ const [specifier, rest] = requiredPositional(values, `packages ${action} requires package@exact-version`);
+ const options = commandOptions(`packages ${action}`, rest);
+ return { command: "packages", action, package: specifier, presentation: options.presentation };
+}
+
+function parseAuthCommand(tail: readonly string[]): AuthCommand {
+ const [action, ...values] = tail;
+ if (action !== "status" && action !== "login" && action !== "logout") {
+ throw new Error("auth takes status, login or logout");
+ }
+ const [endpoint, rest] = requiredPositional(values, `auth ${action} requires one Endpoint instance`);
+ const options = commandOptions(`auth ${action}`, rest,
+ "--runtime", "--slot", ...(action === "login" ? ["--from"] as const : []),
+ ...(action === "status" ? ["--limit"] as const : []));
+ const common = {
+ command: "auth" as const,
+ action,
+ endpoint,
+ presentation: options.presentation,
+ ...optionalRuntime(options),
+ ...(options.slot === undefined ? {} : { slot: options.slot }),
+ };
+ if (action === "status") return { ...common, action, limit: options.limit };
+ if (action === "login") {
+ return {
+ ...common,
+ action,
+ ...(options.credentialFile === undefined ? {} : { credentialFile: options.credentialFile }),
+ };
+ }
+ return { ...common, action };
+}
+
+function commandOptions(label: string, values: readonly string[], ...allowed: readonly string[]): RawOptions {
+ const options = parseOptions(values);
+ const accepted = new Set<string>([...commonOptions, ...allowed]);
+ const invalid = options.seenOptions.find((item) => !accepted.has(item));
+ if (invalid !== undefined) throw new Error(`${invalid} does not apply to ${label}`);
+ return options;
+}
+
+function parseOptions(values: readonly string[]): RawOptions {
let workspaceRoot: string | undefined;
const assetRoots: string[] = [];
let packageRoot: string | undefined;
- let runtime: string | undefined;
+ let runtimeProfile: string | undefined;
let follow = false;
let maxWaitMs: number | undefined;
- let output: string | undefined;
+ let outputName: string | undefined;
let title: string | undefined;
let note: string | undefined;
const highlightedOutputs: string[] = [];
@@ -83,29 +373,28 @@ export function parseArgs(argv: readonly string[]): ParsedArgs {
let limit = 20;
let lines = 50;
let before: string | undefined;
- let to: string | undefined;
+ let destination: string | undefined;
let json = false;
+ let jsonl = false;
let color: CliColorMode = "auto";
let verbose = false;
let watch = false;
- let jsonl = false;
let readyFile: string | undefined;
let workerOwner: string | undefined;
let reason: string | undefined;
let slot: string | undefined;
- let from: string | undefined;
+ let credentialFile: string | undefined;
let source: string | undefined;
const seenOptions = new Set<string>();
- for (let index = 0; index < rest.length; index += 1) {
- const item = rest[index]!;
- if (item.startsWith("--")) {
- const repeatable = [
- "--json", "--jsonl", "--watch", "--verbose", "--debug",
- "--no-color", "--follow", "--asset-root", "--highlight",
- ].includes(item);
- if (!repeatable && seenOptions.has(item)) throw new Error(`${item} cannot be repeated`);
- seenOptions.add(item);
- }
+ for (let index = 0; index < values.length; index += 1) {
+ const item = values[index]!;
+ if (!item.startsWith("--")) throw new Error(`unexpected positional argument ${item}`);
+ const repeatable = [
+ "--json", "--jsonl", "--watch", "--verbose", "--debug",
+ "--no-color", "--follow", "--asset-root", "--highlight",
+ ].includes(item);
+ if (!repeatable && seenOptions.has(item)) throw new Error(`${item} cannot be repeated`);
+ seenOptions.add(item);
if (item === "--json") { json = true; continue; }
if (item === "--jsonl") { jsonl = true; continue; }
if (item === "--watch") { watch = true; continue; }
@@ -113,7 +402,7 @@ export function parseArgs(argv: readonly string[]): ParsedArgs {
if (item === "--debug") continue;
if (item === "--no-color") { color = "never"; continue; }
if (item === "--color") {
- const value = rest[index + 1];
+ const value = optionValue(values, index, "--color requires auto, always or never");
if (value !== "auto" && value !== "always" && value !== "never") {
throw new Error("--color requires auto, always or never");
}
@@ -122,89 +411,119 @@ export function parseArgs(argv: readonly string[]): ParsedArgs {
continue;
}
if (item === "--workspace") {
- const value = optionValue(rest, index, "--workspace requires a directory");
- workspaceRoot = resolve(value); index += 1; continue;
+ workspaceRoot = resolve(optionValue(values, index, "--workspace requires a directory")); index += 1; continue;
}
if (item === "--asset-root") {
- const value = optionValue(rest, index, "--asset-root requires a directory");
- assetRoots.push(resolve(value)); index += 1; continue;
+ assetRoots.push(resolve(optionValue(values, index, "--asset-root requires a directory"))); index += 1; continue;
}
if (item === "--package-root") {
- const value = optionValue(rest, index, "--package-root requires a directory");
- packageRoot = resolve(value); index += 1; continue;
+ packageRoot = resolve(optionValue(values, index, "--package-root requires a directory")); index += 1; continue;
}
if (item === "--runtime") {
- const value = optionValue(rest, index, "--runtime requires a Runtime Profile");
- runtime = resolve(value); index += 1; continue;
+ runtimeProfile = resolve(optionValue(values, index, "--runtime requires a Runtime Profile")); index += 1; continue;
}
if (item === "--out") {
throw new Error("--out does not apply to Build submission; use `get <build-id> --output <name> --to <path>` to export one Result Output");
}
if (item === "--output") {
- output = optionValue(rest, index, "--output requires a public Output name"); index += 1; continue;
+ outputName = optionValue(values, index, "--output requires a public Output name"); index += 1; continue;
}
if (item === "--title") {
- title = optionValue(rest, index, "--title requires text"); index += 1; continue;
+ title = optionValue(values, index, "--title requires text"); index += 1; continue;
}
if (item === "--note") {
- note = optionValue(rest, index, "--note requires text"); index += 1; continue;
+ note = optionValue(values, index, "--note requires text"); index += 1; continue;
}
if (item === "--highlight") {
- highlightedOutputs.push(optionValue(rest, index, "--highlight requires an Output name")); index += 1; continue;
+ highlightedOutputs.push(optionValue(values, index, "--highlight requires an Output name")); index += 1; continue;
}
if (item === "--clear-title") { clearTitle = true; continue; }
if (item === "--clear-note") { clearNote = true; continue; }
if (item === "--clear-highlights") { clearHighlights = true; continue; }
if (item === "--limit") {
- limit = positiveInteger(optionValue(rest, index, "--limit requires a positive integer"), "--limit");
+ limit = positiveInteger(optionValue(values, index, "--limit requires a positive integer"), "--limit");
index += 1; continue;
}
if (item === "--lines") {
- lines = positiveInteger(optionValue(rest, index, "--lines requires a positive integer"), "--lines");
+ lines = positiveInteger(optionValue(values, index, "--lines requires a positive integer"), "--lines");
index += 1; continue;
}
if (item === "--before") {
- before = optionValue(rest, index, "--before requires a Build id"); index += 1; continue;
+ before = optionValue(values, index, "--before requires a Build id"); index += 1; continue;
}
if (item === "--to") {
- to = resolve(optionValue(rest, index, "--to requires a file path")); index += 1; continue;
+ destination = resolve(optionValue(values, index, "--to requires a file path")); index += 1; continue;
}
if (item === "--follow") { follow = true; continue; }
if (item === "--max-wait-ms") {
- const value = Number(optionValue(rest, index, "--max-wait-ms requires milliseconds"));
- if (!Number.isSafeInteger(value) || value < 0) {
- throw new Error("--max-wait-ms must be a non-negative safe integer");
- }
+ const value = Number(optionValue(values, index, "--max-wait-ms requires milliseconds"));
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("--max-wait-ms must be a non-negative safe integer");
maxWaitMs = value; index += 1; continue;
}
if (item === "--ready-file") {
- readyFile = resolve(optionValue(rest, index, "--ready-file requires a path")); index += 1; continue;
+ readyFile = resolve(optionValue(values, index, "--ready-file requires a path")); index += 1; continue;
}
if (item === "--worker-owner") {
- workerOwner = optionValue(rest, index, "--worker-owner requires an identity"); index += 1; continue;
+ workerOwner = optionValue(values, index, "--worker-owner requires an identity"); index += 1; continue;
}
if (item === "--reason") {
- reason = optionValue(rest, index, "--reason requires text"); index += 1; continue;
+ reason = optionValue(values, index, "--reason requires text"); index += 1; continue;
}
if (item === "--slot") {
- slot = optionValue(rest, index, "--slot requires a credential slot"); index += 1; continue;
+ slot = optionValue(values, index, "--slot requires a credential slot"); index += 1; continue;
}
if (item === "--from") {
- from = resolve(optionValue(rest, index, "--from requires a credential file")); index += 1; continue;
+ credentialFile = resolve(optionValue(values, index, "--from requires a credential file")); index += 1; continue;
}
if (item === "--source") {
- source = resolve(optionValue(rest, index, "--source requires a source path")); index += 1; continue;
+ source = resolve(optionValue(values, index, "--source requires a source path")); index += 1; continue;
}
throw new Error(`unknown option ${item}`);
}
+ if (seenOptions.has("--color") && seenOptions.has("--no-color")) {
+ throw new Error("--color and --no-color are mutually exclusive");
+ }
return {
- command, action, file, workspaceRoot, assetRoots, packageRoot, runtime, follow, maxWaitMs,
- output, title, note, highlightedOutputs, clearTitle, clearNote, clearHighlights, limit, lines,
- before, to, json, color, verbose, watch, jsonl, readyFile, workerOwner, reason, slot, from, source,
+ presentation: { json: json || jsonl, ...(jsonl ? { jsonl: true } : {}), color, verbose },
+ assetRoots,
+ follow,
+ highlightedOutputs,
+ clearTitle,
+ clearNote,
+ clearHighlights,
+ limit,
+ lines,
+ watch,
seenOptions: [...seenOptions],
+ ...(workspaceRoot === undefined ? {} : { workspaceRoot }),
+ ...(packageRoot === undefined ? {} : { packageRoot }),
+ ...(runtimeProfile === undefined ? {} : { runtimeProfile }),
+ ...(maxWaitMs === undefined ? {} : { maxWaitMs }),
+ ...(outputName === undefined ? {} : { outputName }),
+ ...(title === undefined ? {} : { title }),
+ ...(note === undefined ? {} : { note }),
+ ...(before === undefined ? {} : { before }),
+ ...(destination === undefined ? {} : { destination }),
+ ...(readyFile === undefined ? {} : { readyFile }),
+ ...(workerOwner === undefined ? {} : { workerOwner }),
+ ...(reason === undefined ? {} : { reason }),
+ ...(slot === undefined ? {} : { slot }),
+ ...(credentialFile === undefined ? {} : { credentialFile }),
+ ...(source === undefined ? {} : { source }),
};
}
+function requiredPositional(values: readonly string[], message: string): readonly [string, readonly string[]] {
+ const value = values[0];
+ if (value === undefined || value.startsWith("--")) throw new Error(message);
+ return [value, values.slice(1)];
+}
+
+function optionalPositional(values: readonly string[]): readonly [string | undefined, readonly string[]] {
+ const value = values[0];
+ return value === undefined || value.startsWith("--") ? [undefined, values] : [value, values.slice(1)];
+}
+
function optionValue(values: readonly string[], index: number, message: string): string {
const value = values[index + 1];
if (value === undefined || value.startsWith("--")) throw new Error(message);
@@ -217,65 +536,28 @@ function positiveInteger(value: string, option: string): number {
return parsed;
}
-export function assertCommandOptions(args: ParsedArgs): void {
- const common = ["--json", "--color", "--no-color", "--verbose", "--debug"];
- const allowed = new Set(common);
- const add = (...items: readonly string[]): void => { for (const item of items) allowed.add(item); };
- switch (args.command) {
- case "programs": add("--max-wait-ms", "--runtime", "--limit"); break;
- case "runtime":
- add("--runtime");
- if (args.action === "use" || args.action === "unset") add("--workspace");
- if (args.action === "up" || args.action === "down") add("--max-wait-ms");
- if (args.action === "logs") add("--lines");
- if (args.action === "status") add("--limit");
- break;
- case "packages": break;
- case "auth":
- add("--runtime", "--slot");
- if (args.action === "login") add("--from");
- if (args.action === "status") add("--limit");
- break;
- case "activity": add("--runtime", "--watch", "--jsonl", "--limit"); break;
- case "paths": add("--runtime"); break;
- case "get": add("--workspace", "--output", "--to"); break;
- case "cancel": add("--runtime", "--reason"); break;
- case "result":
- if (args.action === "finish" || args.action === "discard") add("--runtime");
- if (args.action === "edit") {
- add("--workspace", "--title", "--note", "--highlight", "--clear-title", "--clear-note", "--clear-highlights", "--limit");
- }
- break;
- case "doctor": add("--workspace", "--limit"); break;
- case "status":
- add("--runtime", "--watch", "--limit");
- if (args.watch) add("--max-wait-ms");
- break;
- case "builds":
- case "history":
- add("--workspace", "--limit", "--before");
- if (args.command === "history") add("--source");
- break;
- case "inspect": add("--workspace", "--output", "--limit"); break;
- case "check":
- case "plan": add("--runtime", "--package-root", "--workspace", "--asset-root", "--limit"); break;
- case "build":
- add("--runtime", "--package-root", "--workspace", "--asset-root", "--follow", "--max-wait-ms", "--title", "--limit");
- break;
- }
- const invalid = args.seenOptions.find((item) => !allowed.has(item));
- if (invalid !== undefined) {
- const command = args.action === undefined ? args.command : `${args.command} ${args.action}`;
- throw new Error(`${invalid} does not apply to ${command}`);
- }
- if (args.seenOptions.includes("--color") && args.seenOptions.includes("--no-color")) {
- throw new Error("--color and --no-color are mutually exclusive");
- }
- if (args.command === "get" && args.output === undefined) {
- throw new Error("get requires --output with one public Output name");
- }
- if (args.command === "get" && args.to === undefined) {
- throw new Error("get requires --to with the export destination");
+function optionalProject(options: RawOptions): ProjectOption {
+ return options.workspaceRoot === undefined ? {} : { workspaceRoot: options.workspaceRoot };
+}
+
+function optionalRuntime(options: RawOptions): RuntimeOption {
+ return runtimeOption(options.runtimeProfile);
+}
+
+function runtimeOption(profile: string | undefined): RuntimeOption {
+ return profile === undefined ? {} : { runtimeProfile: profile };
+}
+
+function optionalPackageRoot(options: RawOptions): { readonly packageRoot?: string } {
+ return options.packageRoot === undefined ? {} : { packageRoot: options.packageRoot };
+}
+
+function rejectDuplicateProfile(command: "runtime" | "programs", profile: string | undefined, option: string | undefined): void {
+ if (profile !== undefined && option !== undefined) {
+ const detail = command === "runtime"
+ ? "accepts the Runtime Profile either positionally or with --runtime, not both"
+ : "reads all deployment selection from the Runtime Profile itself; provide that Profile only once";
+ throw new Error(`${command} ${detail}`);
}
}
diff --git a/packages/cli/src/command.ts b/packages/cli/src/command.ts
new file mode 100644
index 00000000..0be1dc3d
--- /dev/null
+++ b/packages/cli/src/command.ts
@@ -0,0 +1,193 @@
+import type { CliOutputOptions } from "./output.js";
+
+type CommandBase = {
+ readonly presentation: CliOutputOptions;
+};
+
+export type RuntimeOption = {
+ readonly runtimeProfile?: string;
+};
+
+export type ProjectOption = {
+ readonly workspaceRoot?: string;
+};
+
+type AuthorOptions = ProjectOption & RuntimeOption & {
+ readonly source: string;
+ readonly assetRoots: readonly string[];
+ readonly packageRoot?: string;
+ readonly limit: number;
+};
+
+export type AuthorCommand =
+ | (CommandBase & AuthorOptions & { readonly command: "check" })
+ | (CommandBase & AuthorOptions & { readonly command: "plan" })
+ | (CommandBase & AuthorOptions & {
+ readonly command: "build";
+ readonly follow: boolean;
+ readonly maxWaitMs?: number;
+ readonly title?: string;
+ });
+
+export type ProjectResultCommand =
+ | (CommandBase & ProjectOption & {
+ readonly command: "builds";
+ readonly limit: number;
+ readonly before?: string;
+ })
+ | (CommandBase & ProjectOption & {
+ readonly command: "history";
+ readonly outputName: string;
+ readonly source?: string;
+ readonly limit: number;
+ readonly before?: string;
+ })
+ | (CommandBase & ProjectOption & {
+ readonly command: "inspect";
+ readonly build: string;
+ readonly outputName?: string;
+ readonly limit: number;
+ })
+ | (CommandBase & ProjectOption & {
+ readonly command: "get";
+ readonly build: string;
+ readonly outputName: string;
+ readonly destination: string;
+ })
+ | (CommandBase & ProjectOption & {
+ readonly command: "result";
+ readonly action: "edit";
+ readonly build: string;
+ readonly title?: string;
+ readonly note?: string;
+ readonly highlightedOutputs: readonly string[];
+ readonly clearTitle: boolean;
+ readonly clearNote: boolean;
+ readonly clearHighlights: boolean;
+ readonly limit: number;
+ });
+
+export type ExecutionCommand =
+ | (CommandBase & RuntimeOption & {
+ readonly command: "status";
+ readonly build: string;
+ readonly watch: boolean;
+ readonly maxWaitMs?: number;
+ readonly limit: number;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "activity";
+ readonly watch: boolean;
+ readonly limit: number;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "cancel";
+ readonly build: string;
+ readonly reason?: string;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "result";
+ readonly action: "finish" | "discard";
+ readonly build: string;
+ });
+
+export type RuntimeSelectionCommand =
+ | (CommandBase & ProjectOption & {
+ readonly command: "runtime";
+ readonly action: "use";
+ readonly profile: string;
+ })
+ | (CommandBase & ProjectOption & {
+ readonly command: "runtime";
+ readonly action: "unset";
+ });
+
+export type RuntimeOperationCommand =
+ | (CommandBase & RuntimeOption & {
+ readonly command: "runtime";
+ readonly action: "up";
+ readonly maxWaitMs?: number;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "runtime";
+ readonly action: "down";
+ readonly maxWaitMs?: number;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "runtime";
+ readonly action: "status";
+ readonly limit: number;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "runtime";
+ readonly action: "logs";
+ readonly lines: number;
+ });
+
+export type ProgramsCommand =
+ | (CommandBase & RuntimeOption & {
+ readonly command: "programs";
+ readonly action: "up";
+ readonly maxWaitMs?: number;
+ readonly limit: number;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "programs";
+ readonly action: "down" | "status";
+ readonly limit: number;
+ });
+
+export type AuthCommand =
+ | (CommandBase & RuntimeOption & {
+ readonly command: "auth";
+ readonly action: "status";
+ readonly endpoint: string;
+ readonly slot?: string;
+ readonly limit: number;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "auth";
+ readonly action: "login";
+ readonly endpoint: string;
+ readonly slot?: string;
+ readonly credentialFile?: string;
+ })
+ | (CommandBase & RuntimeOption & {
+ readonly command: "auth";
+ readonly action: "logout";
+ readonly endpoint: string;
+ readonly slot?: string;
+ });
+
+export type EnvironmentCommand =
+ | RuntimeOperationCommand
+ | ProgramsCommand
+ | AuthCommand
+ | (CommandBase & RuntimeOption & {
+ readonly command: "paths";
+ })
+ | (CommandBase & {
+ readonly command: "packages";
+ readonly action: "install" | "status";
+ readonly package: string;
+ })
+ | (CommandBase & ProjectOption & RuntimeOption & {
+ readonly command: "doctor";
+ readonly limit: number;
+ });
+
+export type WorkerCommand = CommandBase & {
+ readonly command: "_worker";
+ readonly profile: string;
+ readonly readyFile: string;
+ readonly workerOwner: string;
+ readonly packageRoot?: string;
+};
+
+export type CliCommand =
+ | AuthorCommand
+ | ProjectResultCommand
+ | ExecutionCommand
+ | RuntimeSelectionCommand
+ | EnvironmentCommand
+ | WorkerCommand;
diff --git a/packages/cli/src/commands/environment.ts b/packages/cli/src/commands/environment.ts
index 6e9cb688..ccb44066 100644
--- a/packages/cli/src/commands/environment.ts
+++ b/packages/cli/src/commands/environment.ts
@@ -4,7 +4,7 @@ import { resolve } from "node:path";
import type { NodeRuntimeHost } from "@hypit/runtime-host-node";
import { hypitHostPackageRoot, inspectHostPackage, prepareHostPackages } from "@hypit/runtime-host-node";
-import type { ParsedArgs } from "../arguments.js";
+import type { CliCommand, EnvironmentCommand } from "../command.js";
import type { CliDistribution } from "../distribution.js";
import { acquireOAuthCredential } from "../oauth.js";
import { writeCliOutput } from "../output.js";
@@ -14,8 +14,16 @@ import type { CliRuntimeController } from "../runtime-port.js";
import { queueLaneLines, summarizeQueueLanes } from "../runtime-view.js";
import type { OperationalWriter } from "./types.js";
+export function isEnvironmentCommand(args: CliCommand): args is EnvironmentCommand {
+ return args.command === "paths" || args.command === "packages" || args.command === "doctor"
+ || args.command === "programs" || args.command === "auth"
+ || (args.command === "runtime"
+ && (args.action === "up" || args.action === "down" || args.action === "status" || args.action === "logs"));
+}
+
export async function runEnvironmentCommand(input: {
- readonly args: ParsedArgs;
+ readonly args: EnvironmentCommand;
+ readonly runtimeProfile: string | undefined;
readonly io: CliIo;
readonly distribution: CliDistribution;
readonly projectRoot: string;
@@ -23,11 +31,11 @@ export async function runEnvironmentCommand(input: {
readonly runtimeHost: (profile: string, packageRoot?: string) => Promise<NodeRuntimeHost>;
readonly runtimeController: (profile: string) => Promise<CliRuntimeController>;
readonly write: OperationalWriter;
-}): Promise<boolean> {
+}): Promise<void> {
const {
- args, io, distribution, projectRoot, packageRootForProject, runtimeHost, runtimeController, write,
+ args, runtimeProfile, io, distribution, projectRoot, packageRootForProject, runtimeHost, runtimeController, write,
} = input;
- const reportProgramProgress = args.json || args.jsonl
+ const reportProgramProgress = args.presentation.json
? undefined
: (event: { readonly id: string; readonly phase: "checking" | "installing" | "starting" | "waiting" | "ready" }): void => {
const verb = {
@@ -39,21 +47,21 @@ export async function runEnvironmentCommand(input: {
}[event.phase];
io.write(` · ${verb} ${event.id}\n`);
};
- const reportPackageProgress = args.json || args.jsonl
+ const reportPackageProgress = args.presentation.json
? undefined
: (event: { readonly specifier: string; readonly phase: "checking" | "installing" | "ready" }): void => {
if (event.phase === "installing") io.write(` · Installing ${event.specifier}\n`);
};
if (args.command === "paths") {
- const runtimePaths = args.runtime === undefined
+ const runtimePaths = runtimeProfile === undefined
? undefined
- : await (await runtimeHost(args.runtime)).resolvePaths();
+ : await (await runtimeHost(runtimeProfile)).resolvePaths();
const machine = {
format: "hypit.cli-paths@1" as const,
project: projectRoot,
projectState: hypitProjectStateRoot(projectRoot),
- ...(args.runtime === undefined ? {} : { profile: args.runtime }),
+ ...(runtimeProfile === undefined ? {} : { profile: runtimeProfile }),
...(runtimePaths === undefined ? {} : { runtimeData: runtimePaths.runtimeDataRoot }),
hostState: hypitHostStateRoot(),
machinePackages: hypitHostPackageRoot(),
@@ -68,18 +76,14 @@ export async function runEnvironmentCommand(input: {
["Machine packages", machine.machinePackages],
["Distribution", machine.distribution ?? "embedded"],
]);
- return true;
+ return;
}
if (args.command === "packages") {
- if (args.action !== "install" && args.action !== "status") {
- throw new Error("packages takes install or status");
- }
- if (args.file === undefined) throw new Error(`packages ${args.action} requires package@exact-version`);
const root = hypitHostPackageRoot();
- const existing = await inspectHostPackage(args.file, root);
+ const existing = await inspectHostPackage(args.package, root);
const reports = args.action === "install"
- ? await prepareHostPackages([args.file], {
+ ? await prepareHostPackages([args.package], {
root,
...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }),
})
@@ -88,23 +92,19 @@ export async function runEnvironmentCommand(input: {
write({
format: "hypit.cli-package@2",
action: args.action,
- package: args.file,
+ package: args.package,
ready,
}, args.action === "install" ? "Machine package is ready" : "Machine package status",
ready ? "success" : "warning", [
- ["Package", args.file],
+ ["Package", args.package],
["Ready", String(ready)],
]);
if (!ready) io.setExitCode?.(1);
- return true;
+ return;
}
if (args.command === "doctor") {
- if (args.packageRoot !== undefined) {
- throw new Error("doctor reads all deployment selection from the Runtime Profile itself");
- }
- const profileInput = args.runtime ?? args.file;
- const profile = profileInput === undefined ? undefined : resolve(profileInput);
+ const profile = runtimeProfile === undefined ? undefined : resolve(runtimeProfile);
const [runtimeResult, projectResult] = await Promise.all([
profile === undefined ? undefined : (await runtimeHost(profile)).doctor(),
distribution.diagnoseProjectResults(projectRoot, {
@@ -124,32 +124,14 @@ export async function runEnvironmentCommand(input: {
diagnostics: diagnostics.slice(0, args.limit),
...(diagnostics.length <= args.limit ? {} : { omittedDiagnostics: diagnostics.length - args.limit }),
};
- writeCliOutput(io, {
- json: args.json || args.jsonl,
- jsonl: args.jsonl,
- color: args.color,
- verbose: args.verbose,
- }, { kind: "doctor", machine });
+ writeCliOutput(io, args.presentation, { kind: "doctor", machine });
if (!machine.ok) io.setExitCode?.(1);
- return true;
+ return;
}
if (args.command === "programs") {
- if (args.file !== undefined && args.runtime !== undefined) {
- throw new Error("programs reads all deployment selection from the Runtime Profile itself; provide that Profile only once");
- }
- if (args.packageRoot !== undefined) {
- throw new Error("programs reads all deployment selection from the Runtime Profile itself");
- }
- if (args.action !== "up" && args.action !== "down" && args.action !== "status") {
- throw new Error("programs takes up, down or status");
- }
- if (args.action !== "up" && args.maxWaitMs !== undefined) {
- throw new Error("--max-wait-ms applies to programs up");
- }
- const profileInput = args.runtime ?? args.file;
- if (profileInput === undefined) throw new Error("programs requires a Runtime Profile");
- const profile = resolve(profileInput);
+ if (runtimeProfile === undefined) throw new Error("programs requires a Runtime Profile");
+ const profile = resolve(runtimeProfile);
const host = await runtimeHost(profile);
if (args.action === "up") {
await host.prepare(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress });
@@ -174,7 +156,7 @@ export async function runEnvironmentCommand(input: {
programs: result.programs.slice(0, args.limit).map((item) => ({
id: item.id,
state: item.state.state,
- ...(args.verbose && item.action !== undefined ? { action: item.action } : {}),
+ ...(args.presentation.verbose && item.action !== undefined ? { action: item.action } : {}),
})),
...(result.programs.length <= args.limit ? {} : { omittedPrograms: result.programs.length - args.limit }),
}, `External programs ${args.action}`,
@@ -183,19 +165,12 @@ export async function runEnvironmentCommand(input: {
["Ready", String(result.programs.filter((item) => item.state.state === "ready").length)],
], shownPrograms.map((item) => `${item.id}: ${item.state.state}`));
if (!lifecycleOk) io.setExitCode?.(1);
- return true;
+ return;
}
if (args.command === "runtime") {
- if (args.action !== "up" && args.action !== "down" && args.action !== "status" && args.action !== "logs") {
- throw new Error("runtime takes up, down, status or logs");
- }
- if (args.file !== undefined && args.runtime !== undefined) {
- throw new Error("runtime accepts the Runtime Profile either positionally or with --runtime, not both");
- }
- const profileInput = args.runtime ?? args.file;
- if (profileInput === undefined) throw new Error("runtime requires a Runtime Profile");
- const profile = resolve(profileInput);
+ if (runtimeProfile === undefined) throw new Error("runtime requires a Runtime Profile");
+ const profile = resolve(runtimeProfile);
const controller = await runtimeController(profile);
if (args.action === "up") {
const packageRoot = await packageRootForProject();
@@ -229,7 +204,7 @@ export async function runEnvironmentCommand(input: {
["External programs", String(external.programs.length)],
]);
if (!ok) io.setExitCode?.(1);
- return true;
+ return;
}
if (args.action === "logs") {
const logs = await controller.worker.logs();
@@ -240,12 +215,12 @@ export async function runEnvironmentCommand(input: {
lines: shown,
totalLines: lines.length,
omittedLines: Math.max(0, lines.length - shown.length),
- ...(args.verbose ? { path: logs.path } : {}),
+ ...(args.presentation.verbose ? { path: logs.path } : {}),
}, "Runtime logs", "info", [
["Lines", `${shown.length}/${lines.length}`],
- ...(args.verbose ? [["Path", logs.path] as const] : []),
+ ...(args.presentation.verbose ? [["Path", logs.path] as const] : []),
], shown.length === 0 ? ["No log output."] : shown);
- return true;
+ return;
}
if (args.action === "down") {
const worker = await controller.worker.down({
@@ -254,7 +229,7 @@ export async function runEnvironmentCommand(input: {
write({ format: "hypit.cli-runtime-down@2", worker: worker.state },
"Runtime Worker is down", "success", [["Worker", worker.state]],
["External programs were left running. Stop them explicitly with hypit programs down."]);
- return true;
+ return;
}
const runtimeLoading = (await runtimeHost(profile)).openControl({ readOnly: true });
@@ -295,7 +270,7 @@ export async function runEnvironmentCommand(input: {
},
capacity: {
active: activity.capacity.length,
- ...(args.verbose ? { lanes: lanes.slice(0, args.limit) } : {}),
+ ...(args.presentation.verbose ? { lanes: lanes.slice(0, args.limit) } : {}),
},
};
write(machine, "Runtime status", attention ? "warning" : ready ? "success" : "info", [
@@ -305,33 +280,29 @@ export async function runEnvironmentCommand(input: {
["Waiting", String(counts.waiting ?? 0)],
["Decided", String(counts.decided ?? 0)],
["Programs", `${external.programs.length - unavailable.length}/${external.programs.length} ready`],
- ...(args.verbose ? [["Active requests", String(activity.capacity.length)] as const] : []),
+ ...(args.presentation.verbose ? [["Active requests", String(activity.capacity.length)] as const] : []),
], [
...unavailable.slice(0, args.limit).map((item) => `${item.id}: ${item.state.state}`),
- ...(args.verbose ? queueLaneLines(lanes.slice(0, args.limit)) : []),
+ ...(args.presentation.verbose ? queueLaneLines(lanes.slice(0, args.limit)) : []),
]);
} finally {
if (runtime !== undefined) await runtime.close();
else await runtimeLoading.then(async (loaded) => await loaded.close(), () => undefined);
}
- return true;
+ return;
}
if (args.command === "auth") {
- if (args.action !== "status" && args.action !== "login" && args.action !== "logout") {
- throw new Error("auth takes status, login or logout");
- }
- if (args.runtime === undefined) {
+ if (runtimeProfile === undefined) {
throw new Error("auth requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>");
}
- if (args.from !== undefined && args.action !== "login") throw new Error("--from applies only to auth login");
- const credentialsControl = await (await runtimeHost(args.runtime)).openCredentials(args.file!);
+ const credentialsControl = await (await runtimeHost(runtimeProfile)).openCredentials(args.endpoint);
try {
- let credentials = await credentialsControl.credentials(args.file!);
+ let credentials = await credentialsControl.credentials(args.endpoint);
if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);
- if (credentials.length === 0) throw new Error(`Endpoint ${args.file} has no matching credential`);
+ if (credentials.length === 0) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
if (args.slot === undefined && credentials.length > 1 && args.action !== "status") {
- throw new Error(`Endpoint ${args.file} has several credentials; select one with --slot`);
+ throw new Error(`Endpoint ${args.endpoint} has several credentials; select one with --slot`);
}
if (args.action === "status") {
const view = credentials.slice(0, args.limit).map((item) => ({
@@ -344,28 +315,28 @@ export async function runEnvironmentCommand(input: {
}));
write({
format: "hypit.cli-auth-status@2",
- endpoint: args.file!,
+ endpoint: args.endpoint,
credentials: view,
...(credentials.length <= args.limit ? {} : { omittedCredentials: credentials.length - args.limit }),
}, "Credential status", "info", [
- ["Endpoint", args.file!],
+ ["Endpoint", args.endpoint],
["Configured", `${credentials.filter((item) => item.configured).length}/${credentials.length}`],
], credentials.slice(0, args.limit).map((item) =>
`${item.slot}: ${item.configured ? "configured" : "missing"} · ${item.writable ? "writable" : "read-only"}`));
} else if (args.action === "login") {
const [item] = credentials;
- if (item === undefined) throw new Error(`Endpoint ${args.file} has no matching credential`);
+ if (item === undefined) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
if (!item.writable) {
const source = item.ref.store === "env"
? `set ${item.ref.key} in the environment`
: "select a writable credential source in the Runtime Profile";
throw new Error(`${item.label} cannot be written by this command; ${source}`);
}
- const raw = item.acquisition !== undefined && args.from === undefined
+ const raw = item.acquisition !== undefined && args.credentialFile === undefined
? await acquireOAuthCredential(io, item.acquisition)
- : args.from === undefined
+ : args.credentialFile === undefined
? await io.readSecret?.(`${item.label}: `)
- : await readFile(args.from, "utf8");
+ : await readFile(args.credentialFile, "utf8");
if (raw === undefined) throw new Error("interactive credential input is unavailable; use --from <file>");
const secret = raw.trim();
if (secret.length === 0) throw new Error("credential input is empty");
@@ -375,30 +346,28 @@ export async function runEnvironmentCommand(input: {
const stored = await credentialsControl.putCredential(item.endpoint, item.slot, secret);
write({
format: "hypit.cli-auth-change@2",
- endpoint: args.file!,
+ endpoint: args.endpoint,
slot: stored.slot,
configured: true,
- }, "Credential stored", "success", [["Endpoint", args.file!], ["Slot", stored.slot]]);
+ }, "Credential stored", "success", [["Endpoint", args.endpoint], ["Slot", stored.slot]]);
} else {
const [item] = credentials;
- if (item === undefined) throw new Error(`Endpoint ${args.file} has no matching credential`);
+ if (item === undefined) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
const removed = await credentialsControl.deleteCredential(item.endpoint, item.slot);
write({
format: "hypit.cli-auth-change@2",
- endpoint: args.file!,
+ endpoint: args.endpoint,
slot: removed.credential.slot,
configured: false,
changed: removed.deleted,
}, removed.deleted ? "Credential removed" : "Credential was absent",
removed.deleted ? "success" : "warning", [
- ["Endpoint", args.file!], ["Slot", removed.credential.slot],
+ ["Endpoint", args.endpoint], ["Slot", removed.credential.slot],
]);
}
} finally {
await credentialsControl.close();
}
- return true;
+ return;
}
-
- return false;
}
diff --git a/packages/cli/src/commands/execution.ts b/packages/cli/src/commands/execution.ts
index 9d57fadf..b8e98972 100644
--- a/packages/cli/src/commands/execution.ts
+++ b/packages/cli/src/commands/execution.ts
@@ -1,7 +1,7 @@
import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";
import type { NodeRuntimeHost } from "@hypit/runtime-host-node";
-import type { ParsedArgs } from "../arguments.js";
+import type { CliCommand, ExecutionCommand } from "../command.js";
import { buildObservationKey } from "../observation.js";
import type { CliIo } from "../output.js";
import type { CliRuntimeController } from "../runtime-port.js";
@@ -14,31 +14,32 @@ type OpenProjectResults = () => Promise<{
close(): void | Promise<void>;
}>;
-export function isExecutionCommand(args: ParsedArgs): boolean {
+export function isExecutionCommand(args: CliCommand): args is ExecutionCommand {
return args.command === "status" || args.command === "cancel" || args.command === "activity"
|| (args.command === "result" && (args.action === "finish" || args.action === "discard"));
}
/** Inspect or control accepted Build work. Observation never owns execution. */
export async function runExecutionCommand(input: {
- readonly args: ParsedArgs;
+ readonly args: ExecutionCommand;
+ readonly runtimeProfile: string | undefined;
readonly io: CliIo;
readonly runtimeHost: (profile: string) => Promise<NodeRuntimeHost>;
readonly runtimeController: (profile: string) => Promise<CliRuntimeController>;
readonly openProjectResults: OpenProjectResults;
readonly write: OperationalWriter;
}): Promise<void> {
- const { args, io, runtimeHost, runtimeController, openProjectResults, write } = input;
- if (args.command === "status" && args.runtime === undefined) {
+ const { args, runtimeProfile, io, runtimeHost, runtimeController, openProjectResults, write } = input;
+ if (args.command === "status" && runtimeProfile === undefined) {
const openedResults = await openProjectResults();
let result;
try {
- result = await openedResults.repository.read(args.file!);
+ result = await openedResults.repository.read(args.build);
} finally {
await openedResults.close();
}
if (args.watch && result?.outcome === undefined) {
- throw new Error(`Build ${args.file} has no finished Result; select its Runtime to observe active execution`);
+ throw new Error(`Build ${args.build} has no finished Result; select its Runtime to observe active execution`);
}
const finished = result?.outcome !== undefined;
const build = result === undefined ? null : buildStatusView({ id: result.id, result });
@@ -46,7 +47,7 @@ export async function runExecutionCommand(input: {
? "Build Result not found"
: finished ? "Build Result is finished" : "Build Result is unfinished",
result === undefined || !finished ? "warning" : "info", [
- ["Build", args.file!],
+ ["Build", args.build],
["Work", build?.work.state ?? "unknown"],
...(build?.work.outcome === undefined ? [] : [["Decision", build.work.outcome] as const]),
["Result", build?.result.state ?? "missing"],
@@ -58,19 +59,19 @@ export async function runExecutionCommand(input: {
return;
}
- if (args.runtime === undefined) {
+ if (runtimeProfile === undefined) {
throw new Error(`${args.command} requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>`);
}
- const selectedHost = await runtimeHost(args.runtime);
+ const selectedHost = await runtimeHost(runtimeProfile);
if (args.command === "result" && args.action === "discard") {
const resultControl = await selectedHost.openResultControl();
- const discarded = await resultControl.discardSubmission(args.file!)
+ const discarded = await resultControl.discardSubmission(args.build)
.finally(async () => await resultControl.close());
- write({ format: "hypit.cli-result-discard@2", build: args.file!, discarded }, discarded
+ write({ format: "hypit.cli-result-discard@2", build: args.build, discarded }, discarded
? "Incomplete Build discarded"
: "Incomplete Build not found", discarded ? "success" : "warning", [
- ["Build", args.file!],
+ ["Build", args.build],
["State", discarded ? "discarded" : "missing"],
], discarded ? ["The incomplete submission was removed."] : []);
if (!discarded) io.setExitCode?.(1);
@@ -80,7 +81,7 @@ export async function runExecutionCommand(input: {
const runtime = await selectedHost.openControl({ readOnly: args.command !== "cancel" });
try {
if (args.command === "activity") {
- const controller = await runtimeController(args.runtime);
+ const controller = await runtimeController(runtimeProfile);
let previous: string | undefined;
const writeActivity = async (): Promise<void> => {
const [activity, worker] = await Promise.all([
@@ -96,7 +97,7 @@ export async function runExecutionCommand(input: {
...(status.attention === undefined ? {} : { attention: status.attention }),
};
});
- const lanes = args.verbose ? summarizeQueueLanes(activity.capacity).slice(0, args.limit) : undefined;
+ const lanes = args.presentation.verbose ? summarizeQueueLanes(activity.capacity).slice(0, args.limit) : undefined;
const currentView = JSON.stringify({
worker: worker.state,
builds,
@@ -120,7 +121,7 @@ export async function runExecutionCommand(input: {
+ `${item.issue === undefined ? "" : ` · ${item.issue.message}`}`);
const activeOperations = activity.builds.flatMap((item) => item.operations)
.filter((item) => item.status === "pending");
- const operationLines = args.verbose
+ const operationLines = args.presentation.verbose
? activity.builds.flatMap((build) => build.operations.filter((item) => item.status === "pending")
.map((item) => `${build.id} · ${item.endpoint}: ${item.progress === undefined
? item.status
@@ -133,7 +134,7 @@ export async function runExecutionCommand(input: {
], [
...buildLines,
...(operationLines.length === 0 ? [] : ["Operations:", ...operationLines]),
- ...(args.verbose ? queueLaneLines(lanes ?? []) : []),
+ ...(args.presentation.verbose ? queueLaneLines(lanes ?? []) : []),
]);
};
if (!args.watch) await writeActivity();
@@ -145,7 +146,7 @@ export async function runExecutionCommand(input: {
}
if (args.command === "status") {
- let view = await runtime.inspect(args.file!);
+ let view = await runtime.inspect(args.build);
let result: BuildResultManifest | undefined;
let resultReadError: string | undefined;
let openedResults: Awaited<ReturnType<OpenProjectResults>> | undefined;
@@ -155,10 +156,10 @@ export async function runExecutionCommand(input: {
const startedAt = Date.now();
let delayMs = 100;
let previous: string | undefined;
- const controller = await runtimeController(args.runtime);
+ const controller = await runtimeController(runtimeProfile);
while (view !== undefined && view.issue === undefined) {
const encoded = buildObservationKey(view);
- if (encoded !== previous && !args.json) {
+ if (encoded !== previous && !args.presentation.json) {
previous = encoded;
io.write(` · ${view.id}: ${view.activity}`
+ `${view.operations.length === 0 ? "" : ` · ${view.operations.length} operation(s)`}\n`);
@@ -174,10 +175,10 @@ export async function runExecutionCommand(input: {
if (worker.state !== "running") break;
await new Promise((resolveWait) => setTimeout(resolveWait,
remaining === undefined ? delayMs : Math.min(delayMs, remaining)));
- view = await runtime.inspect(args.file!);
+ view = await runtime.inspect(args.build);
}
}
- result = await openedResults.repository.read(args.file!);
+ result = await openedResults.repository.read(args.build);
} catch (error) {
resultReadError = error instanceof Error ? error.message : String(error);
} finally {
@@ -192,7 +193,7 @@ export async function runExecutionCommand(input: {
...(view === undefined ? {} : { runtime: view }),
...(result === undefined ? {} : { result }),
...(resultReadError === undefined ? {} : { resultReadError }),
- verbose: args.verbose,
+ verbose: args.presentation.verbose,
operationLimit: args.limit,
});
write({ format: "hypit.cli-status@3", build }, !found
@@ -209,7 +210,7 @@ export async function runExecutionCommand(input: {
: outcome === "failed"
? "error"
: args.watch && activity !== undefined ? "warning" : "info", [
- ["Build", args.file!],
+ ["Build", args.build],
...(build?.title === undefined ? [] : [["Title", build.title] as const]),
["Work", build?.work.state ?? "unknown"],
...(build?.work.outcome === undefined ? [] : [["Decision", build.work.outcome] as const]),
@@ -229,58 +230,58 @@ export async function runExecutionCommand(input: {
}
if (args.command === "result") {
- const before = await runtime.inspect(args.file!);
+ const before = await runtime.inspect(args.build);
if (before !== undefined && before.activity !== "saving-result") {
- throw new Error(`Build ${args.file} is still ${before.activity}; there is no Result write to finish`);
+ throw new Error(`Build ${args.build} is still ${before.activity}; there is no Result write to finish`);
}
if (before !== undefined && before.issue === undefined) {
const worker = await (await selectedHost.controller()).worker.status();
if (worker.state === "running") {
- throw new Error(`Build ${args.file} Result is currently being written by the Runtime Worker`);
+ throw new Error(`Build ${args.build} Result is currently being written by the Runtime Worker`);
}
}
const resultControl = await selectedHost.openResultControl();
- const finished = await resultControl.finishResult(args.file!)
+ const finished = await resultControl.finishResult(args.build)
.finally(async () => await resultControl.close());
if (finished === undefined) {
const openedResults = await openProjectResults();
- const existing = await openedResults.repository.read(args.file!)
+ const existing = await openedResults.repository.read(args.build)
.finally(async () => await openedResults.close());
if (existing?.outcome === undefined) {
- write({ format: "hypit.cli-result-finish@2", build: args.file!, found: false },
- "Result cannot be finished", "warning", [["Build", args.file!]],
+ write({ format: "hypit.cli-result-finish@2", build: args.build, found: false },
+ "Result cannot be finished", "warning", [["Build", args.build]],
["No decided Result write exists for this Build."]);
io.setExitCode?.(1);
return;
}
- write({ format: "hypit.cli-result-finish@2", build: args.file!, outcome: existing.outcome },
- "Result already finished", "info", [["Build", args.file!], ["Outcome", existing.outcome]]);
+ write({ format: "hypit.cli-result-finish@2", build: args.build, outcome: existing.outcome },
+ "Result already finished", "info", [["Build", args.build], ["Outcome", existing.outcome]]);
return;
}
write({
format: "hypit.cli-result-finish@2",
- build: args.file!,
+ build: args.build,
outcome: finished.outcome,
...(finished.issue === undefined ? {} : { attention: {
message: finished.issue.message,
- action: `hypit result finish ${args.file}`,
+ action: `hypit result finish ${args.build}`,
} }),
}, finished.issue === undefined ? "Result finished" : "Result still needs attention",
finished.issue === undefined ? "success" : "error", [
- ["Build", args.file!],
+ ["Build", args.build],
["Outcome", finished.outcome],
], finished.issue === undefined ? [] : [`Attention ${finished.issue.message}`]);
if (finished.issue !== undefined) io.setExitCode?.(1);
return;
}
- const active = await runtime.cancel(args.file!, args.reason);
+ const active = await runtime.cancel(args.build, args.reason);
const openedResults = active === undefined ? await openProjectResults() : undefined;
const finished = openedResults === undefined
? undefined
- : await openedResults.repository.read(args.file!).finally(async () => await openedResults.close());
+ : await openedResults.repository.read(args.build).finally(async () => await openedResults.close());
const build = active === undefined && finished === undefined ? null : buildStatusView({
- id: args.file!,
+ id: args.build,
...(active === undefined ? {} : { runtime: active }),
...(finished === undefined ? {} : { result: finished }),
});
@@ -294,7 +295,7 @@ export async function runExecutionCommand(input: {
: active === undefined ? "Build already finished" : "Build cancellation requested";
write(machine, title,
active === undefined && finished === undefined ? "warning" : active === undefined ? "info" : "success", [
- ["Build", args.file!], ...(build === null ? [] : [["Work", build.work.state] as const]),
+ ["Build", args.build], ...(build === null ? [] : [["Work", build.work.state] as const]),
], active === undefined && finished?.outcome !== undefined
? [`No running work was changed; this Build is already ${finished.outcome}.`]
: []);
diff --git a/packages/cli/src/commands/results.ts b/packages/cli/src/commands/results.ts
index 97b4a7cd..8de22f34 100644
--- a/packages/cli/src/commands/results.ts
+++ b/packages/cli/src/commands/results.ts
@@ -2,7 +2,7 @@ import { resolve } from "node:path";
import type { BuildResultRepository } from "@hypit/build-result";
-import type { ParsedArgs } from "../arguments.js";
+import type { CliCommand, ProjectResultCommand } from "../command.js";
import { exportBuildResultOutput } from "../result-export.js";
import { browseBuildOutputHistory } from "../result-query.js";
import {
@@ -14,14 +14,14 @@ import {
} from "../view.js";
import type { OperationalWriter } from "./types.js";
-export function isProjectResultCommand(args: ParsedArgs): boolean {
+export function isProjectResultCommand(args: CliCommand): args is ProjectResultCommand {
return args.command === "builds" || args.command === "history" || args.command === "inspect"
|| args.command === "get" || (args.command === "result" && args.action === "edit");
}
/** Execute commands that need only project-owned Result history, never a Runtime. */
export async function runProjectResultCommand(input: {
- readonly args: ParsedArgs;
+ readonly args: ProjectResultCommand;
readonly projectRoot: string;
readonly repository: BuildResultRepository;
readonly write: OperationalWriter;
@@ -39,7 +39,7 @@ export async function runProjectResultCommand(input: {
outcome: manifest.outcome,
...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.path, projectRoot) }),
targetCount: manifest.targets.length,
- ...(args.verbose ? {
+ ...(args.presentation.verbose ? {
targets: manifest.targets.slice(0, args.limit),
...(manifest.targets.length <= args.limit ? {} : { omittedTargets: manifest.targets.length - args.limit }),
} : {}),
@@ -62,7 +62,7 @@ export async function runProjectResultCommand(input: {
const source = args.source === undefined ? undefined : resolve(args.source);
const page = await browseBuildOutputHistory(repository, {
projectRoot,
- output: args.file!,
+ output: args.outputName,
...(source === undefined ? {} : { source }),
...(args.before === undefined ? {} : { before: args.before }),
limit: args.limit,
@@ -72,32 +72,32 @@ export async function runProjectResultCommand(input: {
...(manifest.title === undefined ? {} : { title: manifest.title }),
createdAt: buildCreatedAtIso(manifest.id),
outcome: manifest.outcome,
- output: await outputView(repository, manifest, args.file!),
+ output: await outputView(repository, manifest, args.outputName),
})));
write({
format: "hypit.cli-history@4",
- output: args.file!,
+ output: args.outputName,
...(source === undefined ? {} : { source: projectPath(source, projectRoot) }),
entries,
...(page.next === undefined ? {} : { next: page.next }),
}, entries.length === 0 ? "No matching Output" : "Output history",
entries.length === 0 ? "warning" : "info", [
- ["Output", args.file!],
+ ["Output", args.outputName],
...(source === undefined ? [] : [["Source", projectPath(source, projectRoot)] as const]),
["Builds", String(entries.length)],
], entries.map((item) => {
const label = item.title === undefined ? item.build : `${item.title} · ${item.build}`;
return `${label}: ${item.outcome} · ${item.output.kind} · ${item.output.type} · ${item.createdAt}`;
- }).concat(page.next === undefined ? [] : [`Older hypit history ${args.file} --before ${page.next}`]));
+ }).concat(page.next === undefined ? [] : [`Older hypit history ${args.outputName} --before ${page.next}`]));
return;
}
if (args.command === "inspect") {
- const manifest = await repository.read(args.file!);
- if (manifest === undefined) throw new Error(`Build Result ${args.file} does not exist`);
+ const manifest = await repository.read(args.build);
+ if (manifest === undefined) throw new Error(`Build Result ${args.build} does not exist`);
const build = await buildResultView(repository, manifest, {
projectRoot,
- ...(args.output === undefined ? {} : { output: args.output }),
+ ...(args.outputName === undefined ? {} : { output: args.outputName }),
limit: args.limit,
});
write({ format: "hypit.cli-inspect@4", build }, "Build Result",
@@ -122,7 +122,7 @@ export async function runProjectResultCommand(input: {
}
if (args.command === "result") {
- const manifest = await repository.updatePresentation(args.file!, {
+ const manifest = await repository.updatePresentation(args.build, {
...(args.clearTitle ? { title: null } : args.title === undefined ? {} : { title: args.title }),
...(args.clearNote ? { note: null } : args.note === undefined ? {} : { note: args.note }),
...(args.clearHighlights
@@ -148,7 +148,7 @@ export async function runProjectResultCommand(input: {
return;
}
- const exported = await exportBuildResultOutput(repository, args.file!, args.output!, args.to!);
+ const exported = await exportBuildResultOutput(repository, args.build, args.outputName, args.destination);
const machine = {
format: "hypit.cli-get@4" as const,
build: exported.build,
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 618ac277..76f9700a 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -15,17 +15,12 @@ import type {
} from "./runtime-port.js";
import { writeCliHelp, writeCliOutput } from "./output.js";
import type { CliIo, CliMachineView } from "./output.js";
-import {
- assertCommandOptions,
- commandAllowsMissingPositional,
- isKnownCommand,
- parseArgs,
- usage,
-} from "./arguments.js";
+import { parseCommand } from "./arguments.js";
+import type { CliCommand } from "./command.js";
import { assertPreflight, createCatalogDescriptor, preflightPlan } from "./build-planning.js";
import { observeBuild } from "./observation.js";
import { isProjectResultCommand, runProjectResultCommand } from "./commands/results.js";
-import { runEnvironmentCommand } from "./commands/environment.js";
+import { isEnvironmentCommand, runEnvironmentCommand } from "./commands/environment.js";
import { isExecutionCommand, runExecutionCommand } from "./commands/execution.js";
import { inlineValuePreview } from "./runtime-view.js";
import { resolvePackageRoot } from "./project-context.js";
@@ -49,6 +44,18 @@ async function loadRuntime(host: NodeRuntimeHost): Promise<CliRuntime> {
return await host.createRuntime();
}
+function commandWorkspaceRoot(command: CliCommand): string | undefined {
+ return "workspaceRoot" in command ? command.workspaceRoot : undefined;
+}
+
+function commandPackageRoot(command: CliCommand): string | undefined {
+ return "packageRoot" in command ? command.packageRoot : undefined;
+}
+
+function commandRuntimeProfile(command: CliCommand): string | undefined {
+ return "runtimeProfile" in command ? command.runtimeProfile : undefined;
+}
+
export async function runCli(
argv: readonly string[],
io: CliIo,
@@ -59,16 +66,15 @@ export async function runCli(
writeCliHelp(io, topic);
return;
}
- let args = parseArgs(argv);
+ const args = parseCommand(argv);
let selectedRuntimeProjectRoot: string | undefined;
- const commandProjectRoot = (): string => args.workspaceRoot
+ const commandProjectRoot = (): string => commandWorkspaceRoot(args)
?? selectedRuntimeProjectRoot
?? ((args.command === "check" || args.command === "plan" || args.command === "build")
- && args.file !== undefined
- ? dirname(resolve(args.file))
+ ? dirname(resolve(args.source))
: process.cwd());
const packageRootForProject = async (projectRoot = commandProjectRoot()): Promise<string> =>
- args.packageRoot ?? await resolvePackageRoot(projectRoot);
+ commandPackageRoot(args) ?? await resolvePackageRoot(projectRoot);
const writeOperational = (
machine: CliMachineView,
title: string,
@@ -76,10 +82,7 @@ export async function runCli(
facts: readonly (readonly [string, string])[] = [],
lines: readonly string[] = [],
): void => writeCliOutput(io, {
- json: args.json || args.jsonl,
- jsonl: args.jsonl,
- color: args.color,
- verbose: args.verbose,
+ ...args.presentation,
}, { kind: "operational", machine, title, status, facts, lines });
const runtimeHosts = new Map<string, Promise<NodeRuntimeHost>>();
const runtimeHost = async (path: string, requestedPackageRoot?: string): Promise<NodeRuntimeHost> => {
@@ -106,22 +109,14 @@ export async function runCli(
});
};
if (args.command === "_worker") {
- if (args.file === undefined || args.readyFile === undefined || args.workerOwner === undefined) {
- throw new Error("internal Worker launch is incomplete");
- }
await (await runtimeHost(
- args.file,
+ args.profile,
args.packageRoot ?? await packageRootForProject(),
)).runWorker(args.readyFile, args.workerOwner);
return;
}
if (args.command === "runtime" && args.action === "use") {
- if (args.runtime !== undefined) {
- throw new Error("runtime use takes the Runtime Profile positionally, not through --runtime");
- }
- if (args.file === undefined) throw new Error("runtime use requires a Runtime Profile");
- assertCommandOptions(args);
- const profile = resolve(args.file);
+ const profile = resolve(args.profile);
const selected = await selectRuntimeProfile(args.workspaceRoot ?? process.cwd(), profile);
writeOperational({
format: "hypit.cli-runtime-selection@2",
@@ -135,10 +130,6 @@ export async function runCli(
return;
}
if (args.command === "runtime" && args.action === "unset") {
- if (args.file !== undefined || args.runtime !== undefined) {
- throw new Error("runtime unset does not take a Runtime Profile");
- }
- assertCommandOptions(args);
const cleared = await clearRuntimeProfile(args.workspaceRoot ?? process.cwd());
writeOperational({
format: "hypit.cli-runtime-selection@2",
@@ -152,57 +143,24 @@ export async function runCli(
return;
}
- const positionalRuntime = (args.command === "runtime" || args.command === "programs"
- || args.command === "doctor") && args.file !== undefined;
- const runtimeWasExplicit = args.runtime !== undefined || positionalRuntime;
+ let runtimeProfile = commandRuntimeProfile(args);
+ const runtimeWasExplicit = runtimeProfile !== undefined;
let runtimeNeedsHint = runtimeWasExplicit;
- if (args.runtime === undefined && !positionalRuntime) {
+ if (runtimeProfile === undefined) {
const sourceScoped = args.command === "check" || args.command === "plan" || args.command === "build";
- const start = args.workspaceRoot
- ?? (sourceScoped && args.file !== undefined ? dirname(resolve(args.file)) : process.cwd());
+ const start = commandWorkspaceRoot(args)
+ ?? (sourceScoped ? dirname(resolve(args.source)) : process.cwd());
const selected = await findRuntimeProfile(start);
if (selected !== undefined) {
- args = { ...args, runtime: selected.profile };
+ runtimeProfile = selected.profile;
selectedRuntimeProjectRoot = selected.projectRoot;
const cwdFromProject = relative(selected.projectRoot, resolve(process.cwd()));
runtimeNeedsHint = cwdFromProject === ".." || cwdFromProject.startsWith(`..${sep}`)
|| isAbsolute(cwdFromProject);
}
}
- if (!isKnownCommand(args.command)
- || (!commandAllowsMissingPositional(args.command) && args.file === undefined)) {
- throw new Error(usage());
- }
- if (args.watch && args.command !== "activity" && args.command !== "status") {
- throw new Error("--watch applies only to status or activity");
- }
- if (args.jsonl && (args.command !== "activity" || !args.watch)) {
- throw new Error("--jsonl applies only to activity --watch");
- }
- if (args.command === "activity" && args.watch && args.json) {
- throw new Error("activity --watch is a stream; use --jsonl instead of --json");
- }
- if (args.command === "history" && args.file === undefined) {
- throw new Error("history requires one exact Output name");
- }
- if (args.command === "result" && args.action !== "finish"
- && args.action !== "discard" && args.action !== "edit") {
- throw new Error("result accepts finish, discard or edit");
- }
- if (args.command === "result" && args.action === "edit") {
- if (args.title !== undefined && args.clearTitle) throw new Error("--title and --clear-title are mutually exclusive");
- if (args.note !== undefined && args.clearNote) throw new Error("--note and --clear-note are mutually exclusive");
- if (args.highlightedOutputs.length > 0 && args.clearHighlights) {
- throw new Error("--highlight and --clear-highlights are mutually exclusive");
- }
- if (args.title === undefined && args.note === undefined && args.highlightedOutputs.length === 0
- && !args.clearTitle && !args.clearNote && !args.clearHighlights) {
- throw new Error("result edit requires a presentation change");
- }
- }
- assertCommandOptions(args);
const runtimeController = async (profile: string, source?: string): Promise<CliRuntimeController> => {
- const workspaceRoot = args.workspaceRoot
+ const workspaceRoot = commandWorkspaceRoot(args)
?? selectedRuntimeProjectRoot
?? (source === undefined ? process.cwd() : dirname(resolve(source)));
const packageRoot = await packageRootForProject(workspaceRoot);
@@ -210,16 +168,20 @@ export async function runCli(
packageRoot,
});
};
- if (await runEnvironmentCommand({
- args,
- io,
- distribution,
- projectRoot: args.command === "paths" ? selectedRuntimeProjectRoot ?? process.cwd() : commandProjectRoot(),
- packageRootForProject,
- runtimeHost,
- runtimeController,
- write: writeOperational,
- })) return;
+ if (isEnvironmentCommand(args)) {
+ await runEnvironmentCommand({
+ args,
+ runtimeProfile,
+ io,
+ distribution,
+ projectRoot: args.command === "paths" ? selectedRuntimeProjectRoot ?? process.cwd() : commandProjectRoot(),
+ packageRootForProject,
+ runtimeHost,
+ runtimeController,
+ write: writeOperational,
+ });
+ return;
+ }
if (isProjectResultCommand(args)) {
const results = await projectResults();
try {
@@ -237,6 +199,7 @@ export async function runCli(
if (isExecutionCommand(args)) {
await runExecutionCommand({
args,
+ runtimeProfile,
io,
runtimeHost,
runtimeController,
@@ -245,20 +208,20 @@ export async function runCli(
});
return;
}
- const runtimePaths = args.runtime === undefined
+ const runtimePaths = runtimeProfile === undefined
? undefined
- : await (await runtimeHost(args.runtime)).resolvePaths();
+ : await (await runtimeHost(runtimeProfile)).resolvePaths();
const effectivePackageRoot = args.packageRoot ?? runtimePaths?.packageRoot;
const effectiveWorkspaceRoot = args.workspaceRoot
?? selectedRuntimeProjectRoot
- ?? dirname(resolve(args.file!));
+ ?? dirname(resolve(args.source));
const projectResultsRoot = effectiveWorkspaceRoot;
const sourcePackageRoot = effectivePackageRoot
?? await resolvePackageRoot(effectiveWorkspaceRoot);
const loadedPackageSet = distribution.discoverSourcePackages === undefined
? undefined
: await loadDiscoveredSourcePackages(distribution, {
- source: args.file!,
+ source: args.source,
...(effectiveWorkspaceRoot === undefined ? {} : { workspaceRoot: effectiveWorkspaceRoot }),
packageRoot: sourcePackageRoot,
...(distribution.packageRoot === undefined
@@ -273,7 +236,7 @@ export async function runCli(
...(args.assetRoots.length === 0 ? {} : { assetRoots: args.assetRoots }),
packageContributions,
});
- const workspace = await compiler.openFile(args.file!);
+ const workspace = await compiler.openFile(args.source);
const sourceHeader = parseSourceHeader(workspace.entry.name, workspace.entry.text);
const runMode = runFrontends.some((frontend) => frontend.id === sourceHeader.using);
const authorMode = compiler.supportsFrontend(sourceHeader.using);
@@ -320,7 +283,7 @@ export async function runCli(
omittedHistoricalOutputs: loaded.unresolvedHistoricalOutputs.length - args.limit,
}),
} as const;
- writeCliOutput(io, args, {
+ writeCliOutput(io, args.presentation, {
kind: "check-run",
machine,
});
@@ -345,12 +308,12 @@ export async function runCli(
outputCount: outputs.length,
outputs: outputs.slice(0, args.limit).map((item) => ({ name: item.name, type: cliTypeName(item.type) })),
...(outputs.length <= args.limit ? {} : { omittedOutputs: outputs.length - args.limit }),
- ...(args.verbose ? { details: {
+ ...(args.presentation.verbose ? { details: {
modules: modules.slice(0, args.limit),
values: values.slice(0, args.limit).map((item) => ({ name: item.name, type: cliTypeName(item.type) })),
} } : {}),
} as const;
- writeCliOutput(io, args, {
+ writeCliOutput(io, args.presentation, {
kind: "check-author",
machine,
});
@@ -358,7 +321,7 @@ export async function runCli(
}
}
if (args.command === "build") {
- if (args.runtime === undefined) {
+ if (runtimeProfile === undefined) {
throw new Error("build requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>");
}
const buildResults = await projectResults(projectResultsRoot);
@@ -411,10 +374,10 @@ export async function runCli(
catalog.publishedOutputs.some((published) => published.ref.id === forward.output)),
},
} as const;
- const controller = await (await runtimeHost(args.runtime)).controller({
+ const controller = await (await runtimeHost(runtimeProfile)).controller({
packageRoot: sourcePackageRoot,
});
- const preflight = await preflightPlan(await runtimeHost(args.runtime), result.state);
+ const preflight = await preflightPlan(await runtimeHost(runtimeProfile), result.state);
// Build is an execution boundary, not a provisioning command. The cheap
// preflight must already be clean; `runtime up` is the explicit place for
// installing or starting declared programs.
@@ -427,21 +390,21 @@ export async function runCli(
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`Runtime Worker could not start; no Build was queued: ${detail}`);
}
- runtime = await loadRuntime(await runtimeHost(args.runtime));
+ runtime = await loadRuntime(await runtimeHost(runtimeProfile));
let built = await runtime.build(request);
if (args.follow && runtime !== undefined) {
built = await observeBuild(runtime, built, {
...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
controller,
readResult: async () => await buildResults.repository.read(built.id),
- ...(args.json || args.jsonl ? {} : {
+ ...(args.presentation.json ? {} : {
onProgress: (progress) => {
const operations = Object.entries(progress.operations)
.map(([status, count]) => `${count} ${status}`)
.join(", ");
io.write(` · ${progress.phase}`
+ `${operations.length === 0 ? "" : ` · ${operations}`}\n`);
- if (args.verbose) {
+ if (args.presentation.verbose) {
for (const line of progress.activity.slice(0, args.limit)) io.write(` ${line}\n`);
}
},
@@ -478,7 +441,7 @@ export async function runCli(
id: built.id,
...(activeView === undefined ? {} : { runtime: activeView }),
...(finishedResult === undefined ? {} : { result: finishedResult }),
- verbose: args.verbose,
+ verbose: args.presentation.verbose,
operationLimit: args.limit,
});
const machine = {
@@ -487,7 +450,7 @@ export async function runCli(
? buildView
: { ...buildView, title: args.title },
};
- const runtimeHint = runtimeNeedsHint ? ` --runtime ${args.runtime}` : "";
+ const runtimeHint = runtimeNeedsHint ? ` --runtime ${runtimeProfile}` : "";
const resultTargets = finishedResult?.targets.flatMap((name) => {
const output = finishedResult.outputs[name];
return output === undefined ? [] : [{ name, output }];
@@ -551,9 +514,9 @@ export async function runCli(
results: planResults.repository,
});
const result = loaded.compiler.planCompilation(loaded);
- const preflight = args.runtime === undefined
+ const preflight = runtimeProfile === undefined
? undefined
- : await preflightPlan(await runtimeHost(args.runtime), result.state);
+ : await preflightPlan(await runtimeHost(runtimeProfile), result.state);
const outputNames = Object.fromEntries(result.compilation.author.exports.flatMap((item) =>
item.ref.kind === "logical-output" ? [[item.ref.id, item.name]] : []));
const externalRequests = new Map<string, number>();
@@ -573,7 +536,7 @@ export async function runCli(
const requestViews = [...externalRequests.entries()].sort(([left], [right]) => left.localeCompare(right))
.map(([operation, count]) => ({ operation, count }));
const targets = loaded.run.document.targets.map((item) => item.output);
- writeCliOutput(io, args, {
+ writeCliOutput(io, args.presentation, {
kind: "plan",
machine: {
format: "hypit.cli-plan@2",