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): expose bounded semantic views

kashorin1e355a802fef
diff --git a/docs/quickstart/run.md b/docs/quickstart/run.md
index 299b9d68..14544db0 100644
--- a/docs/quickstart/run.md
+++ b/docs/quickstart/run.md
@@ -134,12 +134,13 @@ Query an output name across the project's local Build Results:
hypit history hook-take.video
```
-`history` reports only public Author Outputs that the Build actually produced. It does not list
-declared-but-unbuilt outputs or internal Operation values. If the old name is unknown, list Outputs
-from Results whose manifest names the exact Author Source path:
+`history` reports only the exact public Author Output requested. It does not list
+declared-but-unbuilt outputs or internal Operation values. If the old name is unknown, browse Builds
+and inspect the likely Result:
```bash
-hypit history --source ./main.svml
+hypit builds
+hypit inspect <build-id>
```
An output name is a human locator inside one Build Result. The pair `build + output` is the exact
@@ -366,8 +367,8 @@ and the same external task checkpoints; it never turns another invocation into t
hypit inspect <build-id>
```
-`inspect` reads the project-owned Result directly and lists final Targets plus every completed
-public Output saved along their execution route:
+`inspect` reads the project-owned Result directly and shows its Targets plus a bounded list of
+completed public Outputs. Use `--output <name>` for one exact Output or `--limit <count>` to show more:
```bash
hypit get <build-id> \
diff --git a/docs/zh/quickstart/run.md b/docs/zh/quickstart/run.md
index 9648d589..25be4609 100644
--- a/docs/zh/quickstart/run.md
+++ b/docs/zh/quickstart/run.md
@@ -120,10 +120,11 @@ Hypit 没有隐式缓存。复用结果是显式的运行图编写:把某个
hypit history hook-take.video
```
-`history` 只列出该 Build 确实完成的公开 Author Output。只声明但没有运行出来的输出和内部 Operation 值不会混入结果。如果忘了旧名字,可以按 Result 里记录的精确 Author Source 路径查询:
+`history` 只查询明确给出的那个公开 Author Output。只声明但没有运行出来的输出和内部 Operation 值不会混入结果。如果忘了旧名字,先浏览 Build,再检查可能的 Result:
```bash
-hypit history --source ./main.svml
+hypit builds
+hypit inspect <build-id>
```
输出名是某个 Build Result 内供人查找的名字;`build + output` 这对地址已经足够精确。假如当前源码把 `hook-take.video` 改名为 `opening-shot.video`,`<build-record>` 仍写历史旧名,`<satisfy>` 写当前新名:
@@ -356,7 +357,8 @@ hypit status <build-id> --watch
hypit inspect <build-id>
```
-`inspect` 直接读取项目里的 Build Result,列出最终 Target,以及通向它们的路线上实际完成的所有公开 Output:
+`inspect` 直接读取项目里的 Build Result,列出最终 Target 和一页实际完成的公开 Output;用
+`--output <name>` 精确查看一个 Output,或用 `--limit <count>` 增加显示数量:
```bash
hypit get <build-id> \
diff --git a/packages/cli/README.md b/packages/cli/README.md
index d4e5350f..82bde8b4 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -11,5 +11,6 @@ Source imports decide which language and component packages give the source mean
Profile separately selects the Host and environment packages allowed to execute work. The CLI does
not invent targets, candidates or provider choices.
-Human output is compact by default. `--verbose` expands details and `--json` emits machine readable
-results without presentation text.
+Human output is compact by default. `--json` emits a stable, bounded command view rather than raw
+compiler, Runtime or Repository objects. `--verbose` adds bounded operational detail; it never turns
+the command into an internal state dump.
diff --git a/packages/cli/src/distribution.ts b/packages/cli/src/distribution.ts
index 14fa0449..7d0b1893 100644
--- a/packages/cli/src/distribution.ts
+++ b/packages/cli/src/distribution.ts
@@ -13,34 +13,6 @@ export type CliCompilerOptions = {
readonly packageContributions: readonly NodePackageContribution[];
};
-/**
- * One picture asked for directly, with no Source, Build, Record or Runtime Profile.
- *
- * A component package's own chrome — a paper texture, a board, a panel — is authoring
- * input that ships inside the package, so it is never anybody's Output. Credentials are
- * the only thing this needs.
- */
-export type CliPictureRequest = {
- /** Installed package specifier naming the exact model family; the Distribution defaults it. */
- readonly model?: string;
- readonly prompt: string;
- readonly aspectRatio?: string;
- readonly resolution?: string;
- /** Project package root; the Distribution remains a separate read-only resolution root. */
- readonly packageRoot: string;
- /** Read-only packages shipped by the active Distribution. */
- readonly distributionPackageRoot?: string;
-};
-
-export type CliPicture = {
- /** Installed package specifier that declared the exact model. */
- readonly package: string;
- /** Exact model name, as the model package declares it. */
- readonly model: string;
- readonly mediaType: string;
- readonly bytes: Uint8Array;
-};
-
/**
* Explicit application assembly for the generic command engine.
*
@@ -90,12 +62,4 @@ export type CliDistribution = {
readonly location?: BuildResultRepositoryLocation;
readonly diagnostics: readonly BuildResultRepositoryDiagnostic[];
}>;
- /**
- * Generate one picture for a package asset.
- *
- * Which exact models exist is a model package's declaration and which Provider fulfils
- * them is this Distribution's choice, so both stay here. The generic engine only reads
- * the prompt, writes the file and reports where it went.
- */
- generatePicture?(request: CliPictureRequest): Promise<CliPicture>;
};
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index f4c868ae..61778ab4 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,5 +1,3 @@
-export { pinnedRecords } from "./reuse-markup.js";
-export type { PinnedRecord } from "./reuse-markup.js";
export { runCli } from "./main.js";
export { discoverSourcePackages } from "./source-discovery.js";
export { loadDiscoveredSourcePackages } from "./source-packages.js";
@@ -11,14 +9,20 @@ export { renderCliError, writeCliHelp, writeCliOutput } from "./output.js";
export type {
CliColorMode,
CliIo,
+ CliMachineView,
CliOutputOptions,
CliPresentation,
CliTerminal,
} from "./output.js";
+export type {
+ CliBuildResultView,
+ CliBuildStatusView,
+ CliBuildSummary,
+ CliOutputView,
+ PublicOutputKind,
+} from "./view.js";
export type {
CliCompilerOptions,
CliDistribution,
- CliPicture,
- CliPictureRequest,
} from "./distribution.js";
export type * from "./runtime-port.js";
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 1375f278..ce3a4494 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -1,10 +1,9 @@
import { createHash, randomBytes } from "node:crypto";
import { createServer } from "node:http";
import { spawn } from "node:child_process";
-import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
-import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { readFile, stat } from "node:fs/promises";
-import { deterministicSpeechDurations, deterministicSpeechDurationsFromGraph } from "@hypit/compiler-node";
import { FileBuildResultRepository } from "@hypit/build-result";
import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";
import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";
@@ -16,11 +15,10 @@ import {
} from "@hypit/runtime-host-node";
import { plannedNeeds } from "@hypit/runtime";
import type { BuildCatalogDescriptor, CapacityReservation, OperationProgress } from "@hypit/runtime";
-import { buildIdCreatedAt, orderedBuildId } from "@hypit/protocol";
-import type { BuildState, CapabilityRef, TypeRef } from "@hypit/protocol";
+import { orderedBuildId } from "@hypit/protocol";
+import type { BuildState, CapabilityRef } from "@hypit/protocol";
import { parseSourceHeader } from "@hypit/source";
-import { pinnedRecords } from "./reuse-markup.js";
import { unreachedGenerations } from "./reachability.js";
import { typecheckProjectPackages } from "./package-typecheck.js";
import { checkRunFile, collectRunFrontends, loadRunFile } from "./run-file.js";
@@ -28,13 +26,12 @@ import type { CliDistribution } from "./distribution.js";
import type {
CliBuildSubmission,
CliManagedProgramProgress,
- CliManagedProgramReport,
CliRuntime,
CliRuntimeControl,
CliRuntimeController,
} from "./runtime-port.js";
import { writeCliHelp, writeCliOutput } from "./output.js";
-import type { CliColorMode, CliIo } from "./output.js";
+import type { CliColorMode, CliIo, CliMachineView } from "./output.js";
import { exportBuildResultOutput } from "./result-export.js";
import { hypitHostStateRoot, hypitProjectStateRoot } from "./paths.js";
import { loadDiscoveredSourcePackages } from "./source-packages.js";
@@ -43,6 +40,14 @@ import {
findRuntimeProfile,
selectRuntimeProfile,
} from "./runtime-selection.js";
+import {
+ buildCreatedAtIso,
+ buildResultView,
+ buildStatusView,
+ cliTypeName,
+ outputView,
+ projectPath,
+} from "./view.js";
type ParsedArgs = {
readonly command: string | undefined;
@@ -56,10 +61,6 @@ type ParsedArgs = {
readonly packageRoot: string | undefined;
readonly runtime: string | undefined;
readonly follow: boolean;
- /** Emit Run Source markup that reuses these Outputs instead of listing them. */
- readonly pin: boolean;
- /** Omit this Build's requested Targets from history and generated pin markup. */
- readonly excludeTargets: boolean;
readonly maxWaitMs: number | undefined;
readonly output: string | undefined;
readonly title: string | undefined;
@@ -69,14 +70,9 @@ type ParsedArgs = {
readonly clearNote: boolean;
readonly clearHighlights: boolean;
readonly limit: number;
+ readonly lines: number;
readonly before: string | undefined;
readonly to: string | undefined;
- /** Prompt text, or the path of a text file holding it. */
- readonly prompt: string | undefined;
- /** Installed package specifier naming the exact model family. */
- readonly model: string | undefined;
- readonly aspectRatio: string | undefined;
- readonly resolution: string | undefined;
readonly json: boolean;
readonly color: CliColorMode;
readonly verbose: boolean;
@@ -107,12 +103,6 @@ function createPublicBuildId(now = Date.now()): string {
return orderedBuildId(now, randomBytes(5).toString("hex").toUpperCase());
}
-function buildCreatedAt(build: string): number {
- const createdAt = buildIdCreatedAt(build);
- if (createdAt === undefined) throw new Error(`Build id ${build} has no submission time`);
- return createdAt;
-}
-
async function hypiHubOAuthLogin(io: CliIo): Promise<string> {
const verifier = base64url(randomBytes(32));
const challenge = base64url(createHash("sha256").update(verifier).digest());
@@ -299,8 +289,7 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
|| command === "packages";
const action = scoped ? tail[0] : undefined;
const positional = scoped ? tail.slice(1) : tail;
- const noFile = command === "builds" || command === "activity" || command === "paths"
- || command === "image";
+ 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);
@@ -309,8 +298,6 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
let packageRoot: string | undefined;
let runtime: string | undefined;
let follow = false;
- let pin = false;
- let excludeTargets = false;
let maxWaitMs: number | undefined;
let output: string | undefined;
let title: string | undefined;
@@ -320,12 +307,9 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
let clearNote = false;
let clearHighlights = false;
let limit = 20;
+ let lines = 50;
let before: string | undefined;
let to: string | undefined;
- let prompt: string | undefined;
- let model: string | undefined;
- let aspectRatio: string | undefined;
- let resolution: string | undefined;
let json = false;
let color: CliColorMode = "auto";
let verbose = false;
@@ -459,6 +443,14 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
index += 1;
continue;
}
+ if (item === "--lines") {
+ const value = rest[index + 1];
+ if (value === undefined || value.startsWith("--")) throw new Error("--lines requires a positive integer");
+ lines = Number(value);
+ if (!Number.isSafeInteger(lines) || lines < 1) throw new Error("--lines requires a positive integer");
+ index += 1;
+ continue;
+ }
if (item === "--before") {
const value = rest[index + 1];
if (value === undefined || value.startsWith("--")) throw new Error("--before requires a Build id");
@@ -473,46 +465,10 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
index += 1;
continue;
}
- if (item === "--prompt") {
- const value = rest[index + 1];
- if (value === undefined || value.startsWith("--")) throw new Error("--prompt requires text or a text file path");
- prompt = value;
- index += 1;
- continue;
- }
- if (item === "--model") {
- const value = rest[index + 1];
- if (value === undefined || value.startsWith("--")) throw new Error("--model requires an installed package specifier");
- model = value;
- index += 1;
- continue;
- }
- if (item === "--aspect-ratio") {
- const value = rest[index + 1];
- if (value === undefined || value.startsWith("--")) throw new Error("--aspect-ratio requires a ratio the model accepts");
- aspectRatio = value;
- index += 1;
- continue;
- }
- if (item === "--resolution") {
- const value = rest[index + 1];
- if (value === undefined || value.startsWith("--")) throw new Error("--resolution requires a resolution the model accepts");
- resolution = value;
- index += 1;
- continue;
- }
if (item === "--follow") {
follow = true;
continue;
}
- if (item === "--pin") {
- pin = true;
- continue;
- }
- if (item === "--exclude-targets") {
- excludeTargets = true;
- continue;
- }
if (item === "--max-wait-ms") {
const value = rest[index + 1];
if (value === undefined || value.startsWith("--")) throw new Error("--max-wait-ms requires milliseconds");
@@ -576,8 +532,6 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
packageRoot,
runtime,
follow,
- pin,
- excludeTargets,
maxWaitMs,
output,
title,
@@ -587,12 +541,9 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
clearNote,
clearHighlights,
limit,
+ lines,
before,
to,
- prompt,
- model,
- aspectRatio,
- resolution,
json,
color,
verbose,
@@ -616,20 +567,23 @@ function assertCommandOptions(args: ParsedArgs): void {
case "programs":
// This command has older, more specific diagnostics for deployment-selection
// flags and waiting on status/down; let its handler render those repairs.
- add("--max-wait-ms", "--runtime");
+ add("--max-wait-ms", "--runtime", "--limit");
break;
case "runtime":
add("--runtime");
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");
+ add("--runtime", "--watch", "--jsonl", "--limit");
break;
case "paths":
add("--runtime");
@@ -637,41 +591,37 @@ function assertCommandOptions(args: ParsedArgs): void {
case "get":
add("--workspace", "--output", "--to");
break;
- case "image":
- // A package asset needs credentials and nothing else; no Runtime Profile applies.
- add("--prompt", "--to", "--model", "--aspect-ratio", "--resolution");
- 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");
+ add("--workspace", "--title", "--note", "--highlight", "--clear-title", "--clear-note", "--clear-highlights", "--limit");
}
break;
case "doctor":
- add("--workspace");
+ add("--workspace", "--limit");
break;
case "status":
- add("--runtime", "--watch");
+ 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", "--pin", "--exclude-targets");
+ if (args.command === "history") add("--source");
break;
case "inspect":
- add("--workspace");
+ add("--workspace", "--output", "--limit");
break;
case "check":
case "plan":
- add("--runtime", "--package-root", "--workspace", "--asset-root");
+ add("--runtime", "--package-root", "--workspace", "--asset-root", "--limit");
break;
case "build":
add("--runtime", "--package-root", "--workspace", "--asset-root", "--follow",
- "--max-wait-ms", "--title");
+ "--max-wait-ms", "--title", "--limit");
break;
}
const invalid = args.seenOptions.find((item) => !allowed.has(item));
@@ -692,49 +642,12 @@ function assertCommandOptions(args: ParsedArgs): void {
function usage(): string {
return [
- "usage:",
- " hypit doctor [<runtime-profile>] [--workspace project]",
- " hypit programs up|down|status [<runtime-profile>] [--max-wait-ms milliseconds]",
- " hypit runtime use <runtime-profile>",
- " hypit runtime unset",
- " hypit runtime up|status|logs|down [<runtime-profile>]",
- " hypit packages install|status <package@exact-version>",
- " hypit activity [--runtime profile.json] [--watch]",
- " hypit check <self-described-source> [--runtime profile.json] [--workspace workspace] [--asset-root directory]",
- " hypit plan <run-source> [--runtime profile.json] [--workspace workspace] [--asset-root directory]",
- " hypit build <run-source> [--title text] [--runtime profile.json] [--workspace workspace] [--asset-root directory] [--follow]",
- " hypit status <build-id> [--runtime profile.json] [--watch]",
- " hypit result finish <build-id> [--runtime profile.json]",
- " hypit result discard <build-id> [--runtime profile.json]",
- " hypit result edit <build-id> [--title text] [--note text] [--highlight output] [--workspace project]",
- " hypit builds [--workspace project] [--limit count] [--before build-id]",
- " hypit history [output-name] [--workspace project] [--source author.svml] [--limit count] [--before build-id] [--pin] [--exclude-targets]",
- " hypit inspect <build-id> [--workspace project]",
- " hypit get <build-id> --output output-name --to path [--workspace project]",
- " hypit cancel <build-id> [--runtime profile.json] [--reason text]",
- " hypit auth status|login|logout <endpoint-instance> [--runtime profile.json] [--slot name] [--from secret-file]",
- " hypit image --prompt <text|text-file> --to <path.png> [--model package] [--aspect-ratio r] [--resolution r]",
+ "usage: hypit <command> [options]",
"",
- "output:",
- " --json --verbose --color auto|always|never --no-color --debug",
+ "Run `hypit help` for commands or `hypit help <command>` for exact syntax.",
].join("\n");
}
-/**
- * A prompt is either the text itself or a file holding it. A long prompt lives in a file
- * beside the asset it describes, so it can be edited and reread; a short one does not
- * deserve a file.
- */
-async function readPromptText(value: string): Promise<string> {
- const path = resolve(value);
- const isFile = await stat(path).then((item) => item.isFile(), () => false);
- const prompt = (isFile ? await readFile(path, "utf8") : value).trim();
- if (prompt.length === 0) {
- throw new Error(isFile ? `prompt file ${path} is empty` : "--prompt is empty");
- }
- return prompt;
-}
-
function createCatalogDescriptor(options: {
readonly source: string;
readonly compilation: NodeCompiledSourceClosure;
@@ -784,7 +697,6 @@ async function preflightPlan(
const result = await host.preflight({ capabilities });
return {
ok: !result.diagnostics.some((item) => item.severity === "error"),
- dataRoot: result.dataRoot,
capabilities: capabilities.map(capabilityName),
diagnostics: result.diagnostics,
} as const;
@@ -813,10 +725,6 @@ async function loadRuntimeControl(
return await host.openControl({ readOnly });
}
-function displayType(type: TypeRef): string {
- return `${type.module.name}@${type.module.version}/${type.name}`;
-}
-
function formatOperationProgress(progress: OperationProgress): string {
if (progress.completed === undefined) return progress.phase;
const amount = progress.total === undefined
@@ -861,16 +769,6 @@ function queueLaneLines(groups: readonly QueueLaneSummary[]): readonly string[]
return lines;
}
-function programLine(program: CliManagedProgramReport): string {
- const stateDetail = "detail" in program.state ? ` — ${program.state.detail}` : "";
- const action = program.action === undefined ? "" : ` · ${program.action}`;
- const detail = program.detail === undefined ? "" : ` · ${program.detail}`;
- const instances = program.instances.length === 0 ? "" : ` · ${program.instances.join(", ")}`;
- const pid = program.pid === undefined ? "" : ` · pid ${program.pid}`;
- const log = program.logPath === undefined ? "" : ` · log ${program.logPath}`;
- return `${program.id}: ${program.state.state}${stateDetail}${action}${detail}${instances}${pid}${log}`;
-}
-
function inlineValuePreview(value: unknown, limit = 240): string {
const encoded = JSON.stringify(value);
if (encoded.length <= limit) return encoded;
@@ -1008,7 +906,7 @@ export async function runCli(
const packageRootForProject = async (projectRoot = commandProjectRoot()): Promise<string> =>
args.packageRoot ?? await resolvePackageRoot(projectRoot);
const writeOperational = (
- machine: unknown,
+ machine: CliMachineView,
title: string,
status: "success" | "warning" | "error" | "info" = "info",
facts: readonly (readonly [string, string])[] = [],
@@ -1090,10 +988,10 @@ export async function runCli(
const profile = resolve(args.file);
const selected = await selectRuntimeProfile(args.workspaceRoot ?? process.cwd(), profile);
writeOperational({
- format: "hypit.cli-runtime-selection@1",
+ format: "hypit.cli-runtime-selection@2",
+ selected: true,
profile: selected.profile,
project: selected.projectRoot,
- selectionFile: selected.selectionFile,
}, "Runtime selected", "success", [
["Profile", selected.profile],
["Project", selected.projectRoot],
@@ -1107,11 +1005,10 @@ export async function runCli(
assertCommandOptions(args);
const cleared = await clearRuntimeProfile(process.cwd());
writeOperational({
- format: "hypit.cli-runtime-selection@1",
+ format: "hypit.cli-runtime-selection@2",
selected: false,
removed: cleared !== undefined,
- profile: cleared?.profile,
- project: cleared?.projectRoot,
+ ...(cleared === undefined ? {} : { profile: cleared.profile, project: cleared.projectRoot }),
}, cleared === undefined ? "No Runtime was selected" : "Runtime selection removed",
cleared === undefined ? "info" : "success", cleared === undefined ? [] : [
["Profile", cleared.profile], ["Project", cleared.projectRoot],
@@ -1142,10 +1039,10 @@ export async function runCli(
|| args.command === "result"
|| args.command === "doctor" || args.command === "programs"
|| args.command === "runtime" || args.command === "activity" || args.command === "paths"
- || args.command === "image" || args.command === "packages";
+ || args.command === "packages";
const operational = known || args.command === "auth";
const fileOptional = args.command === "builds" || args.command === "history" || args.command === "activity"
- || args.command === "paths" || args.command === "image"
+ || args.command === "paths"
|| args.command === "programs" || args.command === "runtime" || args.command === "doctor";
if (!operational || (!fileOptional && args.file === undefined)) {
throw new Error(usage());
@@ -1159,8 +1056,8 @@ export async function runCli(
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 && args.source === undefined) {
- throw new Error("history requires an output name or --source path");
+ 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") {
@@ -1178,9 +1075,6 @@ export async function runCli(
}
}
assertCommandOptions(args);
- if (args.excludeTargets && !args.pin) {
- throw new Error("--exclude-targets requires history --pin");
- }
const runtimeController = async (profile: string, source?: string): Promise<CliRuntimeController> => {
const workspaceRoot = args.workspaceRoot
?? selectedRuntimeProjectRoot
@@ -1190,40 +1084,6 @@ export async function runCli(
packageRoot,
});
};
- if (args.command === "image") {
- if (args.prompt === undefined) throw new Error("image requires --prompt with text or a text file path");
- if (args.to === undefined) throw new Error("image requires --to with the file to write");
- if (distribution.generatePicture === undefined) {
- throw new Error("this Distribution cannot generate a picture directly");
- }
- const picture = await distribution.generatePicture({
- prompt: await readPromptText(args.prompt),
- packageRoot: await packageRootForProject(process.cwd()),
- ...(distribution.packageRoot === undefined
- ? {}
- : { distributionPackageRoot: distribution.packageRoot }),
- ...(args.model === undefined ? {} : { model: args.model }),
- ...(args.aspectRatio === undefined ? {} : { aspectRatio: args.aspectRatio }),
- ...(args.resolution === undefined ? {} : { resolution: args.resolution }),
- });
- await mkdir(dirname(args.to), { recursive: true });
- await writeFile(args.to, picture.bytes);
- writeOperational({
- format: "hypit.cli-image@1",
- package: picture.package,
- model: picture.model,
- mediaType: picture.mediaType,
- size: picture.bytes.byteLength,
- path: args.to,
- }, "Picture written", "success", [
- ["Model", picture.model],
- ["Package", picture.package],
- ["Type", picture.mediaType],
- ["Bytes", String(picture.bytes.byteLength)],
- ["Path", args.to],
- ], ["This picture is authoring input; no Build, Record or Runtime Profile took part."]);
- return;
- }
if (args.command === "paths") {
const projectRoot = selectedRuntimeProjectRoot ?? process.cwd();
const runtimePaths = args.runtime === undefined
@@ -1265,14 +1125,13 @@ export async function runCli(
: existing === undefined ? [] : [existing];
const ready = reports.length === 1;
writeOperational({
- format: "hypit.cli-packages-status@1",
- ok: ready,
- root,
- packages: reports,
+ format: "hypit.cli-package@2",
+ action: args.action,
+ package: args.file,
+ ready,
}, args.action === "install" ? "Machine package is ready" : "Machine package status",
ready ? "success" : "warning", [
["Package", args.file],
- ["Root", root],
["Ready", String(ready)],
]);
if (!ready) io.setExitCode?.(1);
@@ -1300,18 +1159,14 @@ export async function runCli(
]);
const diagnostics = [...result.diagnostics, ...(projectResult?.diagnostics ?? [])];
const machine = {
- format: "hypit.cli-doctor@1" as const,
+ format: "hypit.cli-doctor@2" as const,
ok: !diagnostics.some((item) => item.severity === "error"),
- dataRoot: result.dataRoot,
- ...(projectResult?.location === undefined ? {} : {
- resultRepository: {
- root: projectResult.location.root,
- use: projectResult.location.selection.use,
- },
- }),
- diagnostics,
+ profile,
+ diagnosticCount: diagnostics.length,
+ diagnostics: diagnostics.slice(0, args.limit),
+ ...(diagnostics.length <= args.limit ? {} : { omittedDiagnostics: diagnostics.length - args.limit }),
};
- writeCliOutput(io, args, { kind: "doctor", machine, profile });
+ writeCliOutput(io, args, { kind: "doctor", machine });
if (!machine.ok) io.setExitCode?.(1);
return;
}
@@ -1346,25 +1201,25 @@ export async function runCli(
: await controller.programs.report();
const ready = result.programs.every((item) => item.state.state === "ready");
const desiredState = args.action === "down" ? !result.programs.some((item) => item.state.state === "ready") : ready;
- const machine = {
- format: "hypit.cli-programs-status@1" as const,
- // A successful status query is not a failed lifecycle action. `ready` carries readiness.
- ok: args.action === "status" ? true : desiredState,
+ const lifecycleOk = args.action === "status" || desiredState;
+ const shownPrograms = result.programs.filter((item) => item.state.state !== "ready")
+ .slice(0, args.limit);
+ writeOperational({
+ format: "hypit.cli-programs@2",
+ action: args.action,
ready,
- dataRoot: result.dataRoot,
- packages: prepared,
- programs: result.programs,
- };
- const shownPrograms = args.verbose || args.action !== "status"
- ? result.programs
- : result.programs.filter((item) => item.state.state !== "ready");
- writeOperational(machine, `External programs ${args.action}`,
- args.action === "status" ? ready ? "success" : "info" : machine.ok ? "success" : "warning", [
- ["Data root", result.dataRoot],
+ programs: result.programs.slice(0, args.limit).map((item) => ({
+ id: item.id,
+ state: item.state.state,
+ ...(args.verbose && item.action !== undefined ? { action: item.action } : {}),
+ })),
+ ...(result.programs.length <= args.limit ? {} : { omittedPrograms: result.programs.length - args.limit }),
+ }, `External programs ${args.action}`,
+ args.action === "status" ? ready ? "success" : "info" : lifecycleOk ? "success" : "warning", [
["Programs", String(result.programs.length)],
["Ready", String(result.programs.filter((item) => item.state.state === "ready").length)],
- ], shownPrograms.map(programLine));
- if (args.action !== "status" && !machine.ok) io.setExitCode?.(1);
+ ], shownPrograms.map((item) => `${item.id}: ${item.state.state}`));
+ if (!lifecycleOk) io.setExitCode?.(1);
return;
}
if (args.command === "runtime") {
@@ -1396,10 +1251,19 @@ export async function runCli(
});
const ok = processState.state === "running"
&& external.programs.every((item) => item.state.state === "ready");
- writeOperational({ ok, packages: prepared, worker: processState, programs: external.programs }, "Runtime is up",
+ writeOperational({
+ format: "hypit.cli-runtime-up@2",
+ ready: ok,
+ worker: processState.state,
+ preparedPackages: prepared.length,
+ programs: {
+ total: external.programs.length,
+ ready: external.programs.filter((item) => item.state.state === "ready").length,
+ },
+ }, "Runtime is up",
ok ? "success" : "warning", [
["Machine packages", String(prepared.length)],
- ["Worker", String(processState.pid)],
+ ["Worker", processState.state],
["External programs", String(external.programs.length)],
]);
if (!ok) io.setExitCode?.(1);
@@ -1408,14 +1272,16 @@ export async function runCli(
if (args.action === "logs") {
const logs = await controller.worker.logs();
const lines = logs.text.length === 0 ? [] : logs.text.replace(/\n$/u, "").split("\n");
- const shown = args.verbose ? lines : lines.slice(-100);
+ const shown = lines.slice(-args.lines);
writeOperational({
- format: "hypit.cli-runtime-logs@1",
- path: logs.path,
- text: logs.text,
+ format: "hypit.cli-runtime-logs@2",
+ lines: shown,
+ totalLines: lines.length,
+ omittedLines: Math.max(0, lines.length - shown.length),
+ ...(args.verbose ? { path: logs.path } : {}),
}, "Runtime logs", "info", [
- ["Path", logs.path],
- ["Lines", String(lines.length)],
+ ["Lines", `${shown.length}/${lines.length}`],
+ ...(args.verbose ? [["Path", logs.path] as const] : []),
], shown.length === 0 ? ["No log output."] : shown);
return;
}
@@ -1423,7 +1289,7 @@ export async function runCli(
const worker = await controller.worker.down({
...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
});
- writeOperational({ ok: true, worker }, "Runtime Worker is down", "success", [
+ writeOperational({ 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;
@@ -1442,8 +1308,12 @@ export async function runCli(
runtime = selectedRuntime;
const activity = await runtime.activity();
const counts = Object.fromEntries(
- ["submitting", "ready", "running", "waiting", "saving-result"].map((name) =>
- [name, activity.builds.filter((item) => item.activity === name).length]),
+ [
+ ["starting", activity.builds.filter((item) => item.activity === "submitting" || item.activity === "ready").length],
+ ["active", activity.builds.filter((item) => item.activity === "running").length],
+ ["waiting", activity.builds.filter((item) => item.activity === "waiting").length],
+ ["decided", activity.builds.filter((item) => item.activity === "saving-result").length],
+ ],
);
const lanes = summarizeQueueLanes(activity.capacity);
const ready = worker.state === "running"
@@ -1452,24 +1322,35 @@ export async function runCli(
const attention = activity.builds.some((item) => item.issue !== undefined) || (active > 0 && !ready);
const unavailable = external.programs.filter((item) => item.state.state !== "ready");
const machine = {
- format: "hypit.cli-runtime-status@1" as const,
- ok: true,
+ format: "hypit.cli-runtime-status@2" as const,
ready,
attention,
- worker,
- activity: { counts, lanes },
- programs: external.programs,
+ worker: {
+ state: worker.state,
+ ...(worker.configuration === undefined ? {} : { configuration: worker.configuration }),
+ },
+ builds: counts,
+ programs: {
+ total: external.programs.length,
+ ready: external.programs.length - unavailable.length,
+ unavailable: unavailable.slice(0, args.limit).map((item) => ({ id: item.id, state: item.state.state })),
+ },
+ capacity: {
+ active: activity.capacity.length,
+ ...(args.verbose ? { lanes: lanes.slice(0, args.limit) } : {}),
+ },
};
writeOperational(machine, "Runtime status", attention ? "warning" : ready ? "success" : "info", [
["Worker", worker.state],
- ["Ready", String(counts.ready ?? 0)],
- ["Running", String(counts.running ?? 0)],
+ ["Starting", String(counts.starting ?? 0)],
+ ["Active", String(counts.active ?? 0)],
["Waiting", String(counts.waiting ?? 0)],
+ ["Decided", String(counts.decided ?? 0)],
["Programs", `${external.programs.length - unavailable.length}/${external.programs.length} ready`],
- ["Capacity reservations", String(activity.capacity.length)],
+ ...(args.verbose ? [["Active requests", String(activity.capacity.length)] as const] : []),
], [
- ...unavailable.map(programLine),
- ...queueLaneLines(lanes),
+ ...unavailable.slice(0, args.limit).map((item) => `${item.id}: ${item.state.state}`),
+ ...(args.verbose ? queueLaneLines(lanes.slice(0, args.limit)) : []),
]);
} finally {
if (runtime !== undefined) await runtime.close();
@@ -1494,20 +1375,33 @@ export async function runCli(
throw new Error(`Endpoint ${args.file} has several credentials; select one with --slot`);
}
if (args.action === "status") {
- writeOperational({ endpoint: args.file, credentials }, "Credential status", "info", [
+ const view = credentials.slice(0, args.limit).map((item) => ({
+ endpoint: item.endpoint,
+ slot: item.slot,
+ label: item.label,
+ kind: item.kind,
+ configured: item.configured,
+ writable: item.writable,
+ }));
+ writeOperational({
+ format: "hypit.cli-auth-status@2",
+ endpoint: args.file,
+ credentials: view,
+ ...(credentials.length <= args.limit ? {} : { omittedCredentials: credentials.length - args.limit }),
+ }, "Credential status", "info", [
["Endpoint", args.file!],
["Configured", `${credentials.filter((item) => item.configured).length}/${credentials.length}`],
- ], credentials.map((item) => `${item.slot}: ${item.configured ? "configured" : "missing"} · ${item.writable ? "writable" : "read-only"}`));
+ ], 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.writable) {
const source = item.ref.store === "env"
? `set ${item.ref.key} in the environment`
- : `configure ${item.ref.key} through CredentialStore ${item.ref.store}`;
+ : "select a writable credential source in the Runtime Profile";
throw new Error(
- `CredentialStore ${item.ref.store} is read-only for ${item.label}; ${source}, `
- + "or select the writable OS CredentialStore in the Runtime Profile",
+ `${item.label} cannot be written by this command; ${source}`,
);
}
const oauth = item.ref.store === "os" && /hypihub/iu.test(`${item.endpoint} ${item.ref.key}`);
@@ -1523,16 +1417,27 @@ export async function runCli(
try { JSON.parse(secret); } catch { throw new Error(`${item.label} is not valid JSON`); }
}
const stored = await runtime.putCredential(item.endpoint, item.slot, secret);
- writeOperational({ endpoint: args.file, stored }, "Credential stored", "success", [
- ["Endpoint", args.file!], ["Slot", stored.slot], ["Store", stored.ref.store],
+ writeOperational({
+ format: "hypit.cli-auth-change@2",
+ endpoint: args.file,
+ slot: stored.slot,
+ configured: true,
+ }, "Credential stored", "success", [
+ ["Endpoint", args.file!], ["Slot", stored.slot],
]);
} else {
const [item] = credentials;
if (item === undefined) throw new Error(`Endpoint ${args.file} has no matching credential`);
const removed = await runtime.deleteCredential(item.endpoint, item.slot);
- writeOperational({ endpoint: args.file, ...removed }, removed.deleted ? "Credential removed" : "Credential was absent",
+ writeOperational({
+ format: "hypit.cli-auth-change@2",
+ endpoint: args.file,
+ 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], ["Store", removed.credential.ref.store],
+ ["Endpoint", args.file!], ["Slot", removed.credential.slot],
]);
}
} finally {
@@ -1548,87 +1453,80 @@ export async function runCli(
if (args.command === "builds") {
const page = await repository.browse({ limit: args.limit, ...(args.before === undefined ? {} : { before: args.before }) });
const builds = page.results.map((manifest) => ({
- build: manifest.id,
- createdAt: buildCreatedAt(manifest.id),
+ id: manifest.id,
+ createdAt: buildCreatedAtIso(manifest.id),
...(manifest.title === undefined ? {} : { title: manifest.title }),
outcome: manifest.outcome,
- source: manifest.source,
- ...(manifest.run === undefined ? {} : { run: manifest.run }),
- targets: manifest.targets,
- outputs: Object.keys(manifest.outputs),
+ ...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.path, commandProjectRoot()) }),
+ targetCount: manifest.targets.length,
+ ...(args.verbose ? {
+ targets: manifest.targets.slice(0, args.limit),
+ ...(manifest.targets.length <= args.limit ? {} : { omittedTargets: manifest.targets.length - args.limit }),
+ } : {}),
+ outputCount: Object.keys(manifest.outputs).length,
}));
- writeOperational({ format: "hypit.cli-builds@2", builds, ...(page.next === undefined ? {} : { next: page.next }) },
+ writeOperational({ format: "hypit.cli-builds@3", builds, ...(page.next === undefined ? {} : { next: page.next }) },
"Build results", "info", [["Builds", String(builds.length)]],
builds.map((item) => {
- const source = basename(item.run?.path ?? item.source.path);
- const label = item.title === undefined ? item.build : `${item.title} · ${item.build}`;
- return `${label}: ${item.outcome} · ${new Date(item.createdAt).toLocaleString()} · ${source} · ${item.targets.join(", ")}`;
+ const label = item.title === undefined ? item.id : `${item.title} · ${item.id}`;
+ const run = item.run === undefined ? "" : ` · ${item.run}`;
+ return `${label}: ${item.outcome} · ${new Date(item.createdAt).toLocaleString()}${run} · ${item.targetCount} target${item.targetCount === 1 ? "" : "s"}`;
}).concat(page.next === undefined ? [] : [`Older hypit builds --before ${page.next}`]));
return;
}
if (args.command === "history") {
const page = await repository.browse({ limit: args.limit, ...(args.before === undefined ? {} : { before: args.before }) });
const source = args.source === undefined ? undefined : resolve(args.source);
- const entries = page.results.flatMap((manifest) => {
+ const matches = page.results.flatMap((manifest) => {
if (source !== undefined && manifest.source.path !== source) return [];
- return Object.entries(manifest.outputs).flatMap(([name, output]) => {
- if (args.file !== undefined && name !== args.file) return [];
- if (args.excludeTargets && manifest.targets.includes(name)) return [];
- return [{
- build: manifest.id,
- createdAt: buildCreatedAt(manifest.id),
- outcome: manifest.outcome,
- source: manifest.source,
- ...(manifest.run === undefined ? {} : { run: manifest.run }),
- output: { name, type: output.type, value: output.value },
- }];
- });
+ return manifest.outputs[args.file!] === undefined ? [] : [manifest];
});
- const pins = args.pin ? pinnedRecords(entries) : [];
+ const entries = await Promise.all(matches.map(async (manifest) => ({
+ build: manifest.id,
+ ...(manifest.title === undefined ? {} : { title: manifest.title }),
+ createdAt: buildCreatedAtIso(manifest.id),
+ outcome: manifest.outcome,
+ output: await outputView(repository, manifest, args.file!),
+ })));
writeOperational({
- format: "hypit.cli-history@2",
- query: {
- ...(args.file === undefined ? {} : { output: args.file }),
- ...(source === undefined ? {} : { source }),
- },
+ format: "hypit.cli-history@3",
+ output: args.file,
+ ...(source === undefined ? {} : { source: projectPath(source, commandProjectRoot()) }),
entries,
...(page.next === undefined ? {} : { next: page.next }),
- ...(args.pin ? { pins } : {}),
- }, entries.length === 0 ? "No Build Output history" : args.pin ? "Reuse these Outputs" : "Output history",
+ }, entries.length === 0 ? "No matching Output" : "Output history",
entries.length === 0 ? "warning" : "info", [
- ...(args.file === undefined ? [] : [["Output", args.file] as const]),
- ...(source === undefined ? [] : [["Source", source] as const]),
- ["Outputs", String(entries.length)],
- ], args.pin
- ? ["Paste into a Run Source; every reference names one exact Build Output.", ...pins.flatMap((item) => item.markup)]
- : entries.map((item) => {
- const created = new Date(item.createdAt).toISOString();
- const kind = item.output.value.kind === "build-file"
- ? item.output.value.mediaType
- : item.output.value.kind === "inline" ? "inline value" : "structured value";
- return `${item.build}: ${item.output.name} · ${displayType(item.output.type)} · ${kind} · ${created}`;
- }).concat(page.next === undefined ? [] : [`Older hypit history${args.file === undefined ? "" : ` ${args.file}`} --before ${page.next}`]));
+ ["Output", args.file!],
+ ...(source === undefined ? [] : [["Source", projectPath(source, commandProjectRoot())] 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}`]));
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 outputs = Object.entries(manifest.outputs).map(([name, output]) => ({
- name,
- target: manifest.targets.includes(name),
- type: output.type,
- value: output.value,
- }));
- writeOperational({ format: "hypit.cli-inspect@2", result: manifest }, "Build Result detail", manifest.outcome === "failed" ? "error" : "info", [
- ["Build", manifest.id],
- ["Created", new Date(buildCreatedAt(manifest.id)).toLocaleString()],
- ...(manifest.title === undefined ? [] : [["Title", manifest.title] as const]),
- ["Outcome", manifest.outcome ?? "unfinished"],
- ["Targets", String(manifest.targets.length)],
- ["Outputs", String(outputs.length)],
+ const build = await buildResultView(repository, manifest, {
+ projectRoot: commandProjectRoot(),
+ ...(args.output === undefined ? {} : { output: args.output }),
+ limit: args.limit,
+ });
+ writeOperational({ format: "hypit.cli-inspect@3", build }, "Build Result", manifest.outcome === "failed" ? "error" : "info", [
+ ["Build", build.id],
+ ["Created", new Date(build.createdAt).toLocaleString()],
+ ...(build.title === undefined ? [] : [["Title", build.title] as const]),
+ ["Outcome", build.outcome],
+ ["Targets", String(build.targetCount)],
+ ["Outputs", String(build.outputs.length + (build.omittedOutputs ?? 0))],
], [
- ...(manifest.failure === undefined ? [] : [`Reason ${manifest.failure}`]),
- ...outputs.map((item) => `${item.target ? "Target" : "Output"} ${item.name} · ${displayType(item.type)} · ${item.value.kind}`),
+ ...(build.failure === undefined ? [] : [`Reason ${build.failure}`]),
+ ...(build.note === undefined ? [] : [`Note ${build.note}`]),
+ ...build.outputs.map((item) => `${item.highlighted ? "★" : item.target ? "Target" : "Output"} ${item.name} · ${item.type} · ${item.kind}`),
+ ...(build.omittedOutputs === undefined ? [] : [
+ `${build.omittedOutputs} more Outputs · use --limit <count> or --output <name>`,
+ ]),
]);
return;
}
@@ -1641,11 +1539,15 @@ export async function runCli(
: args.highlightedOutputs.length === 0 ? {} : { highlightedOutputs: args.highlightedOutputs }),
});
const presentation = {
- format: "hypit.cli-result-edit@2",
+ format: "hypit.cli-result-edit@3",
build: manifest.id,
title: manifest.title ?? null,
note: manifest.note ?? null,
- highlightedOutputs: manifest.highlightedOutputs ?? [],
+ highlightedOutputCount: manifest.highlightedOutputs?.length ?? 0,
+ highlightedOutputs: manifest.highlightedOutputs?.slice(0, args.limit) ?? [],
+ ...((manifest.highlightedOutputs?.length ?? 0) <= args.limit
+ ? {}
+ : { omittedHighlightedOutputs: manifest.highlightedOutputs!.length - args.limit }),
};
writeOperational(presentation, "Build Result updated", "success", [
["Build", manifest.id],
@@ -1655,10 +1557,18 @@ export async function runCli(
return;
}
const exported = await exportBuildResultOutput(repository, args.file!, args.output!, args.to!);
- writeOperational({ format: "hypit.cli-get@3", ...exported }, "Build Output exported", "success", [
+ const machine = {
+ format: "hypit.cli-get@4",
+ build: exported.build,
+ output: exported.output,
+ type: cliTypeName(exported.type),
+ kind: exported.kind,
+ path: exported.path,
+ } as const;
+ writeOperational(machine, "Build Output exported", "success", [
["Build", exported.build],
["Output", exported.output],
- ["Type", displayType(exported.type)],
+ ["Type", machine.type],
["Kind", exported.kind],
["Path", exported.path],
]);
@@ -1681,28 +1591,20 @@ export async function runCli(
);
}
const finished = result?.outcome !== undefined;
+ const build = result === undefined ? null : buildStatusView({ id: result.id, result });
const machine = {
- format: "hypit.cli-status@2",
- build: result === undefined ? null : {
- id: result.id,
- ...(result.outcome === undefined ? {} : { outcome: result.outcome }),
- result: {
- title: result.title,
- targets: result.targets,
- outputs: Object.keys(result.outputs),
- outcome: result.outcome,
- },
- operations: [],
- },
+ format: "hypit.cli-status@3",
+ build,
};
writeOperational(machine, result === undefined
? "Build Result not found"
: finished ? "Build Result is finished" : "Build Result is unfinished",
result === undefined || !finished ? "warning" : "info", [
["Build", args.file!],
- ["Runtime", "not selected; execution state is unknown"],
- ...(result?.outcome === undefined ? [] : [["Outcome", result.outcome] as const]),
- ["Operations", "0"],
+ ["Work", build?.work.state ?? "unknown"],
+ ...(build?.work.outcome === undefined ? [] : [["Decision", build.work.outcome] as const]),
+ ["Result", build?.result.state ?? "missing"],
+ ...(build?.result.outputCount === undefined ? [] : [["Outputs", String(build.result.outputCount)] as const]),
], result === undefined ? [] : [
"Result and Runtime are independent facts; select the Runtime to inspect active execution.",
]);
@@ -1738,29 +1640,40 @@ export async function runCli(
});
if (args.watch && currentView === previous) return;
previous = currentView;
+ const builds = activity.builds.slice(0, args.limit).map((item) => {
+ const status = buildStatusView({ id: item.id, runtime: item });
+ return {
+ id: item.id,
+ work: status.work,
+ ...(item.outcome === undefined ? {} : { outcome: item.outcome }),
+ ...(status.attention === undefined ? {} : { attention: status.attention }),
+ };
+ });
const value = {
- format: "hypit.cli-activity@1",
+ format: "hypit.cli-activity@2",
at: Date.now(),
- worker,
- builds: activity.builds,
- lanes: summarizeQueueLanes(activity.capacity),
+ worker: worker.state,
+ builds,
+ ...(activity.builds.length <= args.limit ? {} : { omittedBuilds: activity.builds.length - args.limit }),
+ activeRequests: activity.capacity.length,
+ ...(args.verbose ? { lanes: summarizeQueueLanes(activity.capacity).slice(0, args.limit) } : {}),
};
- const buildLines = activity.builds.slice(0, args.verbose ? undefined : 12).map((item) =>
- `${item.id}: ${item.activity}`
+ const buildLines = activity.builds.slice(0, args.limit).map((item) =>
+ `${item.id}: ${buildStatusView({ id: item.id, runtime: item }).work.state}`
+ `${item.cancellationRequested ? " · cancelling" : ""}`
- + `${item.issue === undefined ? "" : ` · ${item.issue.scope}: ${item.issue.message}`}`);
+ + `${item.issue === undefined ? "" : ` · ${item.issue.message}`}`);
const activeOperations = activity.builds.flatMap((item) => item.operations)
.filter((item) => item.status === "pending");
const operationLines = args.verbose
? activity.builds.flatMap((build) => build.operations.filter((item) => item.status === "pending")
.map((item) => `${build.id} · ${item.endpoint}: ${item.progress === undefined
? item.status
- : formatOperationProgress(item.progress)}`))
+ : formatOperationProgress(item.progress)}`)).slice(0, args.limit)
: [];
writeOperational(value, "Runtime activity", activity.builds.length === 0 ? "success" : "info", [
["Active Builds", String(activity.builds.length)],
["Active Operations", String(activeOperations.length)],
- ["Worker", worker.pid === undefined ? worker.state : `${worker.state} · ${worker.pid}`],
+ ["Worker", worker.state],
], [
...buildLines,
...(operationLines.length === 0 ? [] : ["Operations:", ...operationLines]),
@@ -1815,23 +1728,17 @@ export async function runCli(
const activity = view?.activity;
const outcome = result?.outcome ?? view?.outcome;
const issue = view?.issue;
- const resultSummary = result === undefined ? undefined : {
- title: result.title,
- targets: result.targets,
- outputs: Object.keys(result.outputs),
- outcome: result.outcome,
- };
- const machine = {
- format: "hypit.cli-status@2",
- build: !found ? null : {
- id: view?.id ?? result!.id,
- ...(activity === undefined ? {} : { activity }),
- ...(outcome === undefined ? {} : { outcome }),
- ...(issue === undefined ? {} : { issue }),
- ...(resultSummary === undefined ? {} : { result: resultSummary }),
- operations: view?.operations ?? [],
- },
+ const build = !found ? null : buildStatusView({
+ id: view?.id ?? result!.id,
+ ...(view === undefined ? {} : { runtime: view }),
+ ...(result === undefined ? {} : { result }),
...(resultReadError === undefined ? {} : { resultReadError }),
+ verbose: args.verbose,
+ operationLimit: args.limit,
+ });
+ const machine = {
+ format: "hypit.cli-status@3",
+ build,
};
writeOperational(machine, !found
? "Build not found"
@@ -1848,34 +1755,33 @@ export async function runCli(
? "error"
: args.watch && activity !== undefined ? "warning" : "info", [
["Build", args.file!],
- ...(result?.title === undefined ? [] : [["Title", result.title] as const]),
- ...(activity === undefined ? [] : [["Activity", activity] as const]),
- ...(outcome === undefined ? [] : [["Outcome", outcome] as const]),
- ...(result === undefined ? [] : [["Outputs", String(Object.keys(result.outputs).length)] as const]),
- ], (view?.operations ?? []).filter((operation) => operation.status !== "completed")
- .slice(0, args.verbose ? undefined : 12).map((operation) => operation.failure !== undefined
+ ...(build?.title === undefined ? [] : [["Title", build.title] as const]),
+ ["Work", build?.work.state ?? "unknown"],
+ ...(build?.work.outcome === undefined ? [] : [["Decision", build.work.outcome] as const]),
+ ["Result", build?.result.state ?? "missing"],
+ ...(build?.result.outputCount === undefined ? [] : [["Outputs", String(build.result.outputCount)] as const]),
+ ], (build?.operations ?? []).map((operation) => operation.failure !== undefined
? `${operation.endpoint}: ${operation.failure.code} — ${operation.failure.message}`
: operation.progress === undefined
- ? `${operation.endpoint}: ${operation.status}`
+ ? `${operation.endpoint}: ${operation.state}`
: `${operation.endpoint}: ${formatOperationProgress(operation.progress)}`)
- .concat(issue === undefined ? [] : [
- `${issue.scope === "result" ? "Result save" : "Cleanup"} ${issue.message}`,
- ])
- .concat(resultReadError === undefined ? [] : [`Result unavailable: ${resultReadError}`])
- .concat(issue === undefined ? [] : [`Finish hypit result finish ${args.file}`]));
+ .concat(build?.attention === undefined ? [] : [
+ `Attention ${build.attention.message}`,
+ ...(build.attention.action === undefined ? [] : [`Action ${build.attention.action}`]),
+ ]));
if (!found || issue !== undefined || resultReadError !== undefined || outcome === "failed") io.setExitCode?.(1);
} else if (args.command === "result") {
if (args.action === "discard") {
const resultControl = await selectedHost.openResultControl();
const discarded = await resultControl.discardSubmission(args.file!)
.finally(async () => await resultControl.close());
- writeOperational({ format: "hypit.cli-result-discard@1", build: args.file, discarded }, discarded
+ writeOperational({ format: "hypit.cli-result-discard@2", build: args.file, discarded }, discarded
? "Incomplete Build discarded"
: "Incomplete Build not found", discarded ? "success" : "warning", [
["Build", args.file!],
["State", discarded ? "discarded" : "missing"],
], discarded ? [
- "The incomplete submission, Result draft and temporary Build files were removed.",
+ "The incomplete submission was removed.",
] : []);
if (!discarded) io.setExitCode?.(1);
return;
@@ -1897,25 +1803,28 @@ export async function runCli(
const opened = await projectResults();
const existing = await opened.repository.read(args.file!).finally(async () => await opened.close());
if (existing?.outcome === undefined) {
- writeOperational({ format: "hypit.cli-result-finish@1", build: args.file, found: false },
+ writeOperational({ format: "hypit.cli-result-finish@2", build: args.file, found: false },
"Build not found", "warning", [["Build", args.file!]]);
io.setExitCode?.(1);
return;
}
- writeOperational({ format: "hypit.cli-result-finish@1", build: args.file, outcome: existing.outcome },
+ writeOperational({ format: "hypit.cli-result-finish@2", build: args.file, outcome: existing.outcome },
"Result already finished", "info", [["Build", args.file!], ["Outcome", existing.outcome]]);
return;
}
writeOperational({
- format: "hypit.cli-result-finish@1",
+ format: "hypit.cli-result-finish@2",
build: args.file,
outcome: finished.outcome,
- ...(finished.issue === undefined ? {} : { issue: finished.issue }),
+ ...(finished.issue === undefined ? {} : { attention: {
+ message: finished.issue.message,
+ action: `hypit result finish ${args.file}`,
+ } }),
}, finished.issue === undefined ? "Result finished" : "Result still needs attention",
finished.issue === undefined ? "success" : "error", [
["Build", args.file!],
["Outcome", finished.outcome],
- ], finished.issue === undefined ? [] : [`${finished.issue.scope}: ${finished.issue.message}`]);
+ ], finished.issue === undefined ? [] : [`Attention ${finished.issue.message}`]);
if (finished.issue !== undefined) io.setExitCode?.(1);
} else {
const active = await runtime.cancel(args.file!, args.reason);
@@ -1923,19 +1832,22 @@ export async function runCli(
const finished = openedResults === undefined
? undefined
: await openedResults.repository.read(args.file!).finally(async () => await openedResults.close());
+ const build = active === undefined && finished === undefined ? null : buildStatusView({
+ id: args.file!,
+ ...(active === undefined ? {} : { runtime: active }),
+ ...(finished === undefined ? {} : { result: finished }),
+ });
const machine = {
- format: "hypit.cli-cancel@2",
- build: args.file,
+ format: "hypit.cli-cancel@3",
requested: active?.cancellationRequested === true,
- ...(active === undefined ? {} : { activity: active.activity }),
- outcome: active?.outcome ?? finished?.outcome,
+ build,
};
const title = active === undefined && finished === undefined
? "Build not found"
: active === undefined ? "Build already finished" : "Build cancellation requested";
writeOperational(machine, title,
active === undefined && finished === undefined ? "warning" : active === undefined ? "info" : "success", [
- ["Build", args.file!], ...(machine.activity === undefined ? [] : [["Activity", machine.activity] as const]),
+ ["Build", args.file!], ...(build === null ? [] : [["Work", build.work.state] as const]),
], active === undefined && finished?.outcome !== undefined
? [`No running work was changed; this Build is already ${finished.outcome}.`]
: []);
@@ -2002,40 +1914,58 @@ export async function runCli(
packageContributions,
});
const machine = {
- format: "hypit.cli-check@1" as const,
+ format: "hypit.cli-check@2" as const,
sourceKind: "run" as const,
ok: true,
- run: loaded.source,
- source: loaded.authorSource,
- targets: loaded.document.targets,
- candidates: Object.fromEntries(loaded.document.candidates.map((item) => [item.id, item.kind])),
- satisfactions: loaded.document.satisfactions,
- unresolvedHistoricalOutputs: loaded.unresolvedHistoricalOutputs,
- deterministic_durations: deterministicSpeechDurationsFromGraph(loaded.author.graph, loaded.author.program.records),
+ run: projectPath(loaded.source, effectiveWorkspaceRoot),
+ author: projectPath(loaded.authorSource, effectiveWorkspaceRoot),
+ frontend: sourceHeader.using,
+ targetCount: loaded.document.targets.length,
+ targets: loaded.document.targets.slice(0, args.limit).map((item) => item.output),
+ candidates: loaded.document.candidates.length,
+ satisfactions: loaded.document.satisfactions.length,
+ unresolvedHistoricalOutputs: loaded.unresolvedHistoricalOutputs.slice(0, args.limit).map((item) => ({
+ candidate: item.id,
+ build: item.build,
+ output: item.output,
+ })),
+ ...(loaded.unresolvedHistoricalOutputs.length <= args.limit ? {} : {
+ omittedHistoricalOutputs: loaded.unresolvedHistoricalOutputs.length - args.limit,
+ }),
} as const;
writeCliOutput(io, args, {
kind: "check-run",
machine,
- frontend: sourceHeader.using,
});
return;
}
{
const result = await compiler.compileSource(workspace.entry, workspace);
+ const authorFacing = result.exports.filter((item) =>
+ !item.name.includes(".__") && !/\.binding-\d+$/u.test(item.name) && !item.name.endsWith(".bindings"));
+ const outputs = authorFacing.filter((item) => item.ref.kind === "logical-output");
+ const values = authorFacing.filter((item) => item.ref.kind !== "logical-output");
+ const modules = result.program.closure.modules.map((item) => `${item.manifest.name}@${item.manifest.version}`);
const machine = {
- format: "hypit.cli-check@1" as const,
- sourceKind: "author" as const,
- ok: true,
- units: result.closure.units.length,
- sourceAssets: result.attachments.map((item) => item.artifact),
- modules: result.program.closure.modules.map((item) => `${item.manifest.name}@${item.manifest.version}`),
- exports: result.exports.map((item) => ({ name: item.name, type: item.type, kind: item.ref.kind })),
+ format: "hypit.cli-check@2" as const,
+ sourceKind: "author" as const,
+ ok: true,
+ source: projectPath(workspace.entry.name, effectiveWorkspaceRoot),
+ frontend: sourceHeader.using,
+ units: result.closure.units.length,
+ assets: result.attachments.length,
+ modules: modules.length,
+ 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: {
+ 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, {
kind: "check-author",
machine,
- source: workspace.entry.name,
- frontend: sourceHeader.using,
});
return;
}
@@ -2102,9 +2032,8 @@ export async function runCli(
// preflight must already be clean; `runtime up` is the explicit place for
// installing or starting declared programs.
assertPreflight(preflight);
- let worker;
try {
- worker = await controller.worker.up({
+ await controller.worker.up({
...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
});
} catch (error) {
@@ -2123,9 +2052,11 @@ export async function runCli(
const operations = Object.entries(progress.operations)
.map(([status, count]) => `${count} ${status}`)
.join(", ");
- io.write(` · ${progress.build}: ${progress.phase}`
+ io.write(` · ${progress.phase}`
+ `${operations.length === 0 ? "" : ` · ${operations}`}\n`);
- for (const line of progress.activity) io.write(` ${line}\n`);
+ if (args.verbose) {
+ for (const line of progress.activity.slice(0, args.limit)) io.write(` ${line}\n`);
+ }
},
}),
});
@@ -2156,22 +2087,18 @@ export async function runCli(
: {}),
}];
});
+ const buildView = buildStatusView({
+ id: built.id,
+ ...(activeView === undefined ? {} : { runtime: activeView }),
+ ...(finishedResult === undefined ? {} : { result: finishedResult }),
+ verbose: args.verbose,
+ operationLimit: args.limit,
+ });
const machine = {
- format: "hypit.cli-build@2",
- build: {
- id: built.id,
- ...(args.title === undefined ? {} : { title: args.title }),
- ...(activeView === undefined ? {} : { activity: activeView.activity }),
- ...(buildOutcome === undefined ? {} : { outcome: buildOutcome }),
- ...(issue === undefined ? {} : { issue }),
- ...(finishedResult === undefined ? {} : {
- result: {
- targets: finishedResult.targets,
- outputs: Object.keys(finishedResult.outputs),
- outcome: finishedResult.outcome,
- },
- }),
- },
+ format: "hypit.cli-build@3",
+ build: args.title === undefined || buildView.title !== undefined
+ ? buildView
+ : { ...buildView, title: args.title },
};
const runtimeHint = runtimeNeedsHint ? ` --runtime ${args.runtime}` : "";
const resultTargets = finishedResult?.targets.flatMap((name) => {
@@ -2188,17 +2115,18 @@ export async function runCli(
`Inspect hypit inspect ${built.id}`,
...resultTargets
.filter((item) => item.output.value.kind === "inline")
- .slice(0, args.verbose ? undefined : 8)
+ .slice(0, args.limit)
.map((item) => `Result ${item.name} = ${inlineValuePreview(
item.output.value.kind === "inline" ? item.output.value.value : undefined,
)}`),
...resultTargets
.filter((item) => item.output.value.kind !== "inline")
- .slice(0, args.verbose ? undefined : 4)
+ .slice(0, args.limit)
.map((item) =>
`Export hypit get ${built.id} --output ${item.name} --to <path>`),
...(resultTargets.length > 0 ? [] : targetPresentations
.filter((item) => item.inline !== undefined)
+ .slice(0, args.limit)
.map((item) => `Result ${item.published.name} = ${item.inline}`)),
];
writeOperational(machine, args.follow
@@ -2207,11 +2135,9 @@ export async function runCli(
buildOutcome === "failed" || issue !== undefined ? "error"
: buildOutcome === "cancelled" || (args.follow && !finished) ? "warning" : "success", [
["Build", built.id],
- ...(activeView === undefined
- ? []
- : [["Activity", activeView.activity] as const]),
- ...(buildOutcome === undefined ? [] : [["Outcome", buildOutcome] as const]),
- ["Worker", worker.state === "running" ? String(worker.pid) : worker.state],
+ ["Work", machine.build.work.state],
+ ...(machine.build.work.outcome === undefined ? [] : [["Decision", machine.build.work.outcome] as const]),
+ ["Result", machine.build.result.state],
["Targets", String(finishedResult?.targets.length ?? targetPublishedOutputs.length)],
], finished ? finishedLines : issue !== undefined ? [
`Result ${issue.scope}: ${issue.message}`,
@@ -2243,20 +2169,54 @@ export async function runCli(
: await preflightPlan(await runtimeHost(args.runtime), 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>();
+ for (const step of result.definition.plan.steps) {
+ const count = Object.keys(step.needs).length;
+ if (count === 0) continue;
+ const operation = `${step.producer.module.name}@${step.producer.module.version}/${step.producer.name}`;
+ externalRequests.set(operation, (externalRequests.get(operation) ?? 0) + count);
+ }
+ const allChoices = result.selections.flatMap((selection) => {
+ const output = outputNames[selection.output];
+ const candidate = loaded.run.satisfactionNames[selection.output];
+ return output === undefined || candidate === undefined ? [] : [{ output, candidate }];
+ });
+ const allUnreached = unreachedGenerations(result.compilation.author.graph, result.state, outputNames)
+ .map((item) => ({ output: item.name, operation: item.producer }));
+ 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, {
kind: "plan",
machine: {
- format: "hypit.cli-plan@1",
+ format: "hypit.cli-plan@2",
ok: preflight?.ok ?? true,
- plan: result.definition.plan,
- unreached: unreachedGenerations(result.compilation.author.graph, result.state, outputNames),
- deterministic_durations: deterministicSpeechDurations(result.compilation),
- ...(preflight === undefined ? {} : { preflight }),
+ run: projectPath(loaded.path, effectiveWorkspaceRoot),
+ targetCount: targets.length,
+ targets: targets.slice(0, args.limit),
+ steps: result.definition.plan.steps.length,
+ externalRequestCount: requestViews.reduce((total, item) => total + item.count, 0),
+ externalRequests: requestViews.slice(0, args.limit),
+ ...(requestViews.length <= args.limit ? {} : { omittedExternalRequests: requestViews.length - args.limit }),
+ choiceCount: allChoices.length,
+ choices: allChoices.slice(0, args.limit),
+ ...(allChoices.length <= args.limit ? {} : { omittedChoices: allChoices.length - args.limit }),
+ ...(allUnreached.length === 0 ? {} : { unreached: allUnreached.slice(0, args.limit) }),
+ ...(allUnreached.length <= args.limit ? {} : { omittedUnreached: allUnreached.length - args.limit }),
+ ...(preflight === undefined ? {} : { preflight: {
+ ok: preflight.ok,
+ capabilityCount: preflight.capabilities.length,
+ capabilities: preflight.capabilities.slice(0, args.limit),
+ ...(preflight.capabilities.length <= args.limit
+ ? {}
+ : { omittedCapabilities: preflight.capabilities.length - args.limit }),
+ diagnosticCount: preflight.diagnostics.length,
+ diagnostics: preflight.diagnostics.slice(0, args.limit),
+ ...(preflight.diagnostics.length <= args.limit
+ ? {}
+ : { omittedDiagnostics: preflight.diagnostics.length - args.limit }),
+ } }),
},
- run: loaded.path,
- outputNames,
- satisfactionNames: loaded.run.satisfactionNames,
- selections: result.selections,
});
if (preflight !== undefined && !preflight.ok) io.setExitCode?.(1);
} finally {
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index c6db95a5..7e6abd1c 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -1,7 +1,5 @@
import { relative, resolve } from "node:path";
-import type { BuildPlan, TypeRef } from "@hypit/protocol";
-
export type CliTerminal = {
readonly isTTY: boolean;
readonly color: boolean;
@@ -35,103 +33,105 @@ export type CliDiagnostic = {
};
export type DoctorOutput = {
- readonly format: "hypit.cli-doctor@1";
+ readonly format: "hypit.cli-doctor@2";
readonly ok: boolean;
- readonly dataRoot: string;
- readonly resultRepository?: { readonly root: string; readonly use: string };
+ readonly profile: string;
+ readonly diagnosticCount: number;
readonly diagnostics: readonly CliDiagnostic[];
+ readonly omittedDiagnostics?: number;
};
export type AuthorCheckOutput = {
- readonly format: "hypit.cli-check@1";
+ readonly format: "hypit.cli-check@2";
readonly sourceKind: "author";
readonly ok: true;
+ readonly source: string;
+ readonly frontend: string;
readonly units: number;
- readonly sourceAssets: readonly unknown[];
- readonly modules: readonly string[];
- readonly exports: readonly {
+ readonly assets: number;
+ readonly modules: number;
+ readonly outputCount: number;
+ readonly outputs: readonly {
readonly name: string;
- readonly type: TypeRef;
- readonly kind: string;
+ readonly type: string;
}[];
+ readonly omittedOutputs?: number;
+ readonly details?: {
+ readonly modules: readonly string[];
+ readonly values: readonly { readonly name: string; readonly type: string }[];
+ };
};
export type RunCheckOutput = {
- readonly format: "hypit.cli-check@1";
+ readonly format: "hypit.cli-check@2";
readonly sourceKind: "run";
readonly ok: true;
readonly run: string;
- readonly source: string;
- readonly targets: readonly unknown[];
- readonly candidates: Readonly<Record<string, string>>;
- readonly satisfactions: readonly unknown[];
+ readonly author: string;
+ readonly frontend: string;
+ readonly targetCount: number;
+ readonly targets: readonly string[];
+ readonly candidates: number;
+ readonly satisfactions: number;
readonly steps?: number;
readonly unresolvedHistoricalOutputs?: readonly {
- readonly id: string;
+ readonly candidate: string;
readonly build: string;
readonly output: string;
}[];
- /** Provider-free estimate:Speech values available before any Build. */
- readonly deterministic_durations?: readonly {
- readonly operation: string;
- readonly speech_record: string;
- readonly policy_record: string;
- readonly seconds: number;
- }[];
+ readonly omittedHistoricalOutputs?: number;
};
export type PlanPreflight = {
readonly ok: boolean;
- readonly dataRoot: string;
+ readonly capabilityCount: number;
readonly capabilities: readonly string[];
+ readonly omittedCapabilities?: number;
+ readonly diagnosticCount: number;
readonly diagnostics: readonly CliDiagnostic[];
+ readonly omittedDiagnostics?: number;
};
export type PlanOutput = {
- readonly format: "hypit.cli-plan@1";
+ readonly format: "hypit.cli-plan@2";
readonly ok: boolean;
- readonly plan: BuildPlan;
- /** Generations the Source declares that these Targets do not reach and no Record supplies. */
- readonly unreached?: readonly { readonly name: string; readonly producer: string }[];
- /** Provider-free estimate:Speech values used to size deterministic preview and paid takes. */
- readonly deterministic_durations?: readonly {
- readonly operation: string;
- readonly speech_record: string;
- readonly policy_record: string;
- readonly seconds: number;
- }[];
+ readonly run: string;
+ readonly targetCount: number;
+ readonly targets: readonly string[];
+ readonly steps: number;
+ readonly externalRequestCount: number;
+ readonly externalRequests: readonly { readonly operation: string; readonly count: number }[];
+ readonly omittedExternalRequests?: number;
+ readonly choiceCount: number;
+ readonly choices: readonly { readonly output: string; readonly candidate: string }[];
+ readonly omittedChoices?: number;
+ readonly unreached?: readonly { readonly output: string; readonly operation: string }[];
+ readonly omittedUnreached?: number;
readonly preflight?: PlanPreflight;
};
+export type CliMachineView = Readonly<Record<string, unknown>>;
+
export type CliPresentation =
| {
readonly kind: "doctor";
readonly machine: DoctorOutput;
- readonly profile: string;
}
| {
readonly kind: "check-author";
readonly machine: AuthorCheckOutput;
- readonly source: string;
- readonly frontend: string;
}
| {
readonly kind: "check-run";
readonly machine: RunCheckOutput;
- readonly frontend: string;
}
| {
readonly kind: "plan";
readonly machine: PlanOutput;
- readonly run: string;
- /** Presentation names declared by this Author Source and Run Source. Never used to plan. */
- readonly outputNames?: Readonly<Record<string, string>>;
- readonly satisfactionNames?: Readonly<Record<string, string>>;
- readonly selections?: readonly { readonly output: string; readonly candidate: string; readonly record: string }[];
}
| {
readonly kind: "operational";
- readonly machine: unknown;
+ readonly machine: CliMachineView;
readonly title: string;
readonly status?: "success" | "warning" | "error" | "info";
readonly facts?: readonly (readonly [string, string])[];
@@ -177,22 +177,6 @@ function shortPath(path: string): string {
return local.length > 0 && !local.startsWith("..") ? local : absolute;
}
-function shortOpaque(value: string): string {
- if (value.length <= 38) return value;
- return `${value.slice(0, 24)}…${value.slice(-8)}`;
-}
-
-function typeName(type: TypeRef): string {
- return `${type.module.name}@${type.module.version}/${type.name}`;
-}
-
-/** Frontends may export graph plumbing so later compilers can address it.
- * Keep that machine surface intact, but do not make authors read generated
- * binding names during an ordinary source check. */
-function isGeneratedExportName(name: string): boolean {
- return name.includes(".__") || /\.binding-\d+$/u.test(name) || name.endsWith(".bindings");
-}
-
function facts(rows: readonly (readonly [string, string])[], colors: Palette): string[] {
const width = Math.max(...rows.map(([name]) => name.length), 0);
return rows.map(([name, value]) => ` ${colors.dim(name.padEnd(width))} ${value}`);
@@ -210,15 +194,9 @@ function heading(status: "success" | "warning" | "error" | "info", text: string,
}
function renderDoctor(view: Extract<CliPresentation, { kind: "doctor" }>, io: CliIo, colors: Palette): string {
- const errors = view.machine.diagnostics.filter((item) => item.severity === "error");
- const warnings = view.machine.diagnostics.filter((item) => item.severity === "warning");
const lines = [colors.accent(colors.strong("Hypit Doctor")), ""];
lines.push(...facts([
- ["Profile", shortPath(view.profile)],
- ["Data root", shortPath(view.machine.dataRoot)],
- ...(view.machine.resultRepository === undefined
- ? []
- : [["Result store", `${view.machine.resultRepository.use} · ${shortPath(view.machine.resultRepository.root)}`] as const]),
+ ["Profile", shortPath(view.machine.profile)],
], colors));
lines.push("");
if (view.machine.diagnostics.length === 0) {
@@ -231,9 +209,11 @@ function renderDoctor(view: Extract<CliPresentation, { kind: "doctor" }>, io: Cl
if (item.subject !== undefined) lines.push(` ${colors.dim("Subject")} ${item.subject}`);
}
}
+ if ((view.machine.omittedDiagnostics ?? 0) > 0) {
+ lines.push(` ${colors.dim(`${view.machine.omittedDiagnostics} more diagnostics · use --limit <count>`)}`);
+ }
lines.push("");
- const summary = `${errors.length} error${errors.length === 1 ? "" : "s"}`
- + ` · ${warnings.length} warning${warnings.length === 1 ? "" : "s"}`;
+ const summary = `${view.machine.diagnosticCount} diagnostic${view.machine.diagnosticCount === 1 ? "" : "s"}`;
lines.push(view.machine.ok ? colors.success(summary) : colors.error(summary));
return `${lines.join("\n")}\n`;
}
@@ -245,34 +225,34 @@ function renderAuthorCheck(
verbose: boolean,
): string {
const lines = [heading("success", "Source is valid", io, colors), ""];
- const authorFacing = view.machine.exports.filter((item) => !isGeneratedExportName(item.name));
- const outputs = authorFacing.filter((item) => item.kind === "logical-output");
- const values = authorFacing.filter((item) => item.kind !== "logical-output");
- const readable = verbose ? view.machine.exports : outputs;
+ const readable = view.machine.outputs;
lines.push(...facts([
- ["Source", shortPath(view.source)],
- ["Frontend", view.frontend],
- ["Modules", String(view.machine.modules.length)],
+ ["Source", shortPath(view.machine.source)],
+ ["Frontend", view.machine.frontend],
+ ["Modules", String(view.machine.modules)],
["Units", String(view.machine.units)],
- ["Outputs", String(outputs.length)],
- ...(verbose ? [["Values", String(values.length)] as const] : []),
- ["Assets", String(view.machine.sourceAssets.length)],
+ ["Outputs", String(view.machine.outputCount)],
+ ...(verbose && view.machine.details !== undefined
+ ? [["Values", String(view.machine.details.values.length)] as const] : []),
+ ["Assets", String(view.machine.assets)],
], colors));
if (readable.length > 0) {
- lines.push("", colors.strong(verbose ? "All exports" : "Runnable outputs"));
- const ordered = [...readable].sort((left, right) => {
- const leftRank = left.kind === "logical-output" ? 0 : 1;
- const rightRank = right.kind === "logical-output" ? 0 : 1;
- return leftRank - rightRank || left.name.localeCompare(right.name);
- });
- const shown = verbose ? ordered : ordered.slice(0, 12);
+ lines.push("", colors.strong("Outputs"));
+ const ordered = [...readable].sort((left, right) => left.name.localeCompare(right.name));
+ const shown = ordered.slice(0, 12);
const width = Math.max(...shown.map((item) => item.name.length));
for (const item of shown) {
- lines.push(` ${colors.accent(item.name.padEnd(width))} ${typeName(item.type)}`
- + `${verbose ? ` ${colors.dim(item.kind)}` : ""}`);
+ lines.push(` ${colors.accent(item.name.padEnd(width))} ${item.type}`);
}
- if (shown.length < ordered.length) {
- lines.push(` ${colors.dim(`${ordered.length - shown.length} more · use --verbose for the complete list`)}`);
+ const omitted = (view.machine.omittedOutputs ?? 0) + Math.max(0, ordered.length - shown.length);
+ if (omitted > 0) {
+ lines.push(` ${colors.dim(`${omitted} more · use --limit <count>`)}`);
+ }
+ }
+ if (verbose && view.machine.details !== undefined && view.machine.details.values.length > 0) {
+ lines.push("", colors.strong("Values"));
+ for (const item of view.machine.details.values.slice(0, 12)) {
+ lines.push(` ${colors.accent(item.name)} ${item.type}`);
}
}
return `${lines.join("\n")}\n`;
@@ -286,17 +266,20 @@ function renderRunCheck(
const lines = [heading("success", "Run source is valid", io, colors), ""];
lines.push(...facts([
["Run", shortPath(view.machine.run)],
- ["Author", shortPath(view.machine.source)],
- ["Frontend", view.frontend],
- ["Targets", String(view.machine.targets.length)],
- ["Candidates", String(Object.keys(view.machine.candidates).length)],
- ["Satisfactions", String(view.machine.satisfactions.length)],
+ ["Author", shortPath(view.machine.author)],
+ ["Frontend", view.machine.frontend],
+ ["Targets", String(view.machine.targetCount)],
+ ["Candidates", String(view.machine.candidates)],
+ ["Satisfactions", String(view.machine.satisfactions)],
...(view.machine.steps === undefined ? [] : [["Steps", String(view.machine.steps)] as const]),
], colors));
const unresolved = view.machine.unresolvedHistoricalOutputs ?? [];
if (unresolved.length > 0) {
lines.push("", heading("warning", `${unresolved.length} historical Candidate${unresolved.length === 1 ? "" : "s"} unresolved`, io, colors));
- for (const item of unresolved) lines.push(` ${item.id} ← ${item.build}/${item.output}`);
+ for (const item of unresolved) lines.push(` ${item.candidate} ← ${item.build}/${item.output}`);
+ if ((view.machine.omittedHistoricalOutputs ?? 0) > 0) {
+ lines.push(` ${colors.dim(`${view.machine.omittedHistoricalOutputs} more · use --limit <count>`)}`);
+ }
lines.push(` ${colors.dim("The Run source is valid. plan/build will resolve these Result values.")}`);
}
return `${lines.join("\n")}\n`;
@@ -306,58 +289,44 @@ function renderPlan(
view: Extract<CliPresentation, { kind: "plan" }>,
io: CliIo,
colors: Palette,
- verbose: boolean,
): string {
- const plan = view.machine.plan;
- const grouped = new Map<string, number>();
- const requested = new Map<string, number>();
- for (const step of plan.steps) {
- const name = `${step.producer.module.name}@${step.producer.module.version}`;
- grouped.set(name, (grouped.get(name) ?? 0) + 1);
- const needs = Object.keys(step.needs).length;
- if (needs > 0) {
- const producer = `${name}#${step.producer.name}`;
- requested.set(producer, (requested.get(producer) ?? 0) + needs);
- }
- }
const lines = [heading("success", "Build plan is valid", io, colors), ""];
- const requestCount = [...requested.values()].reduce((total, count) => total + count, 0);
lines.push(...facts([
- ["Run", shortPath(view.run)],
- ["Targets", String(plan.goals.length)],
- ["Steps", String(plan.steps.length)],
- ["External requests", String(requestCount)],
+ ["Run", shortPath(view.machine.run)],
+ ["Targets", String(view.machine.targetCount)],
+ ["Steps", String(view.machine.steps)],
+ ["External requests", String(view.machine.externalRequestCount)],
], colors));
- if (verbose && grouped.size > 0) {
- lines.push("", colors.strong("Operations"));
- const entries = [...grouped.entries()].sort(([left], [right]) => left.localeCompare(right));
- const countWidth = Math.max(...entries.map(([, count]) => String(count).length));
- for (const [name, count] of entries) {
- lines.push(` ${colors.accent(String(count).padStart(countWidth))} ${name}`);
- }
- }
- if (requested.size > 0) {
+ if (view.machine.externalRequests.length > 0) {
lines.push("", colors.strong("External requests"));
- const entries = [...requested.entries()].sort(([left], [right]) => left.localeCompare(right));
- const countWidth = Math.max(...entries.map(([, count]) => String(count).length));
- for (const [producer, count] of entries) {
- lines.push(` ${colors.warning(String(count).padStart(countWidth))} ${producer}`);
+ const countWidth = Math.max(...view.machine.externalRequests.map((item) => String(item.count).length));
+ for (const item of view.machine.externalRequests) {
+ lines.push(` ${colors.warning(String(item.count).padStart(countWidth))} ${item.operation}`);
+ }
+ if ((view.machine.omittedExternalRequests ?? 0) > 0) {
+ lines.push(` ${colors.dim(`${view.machine.omittedExternalRequests} more Operations · use --limit <count>`)}`);
}
lines.push(` ${colors.dim("These Needs may reach the Endpoints selected by the Runtime Profile during build.")}`);
}
const unreached = view.machine.unreached ?? [];
if (unreached.length > 0) {
lines.push("", colors.strong("Declared but not reached"));
- const width = Math.max(...unreached.map((item) => item.name.length));
+ const width = Math.max(...unreached.map((item) => item.output.length));
for (const item of unreached) {
- lines.push(` ${colors.accent(item.name.padEnd(width))} ${colors.dim(item.producer)}`);
+ lines.push(` ${colors.accent(item.output.padEnd(width))} ${colors.dim(item.operation)}`);
+ }
+ if ((view.machine.omittedUnreached ?? 0) > 0) {
+ lines.push(` ${colors.dim(`${view.machine.omittedUnreached} more · use --limit <count>`)}`);
}
- lines.push(` ${colors.dim("This Run will not perform these. Either nothing needs them, a Target is missing, or an accepted Record was never pinned.")}`);
+ lines.push(` ${colors.dim("These Outputs are outside the selected target graph.")}`);
}
if (view.machine.preflight !== undefined
&& (view.machine.preflight.capabilities.length > 0 || view.machine.preflight.diagnostics.length > 0)) {
lines.push("", colors.strong("Runtime preflight"));
for (const capability of view.machine.preflight.capabilities) lines.push(` ${colors.accent(capability)}`);
+ if ((view.machine.preflight.omittedCapabilities ?? 0) > 0) {
+ lines.push(` ${colors.dim(`${view.machine.preflight.omittedCapabilities} more capabilities · use --limit <count>`)}`);
+ }
if (view.machine.preflight.diagnostics.length === 0) {
lines.push(` ${colors.success(glyph(io, "✓", "+"))} required deployment slice is ready`);
} else {
@@ -366,24 +335,17 @@ function renderPlan(
lines.push(` ${mark} ${item.code}: ${item.message}`);
}
}
- const capabilityCount = view.machine.preflight.capabilities.length;
+ const capabilityCount = view.machine.preflight.capabilityCount;
lines.push(` ${colors.dim(`Runtime base checked; ${capabilityCount} demanded Endpoint ${capabilityCount === 1 ? "capability" : "capabilities"} checked.`)}`);
}
- const selections = view.selections ?? [];
- const visibleSelections = verbose
- ? selections
- : selections.filter((selection) => view.satisfactionNames?.[selection.output] !== undefined);
- if (visibleSelections.length > 0) {
- lines.push("", colors.strong(verbose ? "Selections" : "Run choices"));
- for (const selection of visibleSelections) {
+ if (view.machine.choices.length > 0) {
+ lines.push("", colors.strong("Run choices"));
+ for (const selection of view.machine.choices) {
const status = colors.success(glyph(io, "✓", "+"));
- const output = view.outputNames?.[selection.output] ?? shortOpaque(selection.output);
- const candidate = view.satisfactionNames?.[selection.output];
- lines.push(` ${status} ${colors.accent(output)}`
- + `${candidate === undefined ? "" : ` ← ${candidate}`}`);
- if (verbose && (output !== selection.output || candidate !== undefined)) {
- lines.push(` ${colors.dim(`${shortOpaque(selection.output)} ← ${shortOpaque(selection.candidate)}`)}`);
- }
+ lines.push(` ${status} ${colors.accent(selection.output)} ← ${selection.candidate}`);
+ }
+ if ((view.machine.omittedChoices ?? 0) > 0) {
+ lines.push(` ${colors.dim(`${view.machine.omittedChoices} more choices · use --limit <count>`)}`);
}
}
return `${lines.join("\n")}\n`;
@@ -417,7 +379,7 @@ export function writeCliOutput(
: presentation.kind === "check-run"
? renderRunCheck(presentation, io, colors)
: presentation.kind === "plan"
- ? renderPlan(presentation, io, colors, options.verbose)
+ ? renderPlan(presentation, io, colors)
: renderOperational(presentation, io, colors);
io.write(output);
}
@@ -426,8 +388,8 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
const common = [
"",
colors.strong("Output"),
- " --json complete machine-readable result",
- " --verbose reveal identities and complete lists",
+ " --json stable machine view",
+ " --verbose add bounded operational detail",
" --color auto|always|never control ANSI color",
" --debug include internal trace frames on failure",
"",
@@ -473,7 +435,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
" hypit runtime unset remove only the local selection",
" hypit runtime up [<profile>] prepare selected packages, programs and Worker",
" hypit runtime status [<profile>] inspect Worker, active Builds and declared programs",
- " hypit runtime logs [<profile>] read Worker logs",
+ " hypit runtime logs [<profile>] [--lines <count>]",
" hypit runtime down [<profile>] stop the Worker; external programs keep running",
],
packages: [
@@ -523,9 +485,9 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
],
inspect: [
colors.accent(colors.strong("hypit inspect")),
- colors.dim("Inspect one project-owned Build Result and every saved public Output."),
+ colors.dim("Inspect one project-owned Build Result and its public Outputs."),
"",
- " hypit inspect <build-id> [--workspace <project>]",
+ " hypit inspect <build-id> [--output <name>] [--limit <count>] [--workspace <project>]",
],
get: [
colors.accent(colors.strong("hypit get")),
@@ -541,7 +503,6 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.dim("Find project Build Outputs from local result manifests."),
"",
" hypit history <output-name> [--workspace <project>] [--source <author-source>] [--limit <count>] [--before <build-id>]",
- " hypit history --source <author-source> [--workspace <project>] [--limit <count>] [--before <build-id>]",
],
cancel: [
colors.accent(colors.strong("hypit cancel")),
@@ -561,23 +522,6 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
" --clear-note remove its note",
" --clear-highlights remove all highlighted Outputs",
],
- image: [
- colors.accent(colors.strong("hypit image")),
- colors.dim("Generate one picture into a file, for an asset that ships inside a package."),
- "",
- " hypit image --prompt <text|text-file> --to <path.png> [--model <package>] [--aspect-ratio <r>] [--resolution <r>]",
- "",
- " --prompt <text|file> the prompt itself, or a text file holding it",
- " --to <path> the file to write; parent directories are created",
- " --model <package> installed package declaring the exact image model",
- " --aspect-ratio <r> a ratio the selected model accepts",
- " --resolution <r> a resolution the selected model accepts",
- "",
- "A package's own chrome is authoring input, so this reads no Source and writes no",
- "Record: no .svml, .svs, .svrun, Build or Runtime Profile takes part. It needs only",
- "the credentials the selected Provider declares.",
- "Unset options take the model's own first declared value.",
- ],
auth: [
colors.accent(colors.strong("hypit auth")),
colors.dim("Manage credentials required by one declared Endpoint instance."),
@@ -594,55 +538,43 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
export function writeCliHelp(io: CliIo, topic?: string): void {
const colors = palette(io.terminal?.isTTY === true && io.terminal.color);
const row = (command: string, description: string, width = 30): string =>
- ` ${command.padEnd(width)}${description}`;
+ ` ${command}${" ".repeat(Math.max(2, width - command.length))}${description}`;
if (topic !== undefined) {
const selected = commandHelp(topic, colors);
if (selected !== undefined) {
- io.write(selected.join("\n"));
+ io.write(`${selected.join("\n")}\n`);
return;
}
}
io.write([
colors.accent(colors.strong("Hypit")),
- colors.dim('"First, there was narration. Then, there were montages."'),
- "",
- colors.strong("Typical flow"),
- row("runtime use <profile>", "select this project's execution environment", 40),
- row("plan <run-source>", "see exactly what this Run will demand", 40),
- row("build <run-source>", "submit durable work; add --follow to watch", 40),
- row("get <build-id>", "export one named Result Output", 40),
- row("doctor [profile]", "diagnose deployment setup when needed", 40),
"",
colors.strong("Authoring"),
row("check <source>", "verify one self-described Author or Run source"),
- row("plan <run-source>", "freeze and inspect a Build plan"),
- row("build <run-source>", "submit a durable Build; --follow only observes"),
- row("image --prompt … --to <path>", "generate one picture file for a package asset"),
+ row("plan <run-source>", "show selected work without executing"),
+ row("build <run-source>", "submit a Build; --follow observes it"),
"",
colors.strong("Results"),
- row("builds", "list known Builds"),
- row("history [output]", "find named historical Build Outputs"),
- row("status <build-id> [--watch]", "show or continuously observe one Build"),
- row("inspect <build-id>", "inspect one project Build Result"),
+ row("builds", "list Results newest first"),
+ row("history <output>", "find one named Output across Builds"),
+ row("status <build-id> [--watch]", "show current work and Result facts"),
+ row("inspect <build-id>", "inspect one Result"),
row("get <build-id> --output <name> --to <path>", "export one Build Output"),
- row("cancel <build-id>", "withdraw one Build and reconcile submitted work"),
- row("result finish <build-id>", "finish an interrupted Result write"),
- row("result discard <build-id>", "discard one incomplete submission"),
- row("result edit <build-id>", "title, annotate or highlight one Result"),
+ row("result edit <build-id>", "title, annotate or highlight a Result"),
"",
colors.strong("Runtime"),
- row("doctor [profile]", "validate deployment without executing"),
+ row("doctor [profile]", "diagnose selected external setup"),
row("runtime use|unset", "select this project's Runtime Profile"),
row("runtime up|status|logs|down", "prepare deployment and manage the Worker"),
row("programs up|status|down", "manage declared external programs only"),
row("packages install|status", "manage pinned upstream packages in the machine home"),
row("activity [--watch]", "inspect active Builds and shared capacity"),
- row("paths", "show every effective state location"),
- row("auth status|login|logout", "manage Endpoint-declared credential references"),
+ row("paths", "show physical state locations"),
+ row("auth status|login|logout", "manage Endpoint credentials"),
"",
colors.strong("Output"),
- row("--json", "complete machine-readable result"),
- row("--verbose", "reveal identities and complete lists"),
+ row("--json", "stable machine view"),
+ row("--verbose", "add bounded operational detail"),
row("--color auto|always|never", "control ANSI color"),
row("--debug", "include internal trace frames on failure"),
"",
diff --git a/packages/cli/src/reachability.ts b/packages/cli/src/reachability.ts
index bb8f802b..b6781e7a 100644
--- a/packages/cli/src/reachability.ts
+++ b/packages/cli/src/reachability.ts
@@ -16,8 +16,7 @@ export type UnreachedGeneration = {
*
* A Run Source does have targets, and planning already prunes to what they reach. So the question
* that can be answered is the one that matters: this Run declares the generation and will not run
- * it. Either nothing needs it, or a target is missing, or an accepted Record should have been
- * pinned and was not.
+ * it. Either nothing needs it, a target is missing, or an explicit Candidate supplies the Output.
*/
export function unreachedGenerations(
graph: CompiledGraph,
diff --git a/packages/cli/src/reuse-markup.ts b/packages/cli/src/reuse-markup.ts
deleted file mode 100644
index 10e1cc54..00000000
--- a/packages/cli/src/reuse-markup.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-export type PinnedRecord = {
- readonly output: string;
- readonly build: string;
- readonly candidate: string;
- readonly markup: readonly string[];
-};
-
-/** Emit explicit Run markup for the newest occurrence of each requested public Output. */
-export function pinnedRecords(
- entries: readonly { readonly build: string; readonly output: { readonly name: string } }[],
-): readonly PinnedRecord[] {
- const seen = new Set<string>();
- const pinned: PinnedRecord[] = [];
- for (const entry of entries) {
- if (seen.has(entry.output.name)) continue;
- seen.add(entry.output.name);
- const candidate = `record-${entry.output.name.replace(/[^a-zA-Z0-9]+/gu, "-").replace(/^-|-$/gu, "")}`;
- pinned.push({
- output: entry.output.name,
- build: entry.build,
- candidate,
- markup: [
- `<build-record id="${candidate}" build="${entry.build}" output="${entry.output.name}"/>`,
- `<satisfy output="${entry.output.name}" candidate="${candidate}"/>`,
- ],
- });
- }
- return pinned;
-}
diff --git a/packages/cli/src/view.ts b/packages/cli/src/view.ts
new file mode 100644
index 00000000..d92ac1af
--- /dev/null
+++ b/packages/cli/src/view.ts
@@ -0,0 +1,217 @@
+import { isAbsolute, relative, resolve, sep } from "node:path";
+
+import type {
+ BuildResultManifest,
+ BuildResultRepository,
+ RepositoryBuildResultOutput,
+} from "@hypit/build-result";
+import { buildIdCreatedAt } from "@hypit/protocol";
+import type { TypeRef } from "@hypit/protocol";
+import type { BuildView } from "@hypit/runtime-host-node";
+
+export type PublicOutputKind = "scalar" | "resource" | "composite";
+
+export type CliOutputView = {
+ readonly name: string;
+ readonly type: string;
+ readonly kind: PublicOutputKind;
+ readonly target: boolean;
+ readonly highlighted: boolean;
+};
+
+export type CliBuildSummary = {
+ readonly id: string;
+ readonly title?: string;
+ readonly createdAt: string;
+ readonly outcome: "complete" | "failed" | "cancelled";
+ readonly run?: string;
+ readonly targetCount: number;
+ readonly targets?: readonly string[];
+ readonly omittedTargets?: number;
+ readonly outputCount: number;
+};
+
+export type CliBuildResultView = {
+ readonly id: string;
+ readonly title?: string;
+ readonly note?: string;
+ readonly createdAt: string;
+ readonly finishedAt?: string;
+ readonly outcome: "open" | "complete" | "failed" | "cancelled";
+ readonly source: string;
+ readonly run?: string;
+ readonly targetCount: number;
+ readonly targets: readonly string[];
+ readonly omittedTargets?: number;
+ readonly outputs: readonly CliOutputView[];
+ readonly omittedOutputs?: number;
+ readonly failure?: string;
+};
+
+export type CliBuildStatusView = {
+ readonly id: string;
+ readonly title?: string;
+ readonly work: {
+ readonly state: "unknown" | "starting" | "active" | "waiting" | "done";
+ readonly outcome?: "complete" | "failed" | "cancelled";
+ readonly cancellationRequested?: boolean;
+ };
+ readonly result: {
+ readonly state: "missing" | "open" | "complete" | "failed" | "cancelled" | "unavailable";
+ readonly outputCount?: number;
+ };
+ readonly attention?: { readonly message: string; readonly action?: string };
+ readonly operations?: readonly {
+ readonly endpoint: string;
+ readonly state: string;
+ readonly progress?: {
+ readonly phase: string;
+ readonly completed?: number;
+ readonly total?: number;
+ readonly unit?: string;
+ };
+ readonly failure?: { readonly code: string; readonly message: string };
+ }[];
+};
+
+export function cliTypeName(type: TypeRef): string {
+ return `${type.module.name}@${type.module.version}/${type.name}`;
+}
+
+export function projectPath(path: string, projectRoot: string): string {
+ const absolute = isAbsolute(path) ? resolve(path) : resolve(projectRoot, path);
+ const local = relative(resolve(projectRoot), absolute);
+ if (local.length === 0) return ".";
+ if (local === ".." || local.startsWith(`..${sep}`)) return path;
+ return local;
+}
+
+export function buildCreatedAtIso(build: string): string {
+ const createdAt = buildIdCreatedAt(build);
+ if (createdAt === undefined) throw new Error(`Build id ${build} has no submission time`);
+ return new Date(createdAt).toISOString();
+}
+
+export function publicOutputKind(output: RepositoryBuildResultOutput): PublicOutputKind {
+ if (output.value.kind === "build-file") return "resource";
+ if (output.value.kind === "value") return "composite";
+ return "scalar";
+}
+
+export async function outputView(
+ repository: BuildResultRepository,
+ manifest: BuildResultManifest,
+ name: string,
+): Promise<CliOutputView> {
+ const output = await repository.resolve(manifest.id, name);
+ if (output === undefined) {
+ throw new Error(`Build Result ${manifest.id} Output ${name} cannot be resolved`);
+ }
+ return {
+ name,
+ type: cliTypeName(output.type),
+ kind: publicOutputKind(output),
+ target: manifest.targets.includes(name),
+ highlighted: manifest.highlightedOutputs?.includes(name) === true,
+ };
+}
+
+function orderedOutputNames(manifest: BuildResultManifest): readonly string[] {
+ const names = Object.keys(manifest.outputs);
+ const highlighted = new Set(manifest.highlightedOutputs ?? []);
+ const targets = new Set(manifest.targets);
+ return names.sort((left, right) => {
+ const leftRank = highlighted.has(left) ? 0 : targets.has(left) ? 1 : 2;
+ const rightRank = highlighted.has(right) ? 0 : targets.has(right) ? 1 : 2;
+ return leftRank - rightRank || left.localeCompare(right);
+ });
+}
+
+function workState(view: BuildView | undefined, result: BuildResultManifest | undefined): CliBuildStatusView["work"]["state"] {
+ if (view === undefined) return result?.outcome === undefined ? "unknown" : "done";
+ if (view.activity === "submitting" || view.activity === "ready") return "starting";
+ if (view.activity === "running") return "active";
+ if (view.activity === "waiting") return "waiting";
+ return "done";
+}
+
+export function buildStatusView(options: {
+ readonly id: string;
+ readonly runtime?: BuildView;
+ readonly result?: BuildResultManifest;
+ readonly resultReadError?: string;
+ readonly verbose?: boolean;
+ readonly operationLimit?: number;
+}): CliBuildStatusView {
+ const resultState = options.resultReadError !== undefined
+ ? "unavailable" as const
+ : options.result?.outcome ?? (options.result === undefined ? "missing" as const : "open" as const);
+ const issue = options.runtime?.issue;
+ return {
+ id: options.id,
+ ...(options.result?.title === undefined ? {} : { title: options.result.title }),
+ work: {
+ state: workState(options.runtime, options.result),
+ ...((options.runtime?.outcome ?? options.result?.outcome) === undefined
+ ? {}
+ : { outcome: options.runtime?.outcome ?? options.result!.outcome }),
+ ...(options.runtime?.cancellationRequested === true ? { cancellationRequested: true } : {}),
+ },
+ result: {
+ state: resultState,
+ ...(options.result === undefined ? {} : { outputCount: Object.keys(options.result.outputs).length }),
+ },
+ ...(issue === undefined && options.resultReadError === undefined ? {} : {
+ attention: issue !== undefined
+ ? {
+ message: issue.message,
+ ...(issue.scope === "result" ? { action: `hypit result finish ${options.id}` } : {}),
+ }
+ : { message: options.resultReadError! },
+ }),
+ ...(!options.verbose || options.runtime === undefined ? {} : {
+ operations: options.runtime.operations
+ .filter((item) => item.status !== "completed")
+ .slice(0, options.operationLimit ?? 20)
+ .map((item) => ({
+ endpoint: item.endpoint,
+ state: item.status,
+ ...(item.progress === undefined ? {} : { progress: item.progress }),
+ ...(item.failure === undefined ? {} : { failure: {
+ code: item.failure.code,
+ message: item.failure.message,
+ } }),
+ })),
+ }),
+ };
+}
+
+export async function buildResultView(
+ repository: BuildResultRepository,
+ manifest: BuildResultManifest,
+ options: { readonly projectRoot: string; readonly output?: string; readonly limit: number },
+): Promise<CliBuildResultView> {
+ if (options.output !== undefined && manifest.outputs[options.output] === undefined) {
+ throw new Error(`Build Result ${manifest.id} has no public Output ${options.output}`);
+ }
+ const allNames = options.output === undefined ? orderedOutputNames(manifest) : [options.output];
+ const selected = allNames.slice(0, options.limit);
+ const outputs = await Promise.all(selected.map(async (name) =>
+ await outputView(repository, manifest, name)));
+ return {
+ id: manifest.id,
+ ...(manifest.title === undefined ? {} : { title: manifest.title }),
+ ...(manifest.note === undefined ? {} : { note: manifest.note }),
+ createdAt: buildCreatedAtIso(manifest.id),
+ ...(manifest.finishedAt === undefined ? {} : { finishedAt: new Date(manifest.finishedAt).toISOString() }),
+ outcome: manifest.outcome ?? "open",
+ source: projectPath(manifest.source.path, options.projectRoot),
+ ...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.path, options.projectRoot) }),
+ targetCount: manifest.targets.length,
+ targets: manifest.targets.slice(0, options.limit),
+ ...(manifest.targets.length <= options.limit ? {} : { omittedTargets: manifest.targets.length - options.limit }),
+ outputs,
+ ...(selected.length === allNames.length ? {} : { omittedOutputs: allNames.length - selected.length }),
+ ...(manifest.failure === undefined ? {} : { failure: manifest.failure }),
+ };
+}
diff --git a/packages/cli/test/build-programs.test.ts b/packages/cli/test/build-programs.test.ts
index 8ca490d6..79dca4f9 100644
--- a/packages/cli/test/build-programs.test.ts
+++ b/packages/cli/test/build-programs.test.ts
@@ -158,7 +158,7 @@ test("Build accepts a Result title and never provisions programs after a clean p
assert.deepEqual(calls, []);
});
-test("plan preserves the frozen plan but exits non-zero when cheap preflight fails", async () => {
+test("plan preserves the selected work summary but exits non-zero when cheap preflight fails", async () => {
const source = await runSource();
let output = "";
let exitCode: number | undefined;
@@ -176,11 +176,11 @@ test("plan preserves the frozen plan but exits non-zero when cheap preflight fai
);
const value = JSON.parse(output) as {
readonly ok: boolean;
- readonly plan: unknown;
+ readonly steps: number;
readonly preflight: { readonly ok: boolean };
};
assert.equal(value.ok, false);
assert.equal(value.preflight.ok, false);
- assert.notEqual(value.plan, undefined);
+ assert.equal(typeof value.steps, "number");
assert.equal(exitCode, 1);
});
diff --git a/packages/cli/test/build-results.test.ts b/packages/cli/test/build-results.test.ts
index 29d12653..5dbe1d1e 100644
--- a/packages/cli/test/build-results.test.ts
+++ b/packages/cli/test/build-results.test.ts
@@ -61,17 +61,19 @@ test("builds, history, inspect and get read project Build Results without openin
await fixture(root);
const builds = await jsonCommand(["builds"], root) as {
readonly builds: readonly {
- readonly build: string;
+ readonly id: string;
readonly title?: string;
readonly outcome: string;
- readonly outputs: readonly string[];
+ readonly outputCount: number;
}[];
};
assert.equal(builds.builds.length, 1);
- assert.equal(builds.builds[0]?.build, "bld_20260902T110000000Z_0000000001");
+ assert.equal(builds.builds[0]?.id, "bld_20260902T110000000Z_0000000001");
assert.equal(builds.builds[0]?.title, "episode-stage");
assert.equal(builds.builds[0]?.outcome, "complete");
- assert.deepEqual(builds.builds[0]?.outputs, ["stage.value"]);
+ assert.equal(builds.builds[0]?.outputCount, 1);
+ assert.equal("source" in builds.builds[0]!, false);
+ assert.equal("outputs" in builds.builds[0]!, false);
const history = await jsonCommand(["history", "stage.value"], root) as {
readonly entries: readonly { readonly build: string; readonly output: { readonly name: string } }[];
@@ -81,20 +83,20 @@ test("builds, history, inspect and get read project Build Results without openin
assert.equal(history.entries[0]?.output.name, "stage.value");
const inspected = await jsonCommand(["inspect", "bld_20260902T110000000Z_0000000001"], root) as {
- readonly result: { readonly id: string; readonly title?: string };
+ readonly build: { readonly id: string; readonly title?: string };
};
- assert.equal(inspected.result.id, "bld_20260902T110000000Z_0000000001");
- assert.equal(inspected.result.title, "episode-stage");
+ assert.equal(inspected.build.id, "bld_20260902T110000000Z_0000000001");
+ assert.equal(inspected.build.title, "episode-stage");
const destination = join(root, "exported.json");
const exported = await jsonCommand([
"get", "bld_20260902T110000000Z_0000000001", "--output", "stage.value", "--to", destination,
], root);
assert.deepEqual(exported, {
- format: "hypit.cli-get@3",
+ format: "hypit.cli-get@4",
build: "bld_20260902T110000000Z_0000000001",
output: "stage.value",
- type: valueType,
+ type: "example.result@1/Value",
kind: "scalar",
path: destination,
});
@@ -152,6 +154,16 @@ test("get exports Resource bytes and a self-contained Composite directory", asyn
});
await result.finish({ outcome: "complete" });
+ const inspected = await jsonCommand([
+ "inspect", build, "--output", "final.take",
+ ], root) as {
+ readonly build: { readonly outputs: readonly [{ readonly name: string; readonly kind: string }] };
+ };
+ assert.equal(inspected.build.outputs[0].name, "final.take");
+ assert.equal(inspected.build.outputs[0].kind, "composite");
+ assert.equal("value" in inspected.build.outputs[0], false);
+ assert.equal("path" in inspected.build.outputs[0], false);
+
const resourceDestination = join(root, "output", "final.mp4");
const resource = await jsonCommand([
"get", build, "--output", "final.video", "--to", resourceDestination,
@@ -199,6 +211,15 @@ test("get requires an exact Output name and an explicit destination", async () =
], silent, {} as CliDistribution),
/get requires --to/u,
);
+ await assert.rejects(
+ runCli(["history", "--source", join(root, "main.svml"), "--workspace", root], silent,
+ {} as CliDistribution),
+ /history requires one exact Output name/u,
+ );
+ await assert.rejects(
+ runCli(["history", "stage.value", "--pin", "--workspace", root], silent, {} as CliDistribution),
+ /unknown option --pin/u,
+ );
} finally {
await rm(root, { recursive: true, force: true });
}
@@ -221,10 +242,11 @@ test("result edit changes only the exact project Result presentation without ope
readonly highlightedOutputs: readonly string[];
};
assert.deepEqual(edited, {
- format: "hypit.cli-result-edit@2",
+ format: "hypit.cli-result-edit@3",
build: "bld_20260902T110000000Z_0000000001",
title: "Episode 12 B-roll",
note: "Use the close-up for the opening beat.",
+ highlightedOutputCount: 1,
highlightedOutputs: ["stage.value"],
});
@@ -239,10 +261,12 @@ test("result edit changes only the exact project Result presentation without ope
], root) as {
readonly title: null;
readonly note: null;
+ readonly highlightedOutputCount: number;
readonly highlightedOutputs: readonly string[];
};
assert.equal(cleared.title, null);
assert.equal(cleared.note, null);
+ assert.equal(cleared.highlightedOutputCount, 0);
assert.deepEqual(cleared.highlightedOutputs, []);
} finally {
await rm(root, { recursive: true, force: true });
diff --git a/packages/cli/test/control-commands.test.ts b/packages/cli/test/control-commands.test.ts
index 06c52f21..9c8792af 100644
--- a/packages/cli/test/control-commands.test.ts
+++ b/packages/cli/test/control-commands.test.ts
@@ -46,7 +46,7 @@ test("activity opens Runtime control without constructing execution Providers",
readonly at: number;
readonly builds: readonly unknown[];
};
- assert.equal(result.format, "hypit.cli-activity@1");
+ assert.equal(result.format, "hypit.cli-activity@2");
assert.equal(typeof result.at, "number");
assert.deepEqual(result.builds, []);
});
@@ -112,10 +112,11 @@ test("status --watch follows active execution, then reads its finished Result",
], { write: (text) => { output += text; } }, distribution);
const result = JSON.parse(output) as {
- readonly build: { readonly id: string; readonly outcome: string };
+ readonly build: { readonly id: string; readonly work: { readonly outcome: string }; readonly result: { readonly state: string } };
};
assert.equal(result.build.id, "build-watch");
- assert.equal(result.build.outcome, "complete");
+ assert.equal(result.build.work.outcome, "complete");
+ assert.equal(result.build.result.state, "complete");
assert.deepEqual(calls, [
"control.inspect",
"control.inspect",
@@ -154,10 +155,11 @@ test("status reads a finished project Result without a Runtime", async () => {
], { write: (text) => { output += text; } }, distribution);
const result = JSON.parse(output) as {
- readonly build: { readonly id: string; readonly outcome: string };
+ readonly build: { readonly id: string; readonly work: { readonly outcome: string }; readonly result: { readonly state: string } };
};
assert.equal(result.build.id, "build-finished");
- assert.equal(result.build.outcome, "complete");
+ assert.equal(result.build.work.outcome, "complete");
+ assert.equal(result.build.result.state, "complete");
assert.deepEqual(calls, ["result.read:build-finished", "result.close"]);
});
@@ -172,7 +174,8 @@ test("status preserves Runtime decision and attention when its Result Store is u
targets: [],
acceptedRecords: 0,
outstandingCommands: 0,
- operations: [],
+ operations: [{ endpoint: "kie.internal", status: "failed" as const,
+ failure: { code: "REMOTE", message: "provider detail" } }],
};
const control = {
async inspect() { return view; },
@@ -193,12 +196,16 @@ test("status preserves Runtime decision and attention when its Result Store is u
], { write: (text) => { output += text; }, setExitCode: (code) => { exitCode = code; } }, distribution);
const result = JSON.parse(output) as {
- readonly build: typeof view;
- readonly resultReadError: string;
+ readonly build: {
+ readonly work: { readonly outcome: string };
+ readonly result: { readonly state: string };
+ readonly attention: { readonly message: string };
+ };
};
- assert.equal(result.build.outcome, "failed");
- assert.equal(result.build.issue.scope, "result");
- assert.equal(result.resultReadError, "S3 unavailable");
+ assert.equal(result.build.work.outcome, "failed");
+ assert.equal(result.build.result.state, "unavailable");
+ assert.equal(result.build.attention.message, "S3 unavailable");
+ assert.equal("operations" in result.build, false);
assert.equal(exitCode, 1);
});
@@ -245,7 +252,7 @@ test("result finish writes only an already-decided Result that needs attention",
assert.equal(finishes, 1);
assert.deepEqual(JSON.parse(output), {
- format: "hypit.cli-result-finish@1",
+ format: "hypit.cli-result-finish@2",
build: "build-blocked",
outcome: "complete",
});
@@ -274,7 +281,7 @@ test("result discard invokes only the exact one-shot Result control", async () =
assert.deepEqual(calls, ["discard:build-submitting", "result-control.close", "control.close"]);
assert.deepEqual(JSON.parse(output), {
- format: "hypit.cli-result-discard@1", build: "build-submitting", discarded: true,
+ format: "hypit.cli-result-discard@2", build: "build-submitting", discarded: true,
});
});
@@ -353,9 +360,36 @@ test("auth opens only one Endpoint credential control, never the execution Runti
"credentials.close",
]);
assert.equal((JSON.parse(output) as { readonly endpoint?: string }).endpoint, "kie.project");
+ const machine = JSON.parse(output) as { readonly credentials: readonly Record<string, unknown>[] };
+ assert.equal("ref" in machine.credentials[0]!, false);
+ assert.equal("key" in machine.credentials[0]!, false);
});
-test("auth login rejects a read-only CredentialStore before asking for a secret", async () => {
+test("runtime logs returns only the requested tail and hides its path by default", async () => {
+ const distribution = {
+ openRuntimeHost: async (path: string) => ({
+ profile: path,
+ controller: async () => ({
+ worker: {
+ logs: async () => ({ path: "/private/runtime.log", text: "one\ntwo\nthree\n" }),
+ },
+ }),
+ }),
+ } as unknown as CliDistribution;
+ let output = "";
+ await runCli([
+ "runtime", "logs", "/tmp/runtime.json", "--lines", "2", "--json",
+ ], { write: (text) => { output += text; } }, distribution);
+
+ assert.deepEqual(JSON.parse(output), {
+ format: "hypit.cli-runtime-logs@2",
+ lines: ["two", "three"],
+ totalLines: 3,
+ omittedLines: 1,
+ });
+});
+
+test("auth login explains an environment-owned credential before asking for a secret", async () => {
let prompted = false;
let closed = false;
const credentials = {
@@ -389,7 +423,7 @@ test("auth login rejects a read-only CredentialStore before asking for a secret"
return "must-not-be-read";
},
}, distribution),
- /CredentialStore env is read-only.*set KIE_API_KEY/u,
+ /cannot be written.*set KIE_API_KEY/u,
);
assert.equal(prompted, false);
assert.equal(closed, true);
@@ -429,9 +463,12 @@ test("cancelling a completed Build reports that no cancellation was requested",
], { write: (text) => { output += text; } }, distribution);
assert.deepEqual(JSON.parse(output), {
- format: "hypit.cli-cancel@2",
- build: "build-complete",
+ format: "hypit.cli-cancel@3",
requested: false,
- outcome: "complete",
+ build: {
+ id: "build-complete",
+ work: { state: "done", outcome: "complete" },
+ result: { state: "complete", outputCount: 0 },
+ },
});
});
diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.ts
index cd0d2f71..494c8e3c 100644
--- a/packages/cli/test/output.test.ts
+++ b/packages/cli/test/output.test.ts
@@ -1,259 +1,96 @@
import assert from "node:assert/strict";
import test from "node:test";
-import type { BuildPlan } from "@hypit/protocol";
-
import { renderCliError, writeCliHelp, writeCliOutput } from "../src/output.js";
-import type { PlanPreflight } from "../src/output.js";
-
-const resource = "res_cli-output" as const;
function capture(
options: Parameters<typeof writeCliOutput>[1],
presentation: Parameters<typeof writeCliOutput>[2],
- terminal?: Parameters<typeof writeCliOutput>[0]["terminal"],
): string {
let output = "";
- writeCliOutput({
- write(text) { output += text; },
- ...(terminal === undefined ? {} : { terminal }),
- }, options, presentation);
+ writeCliOutput({ write(text) { output += text; } }, options, presentation);
return output;
}
const human = { json: false, color: "auto", verbose: false } as const;
-test("author check renders a compact human summary without dumping identity", () => {
+test("author check exposes author-facing Outputs, not graph or resource identities", () => {
const output = capture(human, {
kind: "check-author",
- source: "/project/main.svml",
- frontend: "@hypit/markup@1",
machine: {
- format: "hypit.cli-check@1",
+ format: "hypit.cli-check@2",
sourceKind: "author",
ok: true,
+ source: "/project/main.svml",
+ frontend: "@hypit/markup@1",
units: 2,
- sourceAssets: [{ resource }],
- modules: ["@hypit/script@1"],
- exports: [{
- name: "story",
- type: { module: { name: "@hypit/narrative", version: "1" }, name: "Narrative" },
- kind: "logical-output",
- }],
+ assets: 1,
+ modules: 1,
+ outputCount: 1,
+ outputs: [{ name: "story", type: "@hypit/narrative@1/Narrative" }],
},
});
assert.match(output, /✓ Source is valid/u);
- assert.match(output, /Frontend\s+@hypit\/markup@1/u);
assert.match(output, /story\s+@hypit\/narrative@1\/Narrative/u);
- assert.doesNotMatch(output, /res_cli-output/u);
- assert.doesNotMatch(output, /\u001b\[/u);
-});
-
-test("large author exports are bounded until verbose output is requested", () => {
- const exports = Array.from({ length: 15 }, (_, index) => ({
- name: `output-${String(index).padStart(2, "0")}`,
- type: { module: { name: "example", version: "1" }, name: "Value" },
- kind: "logical-output",
- }));
- const presentation = {
- kind: "check-author" as const,
- source: "/project/main.svml",
- frontend: "example@1",
- machine: {
- format: "hypit.cli-check@1" as const,
- sourceKind: "author" as const,
- ok: true as const,
- units: 1,
- sourceAssets: [],
- modules: [],
- exports,
- },
- };
- const compact = capture(human, presentation);
- assert.match(compact, /3 more · use --verbose/u);
- assert.doesNotMatch(compact, /output-14/u);
- assert.match(capture({ ...human, verbose: true }, presentation), /output-14/u);
-});
-
-test("author check hides generated graph plumbing without deleting machine exports", () => {
- const machine = {
- format: "hypit.cli-check@1" as const,
- sourceKind: "author" as const,
- ok: true as const,
- units: 1,
- sourceAssets: [],
- modules: [],
- exports: [{
- name: "final.video",
- type: { module: { name: "example", version: "1" }, name: "Video" },
- kind: "logical-output",
- }, {
- name: "card.__canvas-frame",
- type: { module: { name: "example", version: "1" }, name: "Frame" },
- kind: "record",
- }, {
- name: "rendered.binding-0001",
- type: { module: { name: "example", version: "1" }, name: "Binding" },
- kind: "record",
- }],
- };
- const presentation = {
- kind: "check-author" as const,
- source: "/project/main.svml",
- frontend: "example@1",
- machine,
- };
- const compact = capture(human, presentation);
- assert.match(compact, /final\.video/u);
- assert.doesNotMatch(compact, /__canvas-frame|binding-0001/u);
- assert.match(capture({ ...human, verbose: true }, presentation), /__canvas-frame/u);
- assert.deepEqual(machine.exports.length, 3);
+ assert.doesNotMatch(output, /resource|logical-output|res_/u);
});
-test("JSON mode is exact machine data with no terminal decoration", () => {
+test("JSON mode writes exactly the stable command view", () => {
const machine = {
- format: "hypit.cli-doctor@1" as const,
+ format: "hypit.cli-doctor@2" as const,
ok: false,
- dataRoot: "/project",
+ profile: "/project/hypit.runtime.ts",
+ diagnosticCount: 1,
diagnostics: [{ severity: "error" as const, code: "MISSING", message: "not found" }],
};
- const output = capture({ json: true, color: "always", verbose: true }, {
- kind: "doctor",
- profile: "/project/hypit.runtime.json",
- machine,
- }, { isTTY: true, color: true, unicode: true, columns: 100 });
+ const output = capture({ json: true, color: "always", verbose: true }, { kind: "doctor", machine });
assert.deepEqual(JSON.parse(output), machine);
- assert.doesNotMatch(output, /Hypit Doctor/u);
- assert.doesNotMatch(output, /\u001b\[/u);
+ assert.doesNotMatch(output, /Hypit Doctor|\u001b\[/u);
});
-test("plan keeps named Run choices visible and leaves graph internals to verbose output", () => {
- const plan: BuildPlan = {
- format: "hypit.plan@1",
- steps: [{
- id: "step-1",
- producer: { module: { name: "@hypit/media", version: "1" }, name: "inspect" },
- inputs: {},
- outputs: {},
- needs: { generated: { id: "need-1", result: "record-1" } },
- }, {
- id: "step-2",
- producer: { module: { name: "@hypit/media", version: "1" }, name: "normalize" },
- inputs: {},
- outputs: {},
- needs: {},
- }],
- goals: [],
- outputBindings: [{
- output: "logical:take",
- record: "record:take",
- type: { module: { name: "example.media", version: "1" }, name: "Take" },
- }],
- };
+test("plan presents named choices and bounded external request summaries", () => {
const output = capture(human, {
kind: "plan",
- machine: { format: "hypit.cli-plan@1", ok: true, plan },
- run: "/project/build.svrun",
- outputNames: { "logical:take": "take.video" },
- satisfactionNames: { "logical:take": "preview" },
- selections: [{ output: "logical:take", candidate: "candidate:preview", record: "record:take" }],
+ machine: {
+ format: "hypit.cli-plan@2",
+ ok: true,
+ run: "/project/build.svrun",
+ targetCount: 1,
+ targets: ["take.video"],
+ steps: 2,
+ externalRequestCount: 1,
+ externalRequests: [{ operation: "@hypit/media@1/inspect", count: 1 }],
+ choiceCount: 1,
+ choices: [{ output: "take.video", candidate: "preview" }],
+ },
});
- assert.match(output, /Run choices/u);
assert.match(output, /take\.video\s+← preview/u);
- assert.doesNotMatch(output, /Operations/u);
- assert.match(output, /External requests/u);
- assert.match(output, /1\s+@hypit\/media@1#inspect/u);
- assert.doesNotMatch(output, /No external work was started\./u);
- assert.match(capture({ ...human, verbose: true }, {
- kind: "plan",
- machine: { format: "hypit.cli-plan@1", ok: true, plan },
- run: "/project/build.svrun",
- outputNames: { "logical:take": "take.video" },
- satisfactionNames: { "logical:take": "preview" },
- selections: [{ output: "logical:take", candidate: "candidate:preview", record: "record:take" }],
- }), /2\s+@hypit\/media@1/u);
+ assert.match(output, /1\s+@hypit\/media@1\/inspect/u);
+ assert.doesNotMatch(output, /logical:|record:|step-/u);
});
-test("a plan with no Needs stays compact without knowing any Provider names", () => {
- const plan: BuildPlan = {
- format: "hypit.plan@1",
- steps: [],
- goals: [],
- outputBindings: [],
- };
- const output = capture(human, {
- kind: "plan",
- machine: { format: "hypit.cli-plan@1", ok: true, plan },
- run: "/project/free.svrun",
- });
- assert.match(output, /External requests\s+0/u);
- assert.doesNotMatch(output, /No external requests/u);
-});
-
-test("plan runtime preflight presents only demanded capabilities", () => {
- const plan: BuildPlan = {
- format: "hypit.plan@1",
- steps: [],
- goals: [],
- outputBindings: [],
- };
- const preflight: PlanPreflight = {
- ok: false,
- dataRoot: "/project",
- capabilities: ["@example/image@1#generate"],
- diagnostics: [{
- severity: "error",
- code: "RUNTIME_CREDENTIAL_MISSING",
- message: "Image key is absent",
- }],
- };
- const output = capture(human, {
- kind: "plan",
- machine: { format: "hypit.cli-plan@1", ok: false, plan, preflight },
- run: "/project/images.svrun",
- });
- assert.match(output, /Runtime preflight/u);
- assert.match(output, /@example\/image@1#generate/u);
- assert.match(output, /Image key is absent/u);
-});
-
-test("human errors expose stable codes while JSON errors remain parseable", () => {
- const error = Object.assign(new Error("credential is absent"), { code: "RUNTIME_CREDENTIAL_MISSING" });
- const humanError = renderCliError(error, { json: false, color: false, unicode: true, debug: false });
- assert.match(humanError, /× Command failed/u);
- assert.match(humanError, /RUNTIME_CREDENTIAL_MISSING/u);
- const machine = JSON.parse(renderCliError(error, {
- json: true,
- color: true,
- unicode: true,
- debug: false,
- })) as { readonly format: string; readonly error: { readonly code: string } };
- assert.equal(machine.format, "hypit.cli-error@1");
- assert.equal(machine.error.code, "RUNTIME_CREDENTIAL_MISSING");
-});
-
-test("help is a successful product surface rather than a usage error", () => {
+test("help is concise and describes stable rather than complete output", () => {
let output = "";
writeCliHelp({ write(text) { output += text; } });
assert.match(output, /^Hypit\n/u);
- assert.match(output, /Authoring/u);
- assert.match(output, /--json/u);
- assert.doesNotMatch(output, /CLI_ERROR/u);
+ assert.match(output, /Results/u);
+ assert.match(output, /stable machine view/u);
+ assert.doesNotMatch(output, /Typical flow|complete machine-readable|image --prompt/u);
});
-test("command help explains only the selected shell grammar", () => {
- let output = "";
- writeCliHelp({ write(text) { output += text; } }, "build");
- assert.match(output, /^hypit build\n/u);
- assert.match(output, /--follow/u);
- assert.doesNotMatch(output, /Authoring/u);
+test("human errors expose stable codes while JSON errors stay parseable", () => {
+ const error = Object.assign(new Error("credential is absent"), { code: "RUNTIME_CREDENTIAL_MISSING" });
+ assert.match(renderCliError(error, { json: false, color: false, unicode: true, debug: false }),
+ /RUNTIME_CREDENTIAL_MISSING/u);
+ const machine = JSON.parse(renderCliError(error, {
+ json: true, color: true, unicode: true, debug: false,
+ })) as { readonly error: { readonly code: string } };
+ assert.equal(machine.error.code, "RUNTIME_CREDENTIAL_MISSING");
});
-test("Result commands have their own help instead of falling back to the global screen", () => {
+test("Result help makes exact Output addressing explicit", () => {
let output = "";
writeCliHelp({ write(text) { output += text; } }, "get");
- assert.match(output, /^hypit get\n/u);
assert.match(output, /--output <name> --to <path>/u);
assert.match(output, /Composite Output becomes a directory/u);
- assert.doesNotMatch(output, /Typical flow/u);
});
diff --git a/packages/cli/test/pin.test.ts b/packages/cli/test/pin.test.ts
deleted file mode 100644
index 0fde9ed5..00000000
--- a/packages/cli/test/pin.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { parseRunDocument } from "@hypit/run-markup";
-
-import { pinnedRecords } from "../src/reuse-markup.js";
-
-test("pinned Records emit Run Source markup that parses, one per output", () => {
- const pins = pinnedRecords([
- { build: "bld_newest", output: { name: "paper.image" } },
- { build: "bld_older", output: { name: "paper.image" } },
- { build: "bld_other", output: { name: "apple-plate.image" } },
- ]);
- assert.deepEqual(pins.map((item) => item.output), ["paper.image", "apple-plate.image"]);
- assert.equal(pins[0]!.build, "bld_newest", "the newest accepted Record of an output is the one selected");
-
- const document = [
- `<svrun version="1">`,
- ` <author source="./main.svml"/>`,
- ` <target output="final.video"/>`,
- ...pins.flatMap((item) => item.markup).map((line) => ` ${line}`),
- `</svrun>`,
- ].join("\n");
- // Emitting markup nobody can parse would be worse than emitting nothing, because it reads as done.
- const parsed = parseRunDocument("pin.svrun", document);
- assert.equal(parsed.candidates.length, 2);
- assert.equal(parsed.satisfactions.length, 2);
-});
diff --git a/packages/video-cli/README.md b/packages/video-cli/README.md
index 63682937..afd7f0f2 100644
--- a/packages/video-cli/README.md
+++ b/packages/video-cli/README.md
@@ -18,12 +18,11 @@ hypit build build.svrun --follow
hypit status <build-id> --watch
hypit activity
hypit builds
-hypit history [source-output-name] [--source ./main.svml] [--pin] [--exclude-targets]
-hypit inspect <build-id>
+hypit history <source-output-name> [--source ./main.svml]
+hypit inspect <build-id> [--output <source-output-name>]
hypit get <build-id> --output final.video --to ./final.mp4
hypit cancel <build-id>
hypit doctor
-hypit gc
```
Install the `hypit` Distribution globally once. It resolves its own TypeScript loader and CLI, so it
@@ -70,6 +69,13 @@ changes Build identity or retention; large media does not need to be loaded into
`builds` and `history` browse project-owned Result manifests newest first. `--before <build-id>` moves
the cursor to older Results without a central history table. Presentation titles, notes and highlights
live in the Result manifest and may be edited without changing the Build id or the saved Outputs.
+`history` always asks for one exact Output name; it never chooses a Result or writes reuse markup.
+Use the returned Build id and Output name explicitly in a Run Source when reusing that value.
+
+Human output is compact and organized around author-facing names. `--json` returns a stable, bounded
+command view rather than Repository manifests or Runtime persistence objects. `--verbose` adds bounded
+operational detail; physical state locations remain the job of `paths`, while `get --to` and
+`runtime logs --verbose` expose the paths those commands explicitly operate on.
Historical Records, fixed files and generated previews are declared as ordinary Candidates in the
Run Source and selected by explicit Satisfaction edges. The Host verifies a referenced prior Build
diff --git a/packages/video-cli/src/cli.ts b/packages/video-cli/src/cli.ts
index d1879461..ffe960fa 100644
--- a/packages/video-cli/src/cli.ts
+++ b/packages/video-cli/src/cli.ts
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import { renderCliError, writeCliHelp } from "@hypit/cli";
import type { CliIo } from "@hypit/cli";
+import { writeVideoImageHelp } from "./image-command.js";
const argv = process.argv.slice(2);
const json = argv.includes("--json");
@@ -59,7 +60,11 @@ const io: CliIo = {
async function main(): Promise<void> {
if (argv.length === 0 || argv[0] === "help" || argv.includes("--help")) {
const topic = argv[0] === "help" ? argv[1] : argv.includes("--help") ? argv[0] : undefined;
- writeCliHelp(io, topic);
+ if (topic === "image") writeVideoImageHelp(io);
+ else {
+ writeCliHelp(io, topic);
+ if (topic === undefined) io.write("\nVideo utility\n image --prompt <text|file> --to <path> create authoring input\n");
+ }
return;
}
const { runVideoCli } = await import("./index.js");
diff --git a/packages/video-cli/src/distribution.ts b/packages/video-cli/src/distribution.ts
index 589fe4e6..bd0cd9a2 100644
--- a/packages/video-cli/src/distribution.ts
+++ b/packages/video-cli/src/distribution.ts
@@ -24,10 +24,6 @@ export const videoCliDistribution: CliDistribution = {
const { discoverVideoSourcePackages } = await import("./package-selection.js");
return await discoverVideoSourcePackages(path, options);
},
- generatePicture: async (request) => {
- const { generateVideoCliPicture } = await import("./picture.js");
- return await generateVideoCliPicture(request);
- },
openRuntimeHost: async (path, options) => await openLocalRuntimeHost(path, {
packageRoot: options.packageRoot,
...(options.distributionPackageRoot === undefined
diff --git a/packages/video-cli/src/image-command.ts b/packages/video-cli/src/image-command.ts
new file mode 100644
index 00000000..6e1d63c7
--- /dev/null
+++ b/packages/video-cli/src/image-command.ts
@@ -0,0 +1,126 @@
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+
+import type { CliIo } from "@hypit/cli";
+
+import { generateVideoCliPicture } from "./picture.js";
+
+type ImageArgs = {
+ readonly prompt: string;
+ readonly to: string;
+ readonly model?: string;
+ readonly aspectRatio?: string;
+ readonly resolution?: string;
+ readonly json: boolean;
+};
+
+async function nearestPackageRoot(start: string): Promise<string> {
+ let directory = resolve(start);
+ while (true) {
+ const manifest = resolve(directory, "package.json");
+ if (await stat(manifest).then((item) => item.isFile(), () => false)) return directory;
+ const parent = dirname(directory);
+ if (parent === directory) return resolve(start);
+ directory = parent;
+ }
+}
+
+async function promptText(value: string): Promise<string> {
+ const path = resolve(value);
+ const isFile = await stat(path).then((item) => item.isFile(), () => false);
+ const prompt = (isFile ? await readFile(path, "utf8") : value).trim();
+ if (prompt.length === 0) throw new Error(isFile ? `prompt file ${path} is empty` : "--prompt is empty");
+ return prompt;
+}
+
+function parseImageArgs(argv: readonly string[]): ImageArgs {
+ let prompt: string | undefined;
+ let to: string | undefined;
+ let model: string | undefined;
+ let aspectRatio: string | undefined;
+ let resolution: string | undefined;
+ let json = false;
+ const seen = new Set<string>();
+ for (let index = 1; index < argv.length; index += 1) {
+ const option = argv[index]!;
+ if (option === "--json") { json = true; continue; }
+ if (option === "--debug" || option === "--verbose" || option === "--no-color") continue;
+ if (option === "--color") {
+ const value = argv[index + 1];
+ if (value !== "auto" && value !== "always" && value !== "never") {
+ throw new Error("--color requires auto, always or never");
+ }
+ index += 1;
+ continue;
+ }
+ if (!["--prompt", "--to", "--model", "--aspect-ratio", "--resolution"].includes(option)) {
+ throw new Error(`unknown option ${option}`);
+ }
+ if (seen.has(option)) throw new Error(`${option} cannot be repeated`);
+ seen.add(option);
+ const value = argv[index + 1];
+ if (value === undefined || value.startsWith("--")) throw new Error(`${option} requires a value`);
+ if (option === "--prompt") prompt = value;
+ else if (option === "--to") to = resolve(value);
+ else if (option === "--model") model = value;
+ else if (option === "--aspect-ratio") aspectRatio = value;
+ else resolution = value;
+ index += 1;
+ }
+ if (prompt === undefined) throw new Error("image requires --prompt with text or a text file path");
+ if (to === undefined) throw new Error("image requires --to with the file to write");
+ return { prompt, to, json, ...(model === undefined ? {} : { model }),
+ ...(aspectRatio === undefined ? {} : { aspectRatio }),
+ ...(resolution === undefined ? {} : { resolution }) };
+}
+
+export function writeVideoImageHelp(io: CliIo): void {
+ io.write([
+ "hypit image",
+ "Generate one image file used as video authoring input.",
+ "",
+ " hypit image --prompt <text|file> --to <path> [--model <package>]",
+ " [--aspect-ratio <ratio>] [--resolution <size>]",
+ "",
+ "This is a video-distribution utility. It creates no Build or Result.",
+ "",
+ ].join("\n"));
+}
+
+export async function runVideoImageCli(
+ argv: readonly string[],
+ io: CliIo,
+ distributionPackageRoot?: string,
+): Promise<void> {
+ const args = parseImageArgs(argv);
+ if (await stat(args.to).then(() => true, () => false)) {
+ throw new Error(`Image destination ${args.to} already exists`);
+ }
+ const picture = await generateVideoCliPicture({
+ prompt: await promptText(args.prompt),
+ packageRoot: await nearestPackageRoot(process.cwd()),
+ ...(distributionPackageRoot === undefined ? {} : { distributionPackageRoot }),
+ ...(args.model === undefined ? {} : { model: args.model }),
+ ...(args.aspectRatio === undefined ? {} : { aspectRatio: args.aspectRatio }),
+ ...(args.resolution === undefined ? {} : { resolution: args.resolution }),
+ });
+ await mkdir(dirname(args.to), { recursive: true });
+ try {
+ await writeFile(args.to, picture.bytes, { flag: "wx" });
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
+ throw new Error(`Image destination ${args.to} already exists`);
+ }
+ throw error;
+ }
+ const view = {
+ format: "hypit.video-cli-image@1",
+ model: picture.model,
+ package: picture.package,
+ mediaType: picture.mediaType,
+ bytes: picture.bytes.byteLength,
+ path: args.to,
+ } as const;
+ if (args.json) io.write(`${JSON.stringify(view, null, 2)}\n`);
+ else io.write(`✓ Picture written\n\n ${picture.model} · ${picture.mediaType}\n ${args.to}\n`);
+}
diff --git a/packages/video-cli/src/index.ts b/packages/video-cli/src/index.ts
index e2164ff7..2cebe101 100644
--- a/packages/video-cli/src/index.ts
+++ b/packages/video-cli/src/index.ts
@@ -8,6 +8,8 @@ import { hypitHostPackageRoot } from "@hypit/runtime-host-node";
import type { LoadedPackage } from "@hypit/package-loader-node";
import { videoCliDistribution } from "./distribution.js";
+import { runVideoImageCli } from "./image-command.js";
+import { writeVideoImageHelp } from "./image-command.js";
export {
createVideoCompiler,
@@ -24,6 +26,14 @@ export function runVideoCli(
? []
: [videoCliDistribution.packageRoot]);
installExternalPackageResolution([hypitHostPackageRoot()]);
+ if ((argv[0] === "image" && argv.includes("--help"))
+ || (argv[0] === "help" && argv[1] === "image")) {
+ writeVideoImageHelp(io);
+ return Promise.resolve();
+ }
+ if (argv[0] === "image") {
+ return runVideoImageCli(argv, io, videoCliDistribution.packageRoot);
+ }
return runCli(argv, io, {
...videoCliDistribution,
bootstrapPackages: packages,
diff --git a/packages/video-cli/src/picture.ts b/packages/video-cli/src/picture.ts
index b9a4acc9..52279be7 100644
--- a/packages/video-cli/src/picture.ts
+++ b/packages/video-cli/src/picture.ts
@@ -1,4 +1,3 @@
-import type { CliPicture, CliPictureRequest } from "@hypit/cli";
import { EnvironmentCredentialStore } from "@hypit/credential-store-env";
import { OsCredentialStore } from "@hypit/credential-store-os";
import { EndpointRegistry, MemoryResourceStore } from "@hypit/driver-node";
@@ -24,6 +23,22 @@ const optionPorts = {
resolution: "--resolution",
} as const;
+export type VideoCliPictureRequest = {
+ readonly model?: string;
+ readonly prompt: string;
+ readonly aspectRatio?: string;
+ readonly resolution?: string;
+ readonly packageRoot: string;
+ readonly distributionPackageRoot?: string;
+};
+
+export type VideoCliPicture = {
+ readonly package: string;
+ readonly model: string;
+ readonly mediaType: string;
+ readonly bytes: Uint8Array;
+};
+
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
@@ -58,7 +73,7 @@ async function selectImageModel(
*/
function portValue(
port: GenerationPort,
- request: CliPictureRequest,
+ request: VideoCliPictureRequest,
model: string,
): GenerationPortValue | undefined {
if (port.name === "prompt") return request.prompt;
@@ -74,7 +89,7 @@ function portValue(
throw new Error(`${model} requires ${port.name}, which hypit image cannot supply`);
}
-function sealPictureRequest(endpoint: ExactModelEndpoint, request: CliPictureRequest): CanonicalValue {
+function sealPictureRequest(endpoint: ExactModelEndpoint, request: VideoCliPictureRequest): CanonicalValue {
const table = endpoint.ports;
for (const [name, option] of Object.entries(optionPorts)) {
if (request[name as keyof typeof optionPorts] === undefined) continue;
@@ -140,7 +155,7 @@ async function readPicture(
* ResourceStore and the Provider all live for the length of this one call, and no
* Build, Record or Runtime Profile observes any of it.
*/
-export async function generateVideoCliPicture(request: CliPictureRequest): Promise<CliPicture> {
+export async function generateVideoCliPicture(request: VideoCliPictureRequest): Promise<VideoCliPicture> {
const specifier = request.model ?? defaultPictureModel;
const model = await selectImageModel(specifier, request.packageRoot, request.distributionPackageRoot);
const need: Need = {
diff --git a/packages/video-cli/test/cli.test.ts b/packages/video-cli/test/cli.test.ts
index 08112369..227d5827 100644
--- a/packages/video-cli/test/cli.test.ts
+++ b/packages/video-cli/test/cli.test.ts
@@ -51,15 +51,14 @@ test("provider-free example plans from installed Source packages", async () => {
"--workspace",
process.cwd(),
], { write: (text) => { output += text; } });
- const plan = (JSON.parse(output) as { readonly plan: {
- readonly goals: readonly unknown[];
- readonly steps: readonly { readonly producer: { readonly name: string } }[];
- } }).plan;
- const producers = new Set(plan.steps.map((step) => step.producer.name));
- assert.equal(producers.has("assemble-semantic-track"), true);
- assert.equal(producers.has("compile-composition"), true);
- assert.equal(producers.has("project-muxed-media"), true);
- assert.equal(plan.goals.length, 1);
+ const plan = JSON.parse(output) as {
+ readonly format: string;
+ readonly steps: number;
+ readonly targets: readonly string[];
+ };
+ assert.equal(plan.format, "hypit.cli-plan@2");
+ assert.equal(plan.steps > 0, true);
+ assert.equal(plan.targets.length, 1);
});
/**
@@ -107,12 +106,12 @@ test("image writes one picture file with no Source, Build, Record or Runtime Pro
], { write: (text) => { output += text; } });
const machine = JSON.parse(output) as {
readonly package: string; readonly model: string;
- readonly mediaType: string; readonly size: number; readonly path: string;
+ readonly mediaType: string; readonly bytes: number; readonly path: string;
};
assert.equal(machine.package, "@hypit/gpt-image");
assert.equal(machine.model, "gpt-image-2");
assert.equal(machine.mediaType, "image/png");
- assert.equal(machine.size, pictureBytes.byteLength);
+ assert.equal(machine.bytes, pictureBytes.byteLength);
assert.equal(machine.path, destination);
assert.deepEqual(Uint8Array.from(await readFile(destination)), pictureBytes);
// The author gave one option; every other port took the model's own first value.