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.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
refactor(cli): separate commands from storage details
kashorinc5dbb4defc90
diff --git a/docs/quickstart/run.md b/docs/quickstart/run.mdindex 14544db0..ca5b1c2e 100644--- a/docs/quickstart/run.md+++ b/docs/quickstart/run.md@@ -298,10 +298,11 @@ owns their versions.hypit doctor```-Doctor validates every selected Runtime role, Endpoint configuration, credential-presence and bounded environment probes. It never starts the Worker or performs a paid request.+Doctor always validates the project's selected Result Store. When a Runtime Profile is selected or+passed explicitly, it also validates every selected Runtime role, Endpoint configuration, credential+presence and bounded environment probe. It never starts the Worker or performs a paid request.-Doctor is intentionally a **full profile audit**. For the environment required by one Run, use+When a Profile is present, Doctor intentionally performs a **full profile audit**. For the environment required by one Run, use`plan`: it checks only capabilities demanded by that finite plan. Missing readiness is returned in`preflight` and gives the command a non-zero exit status, while the frozen plan remains available inJSON for inspection.diff --git a/docs/zh/quickstart/run.md b/docs/zh/quickstart/run.mdindex 25be4609..d8560e94 100644--- a/docs/zh/quickstart/run.md+++ b/docs/zh/quickstart/run.md@@ -296,9 +296,10 @@ Author/Run Source 通过 import 选择作者包,Runtime Profile 通过 `use`hypit doctor```-Doctor 校验全部显式 Runtime 角色、Endpoint 配置、凭据是否存在和有界环境探测;它不启动 Worker,也不发付费请求。+Doctor 总会校验项目选择的 Result Store;存在已选或显式传入的 Runtime Profile 时,还会校验全部+Runtime 角色、Endpoint 配置、凭据是否存在和有界环境探测。它不启动 Worker,也不发付费请求。-`doctor` 有意检查完整 Runtime Profile。若只想检查某次 Run 真正需要的环境,请使用带+存在 Profile 时,`doctor` 有意检查完整 Runtime Profile。若只想检查某次 Run 真正需要的环境,请使用带所选 Runtime 的 `plan`。未就绪会写入 `preflight` 并令命令非零退出,但 JSON 中仍保留冻结计划供检查。diff --git a/packages/build-result-s3/src/repository.ts b/packages/build-result-s3/src/repository.tsindex c24e0a0f..6d47ccae 100644--- a/packages/build-result-s3/src/repository.ts+++ b/packages/build-result-s3/src/repository.ts@@ -10,6 +10,7 @@ import type {BuildResultWriter,BuildResultWriterState,RepositoryBuildResultOutput,+ RepositoryBuildResultOutputDescription,} from "@hypit/build-result";import {applyBuildResultPresentation,@@ -266,6 +267,30 @@ export class S3BuildResultRepository implements BuildResultRepository {};}+ async describeOutput(build: string, output: string): Promise<RepositoryBuildResultOutputDescription | undefined> {+ const seen = new Set<string>();+ let currentBuild = build;+ let currentOutput = output;+ while (true) {+ const address = `${currentBuild}\u0000${currentOutput}`;+ assert(!seen.has(address), `Build Output forwarding repeats ${currentBuild} / ${currentOutput}`);+ seen.add(address);+ const manifest = await this.read(currentBuild);+ const entry = manifest?.outputs[currentOutput];+ if (entry === undefined) return undefined;+ if (entry.value.kind === "build-output") {+ currentBuild = entry.value.build;+ currentOutput = entry.value.output;+ continue;+ }+ return entry.value.kind === "build-file"+ ? { type: entry.type, kind: "resource", size: entry.value.size, mediaType: entry.value.mediaType }+ : entry.value.kind === "value"+ ? { type: entry.type, kind: "composite" }+ : { type: entry.type, kind: "scalar" };+ }+ }+async resolve(build: string, output: string): Promise<RepositoryBuildResultOutput | undefined> {const seen = new Set<string>();let currentBuild = build;diff --git a/packages/build-result-s3/test/repository.test.ts b/packages/build-result-s3/test/repository.test.tsindex 96243eae..401022da 100644--- a/packages/build-result-s3/test/repository.test.ts+++ b/packages/build-result-s3/test/repository.test.ts@@ -363,6 +363,8 @@ test("S3 forwarding can cross several Builds without copying the historical fileawait forward("bld_20260902T100000002Z_0000000001", "bld_20260902T100000001Z_0000000001");await forward("bld_20260902T100000003Z_0000000001", "bld_20260902T100000002Z_0000000001");+ const described = await repository.describeOutput("bld_20260902T100000003Z_0000000001", "video");+ assert.equal(described?.kind, "resource");const resolved = await repository.resolve("bld_20260902T100000003Z_0000000001", "video");assert.equal(resolved?.build, "bld_20260902T100000001Z_0000000001");assert.equal(resolved?.value.kind, "build-file");diff --git a/packages/build-result/src/index.ts b/packages/build-result/src/index.tsindex 7c3ae309..1418bca1 100644--- a/packages/build-result/src/index.ts+++ b/packages/build-result/src/index.ts@@ -16,6 +16,7 @@ export {applyBuildResultPresentation,browseBuildResults,buildResultDirectory,+ describeBuildResultOutput,readBuildResult,resolveBuildResultOutput,} from "./store.js";diff --git a/packages/build-result/src/store.ts b/packages/build-result/src/store.tsindex 1782929d..112dc480 100644--- a/packages/build-result/src/store.ts+++ b/packages/build-result/src/store.ts@@ -27,6 +27,7 @@ import type {ResolvedBuildResultOutput,BuildResultRepository,RepositoryBuildResultOutput,+ RepositoryBuildResultOutputDescription,FinishedBuildResultManifest,} from "./types.js";import { assertBuildResultSeed } from "./types.js";@@ -240,6 +241,34 @@ export async function resolveBuildResultOutput(}}+export async function describeBuildResultOutput(+ root: string,+ build: string,+ output: string,+): Promise<RepositoryBuildResultOutputDescription | undefined> {+ const seen = new Set<string>();+ let currentBuild = build;+ let currentOutput = output;+ while (true) {+ const address = `${currentBuild}\u0000${currentOutput}`;+ assert(!seen.has(address), `Build Output forwarding repeats ${currentBuild} / ${currentOutput}`);+ seen.add(address);+ const manifest = await readBuildResult(buildResultDirectory(root, currentBuild));+ const entry = manifest?.outputs[currentOutput];+ if (entry === undefined) return undefined;+ if (entry.value.kind === "build-output") {+ currentBuild = entry.value.build;+ currentOutput = entry.value.output;+ continue;+ }+ return entry.value.kind === "build-file"+ ? { type: entry.type, kind: "resource", size: entry.value.size, mediaType: entry.value.mediaType }+ : entry.value.kind === "value"+ ? { type: entry.type, kind: "composite" }+ : { type: entry.type, kind: "scalar" };+ }+}+export class FileBuildResult {readonly directory: string;@@ -385,6 +414,10 @@ export class FileBuildResultRepository implements BuildResultRepository {return await browseBuildResults(this.root, request);}+ async describeOutput(build: string, output: string): Promise<RepositoryBuildResultOutputDescription | undefined> {+ return await describeBuildResultOutput(this.root, build, output);+ }+async resolve(build: string, output: string): Promise<RepositoryBuildResultOutput | undefined> {const resolvedOutput = await resolveBuildResultOutput(this.root, build, output);if (resolvedOutput === undefined) return undefined;diff --git a/packages/build-result/src/types.ts b/packages/build-result/src/types.tsindex 23447f25..94332f0e 100644--- a/packages/build-result/src/types.ts+++ b/packages/build-result/src/types.ts@@ -290,6 +290,19 @@ export type ResolvedBuildResultOutput = {/** Storage-neutral resolved Output. Physical repositories never enter Build or Run identity. */export type RepositoryBuildResultOutput = Omit<ResolvedBuildResultOutput, "directory">;+/**+ * Storage-neutral description of one resolved public Output. Unlike `resolve`, this never opens a+ * Composite value document or Resource bytes. Forwarding remains internal: callers cannot use this+ * view to distinguish a forwarded Output from one produced by the named Build.+ */+export type RepositoryBuildResultOutputDescription = {+ readonly type: TypeRef;+} & (+ | { readonly kind: "scalar" }+ | { readonly kind: "composite" }+ | { readonly kind: "resource"; readonly size: number; readonly mediaType: string }+);+export type BuildResultWriter = {read(): Promise<BuildResultManifest>;sync(input: BuildResultSync): Promise<BuildResultManifest>;@@ -310,6 +323,8 @@ export type BuildResultRepository = {updatePresentation(build: string, update: BuildResultPresentationUpdate): Promise<BuildResultManifest>;/** Browse finished Results in descending Build-id time order. */browse(request: BuildResultBrowseRequest): Promise<BuildResultPage>;+ /** Follow explicit Output forwarding and describe its terminal value without opening content. */+ describeOutput(build: string, output: string): Promise<RepositoryBuildResultOutputDescription | undefined>;resolve(build: string, output: string): Promise<RepositoryBuildResultOutput | undefined>;openFile(build: string,diff --git a/packages/build-result/test/result.test.ts b/packages/build-result/test/result.test.tsindex f46b2f65..ad6f3095 100644--- a/packages/build-result/test/result.test.ts+++ b/packages/build-result/test/result.test.ts@@ -239,6 +239,29 @@ test("reserved-looking domain objects remain ordinary Composite data", async ()}});+test("describing a Composite Output reads only its manifest", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-result-describe-"));+ const id = "bld_20260902T100000020Z_0000000001";+ try {+ const directory = join(root, id);+ await mkdir(directory, { recursive: true });+ await writeFile(join(directory, "result.json"), JSON.stringify({+ format: "hypit.build-result@2",+ source: { path: "main.svml" },+ targets: ["take"],+ outcome: "complete",+ finishedAt: 1,+ outputs: { take: { type: takeType, value: { kind: "value", path: "values/missing.json" } } },+ }));+ const repository = new FileBuildResultRepository(root);+ const description = await repository.describeOutput(id, "take");+ assert.equal(description?.kind, "composite");+ await assert.rejects(repository.resolve(id, "take"), /missing\.json/u);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});+test("an explicitly reused public output is a forward reference and copies no bytes", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-build-result-reuse-"));try {diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 82bde8b4..f7a9b355 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -14,3 +14,11 @@ not invent targets, candidates or provider choices.Human output is compact by default. `--json` emits a stable, bounded command view rather than rawcompiler, Runtime or Repository objects. `--verbose` adds bounded operational detail; it never turnsthe command into an internal state dump.++The implementation follows those same boundaries: argument parsing and option ownership live in+`arguments.ts`; project Result browsing/export lives under `commands/results.ts`; Runtime,+credential, package and deployment operations live under `commands/environment.ts`; active Build+observation is read-only code in `observation.ts`; and human rendering is separate from the explicit+machine-view union. `main.ts` resolves project context and dispatches these command groups. Result+commands cannot silently construct a Runtime, and the generic CLI cannot silently choose a physical+Result Store or a Provider-specific login flow.diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.tsnew file mode 100644index 00000000..314ec4d3--- /dev/null+++ b/packages/cli/src/arguments.ts@@ -0,0 +1,288 @@+import { resolve } from "node:path";++import type { CliColorMode } from "./output.js";++export type CliCommandName =+ | "check" | "plan" | "build"+ | "builds" | "history" | "inspect" | "get" | "status" | "activity" | "cancel" | "result"+ | "runtime" | "programs" | "packages" | "auth" | "doctor" | "paths"+ | "_worker";++export type ParsedArgs = {+ readonly command: string | undefined;+ readonly action: string | undefined;+ readonly file: string | undefined;+ readonly workspaceRoot: string | undefined;+ readonly assetRoots: readonly string[];+ readonly packageRoot: string | undefined;+ readonly runtime: string | undefined;+ readonly follow: boolean;+ readonly maxWaitMs: number | undefined;+ readonly output: string | undefined;+ readonly title: string | undefined;+ readonly note: string | undefined;+ readonly highlightedOutputs: readonly string[];+ readonly clearTitle: boolean;+ readonly clearNote: boolean;+ readonly clearHighlights: boolean;+ readonly limit: number;+ readonly lines: number;+ readonly before: string | undefined;+ readonly to: string | undefined;+ readonly json: boolean;+ readonly color: CliColorMode;+ readonly verbose: boolean;+ readonly watch: boolean;+ readonly jsonl: boolean;+ readonly readyFile: string | undefined;+ readonly workerOwner: string | undefined;+ readonly reason: string | undefined;+ readonly slot: string | undefined;+ readonly from: string | undefined;+ readonly source: string | undefined;+ readonly seenOptions: readonly string[];+};++const scopedCommands = new Set(["programs", "runtime", "auth", "result", "packages"]);+const positionalOptionalCommands = new Set(["builds", "history", "activity", "paths", "programs", "runtime", "doctor"]);+const knownCommands = new Set<CliCommandName>([+ "check", "plan", "build", "builds", "history", "inspect", "get", "status", "activity", "cancel",+ "result", "runtime", "programs", "packages", "auth", "doctor", "paths", "_worker",+]);++export function isKnownCommand(value: string | undefined): value is CliCommandName {+ return value !== undefined && knownCommands.has(value as CliCommandName);+}++export function commandAllowsMissingPositional(value: string | undefined): boolean {+ return value !== undefined && positionalOptionalCommands.has(value);+}++export function parseArgs(argv: readonly string[]): ParsedArgs {+ const [command, ...tail] = argv;+ const scoped = command !== undefined && scopedCommands.has(command);+ const action = scoped ? tail[0] : undefined;+ const positional = scoped ? tail.slice(1) : tail;+ const noFile = command === "builds" || command === "activity" || command === "paths";+ const hasFile = !noFile && positional[0] !== undefined && !positional[0]!.startsWith("--");+ const file = hasFile ? positional[0] : undefined;+ const rest = noFile || !hasFile ? positional : positional.slice(1);+ let workspaceRoot: string | undefined;+ const assetRoots: string[] = [];+ let packageRoot: string | undefined;+ let runtime: string | undefined;+ let follow = false;+ let maxWaitMs: number | undefined;+ let output: string | undefined;+ let title: string | undefined;+ let note: string | undefined;+ const highlightedOutputs: string[] = [];+ let clearTitle = false;+ let clearNote = false;+ let clearHighlights = false;+ let limit = 20;+ let lines = 50;+ let before: string | undefined;+ let to: string | undefined;+ let json = false;+ let color: CliColorMode = "auto";+ let verbose = false;+ let watch = false;+ let jsonl = false;+ let readyFile: string | undefined;+ let workerOwner: string | undefined;+ let reason: string | undefined;+ let slot: string | undefined;+ let from: string | undefined;+ let source: string | undefined;+ const seenOptions = new Set<string>();+ for (let index = 0; index < rest.length; index += 1) {+ const item = rest[index]!;+ if (item.startsWith("--")) {+ const repeatable = [+ "--json", "--jsonl", "--watch", "--verbose", "--debug",+ "--no-color", "--follow", "--asset-root", "--highlight",+ ].includes(item);+ if (!repeatable && seenOptions.has(item)) throw new Error(`${item} cannot be repeated`);+ seenOptions.add(item);+ }+ if (item === "--json") { json = true; continue; }+ if (item === "--jsonl") { jsonl = true; continue; }+ if (item === "--watch") { watch = true; continue; }+ if (item === "--verbose") { verbose = true; continue; }+ if (item === "--debug") continue;+ if (item === "--no-color") { color = "never"; continue; }+ if (item === "--color") {+ const value = rest[index + 1];+ if (value !== "auto" && value !== "always" && value !== "never") {+ throw new Error("--color requires auto, always or never");+ }+ color = value;+ index += 1;+ continue;+ }+ if (item === "--workspace") {+ const value = optionValue(rest, index, "--workspace requires a directory");+ workspaceRoot = resolve(value); index += 1; continue;+ }+ if (item === "--asset-root") {+ const value = optionValue(rest, index, "--asset-root requires a directory");+ assetRoots.push(resolve(value)); index += 1; continue;+ }+ if (item === "--package-root") {+ const value = optionValue(rest, index, "--package-root requires a directory");+ packageRoot = resolve(value); index += 1; continue;+ }+ if (item === "--runtime") {+ const value = optionValue(rest, index, "--runtime requires a Runtime Profile");+ runtime = resolve(value); index += 1; continue;+ }+ if (item === "--out") {+ throw new Error("--out does not apply to Build submission; use `get <build-id> --output <name> --to <path>` to export one Result Output");+ }+ if (item === "--output") {+ output = optionValue(rest, index, "--output requires a public Output name"); index += 1; continue;+ }+ if (item === "--title") {+ title = optionValue(rest, index, "--title requires text"); index += 1; continue;+ }+ if (item === "--note") {+ note = optionValue(rest, index, "--note requires text"); index += 1; continue;+ }+ if (item === "--highlight") {+ highlightedOutputs.push(optionValue(rest, index, "--highlight requires an Output name")); index += 1; continue;+ }+ if (item === "--clear-title") { clearTitle = true; continue; }+ if (item === "--clear-note") { clearNote = true; continue; }+ if (item === "--clear-highlights") { clearHighlights = true; continue; }+ if (item === "--limit") {+ limit = positiveInteger(optionValue(rest, index, "--limit requires a positive integer"), "--limit");+ index += 1; continue;+ }+ if (item === "--lines") {+ lines = positiveInteger(optionValue(rest, index, "--lines requires a positive integer"), "--lines");+ index += 1; continue;+ }+ if (item === "--before") {+ before = optionValue(rest, index, "--before requires a Build id"); index += 1; continue;+ }+ if (item === "--to") {+ to = resolve(optionValue(rest, index, "--to requires a file path")); index += 1; continue;+ }+ if (item === "--follow") { follow = true; continue; }+ if (item === "--max-wait-ms") {+ const value = Number(optionValue(rest, index, "--max-wait-ms requires milliseconds"));+ if (!Number.isSafeInteger(value) || value < 0) {+ throw new Error("--max-wait-ms must be a non-negative safe integer");+ }+ maxWaitMs = value; index += 1; continue;+ }+ if (item === "--ready-file") {+ readyFile = resolve(optionValue(rest, index, "--ready-file requires a path")); index += 1; continue;+ }+ if (item === "--worker-owner") {+ workerOwner = optionValue(rest, index, "--worker-owner requires an identity"); index += 1; continue;+ }+ if (item === "--reason") {+ reason = optionValue(rest, index, "--reason requires text"); index += 1; continue;+ }+ if (item === "--slot") {+ slot = optionValue(rest, index, "--slot requires a credential slot"); index += 1; continue;+ }+ if (item === "--from") {+ from = resolve(optionValue(rest, index, "--from requires a credential file")); index += 1; continue;+ }+ if (item === "--source") {+ source = resolve(optionValue(rest, index, "--source requires a source path")); index += 1; continue;+ }+ throw new Error(`unknown option ${item}`);+ }+ return {+ command, action, file, workspaceRoot, assetRoots, packageRoot, runtime, follow, maxWaitMs,+ output, title, note, highlightedOutputs, clearTitle, clearNote, clearHighlights, limit, lines,+ before, to, json, color, verbose, watch, jsonl, readyFile, workerOwner, reason, slot, from, source,+ seenOptions: [...seenOptions],+ };+}++function optionValue(values: readonly string[], index: number, message: string): string {+ const value = values[index + 1];+ if (value === undefined || value.startsWith("--")) throw new Error(message);+ return value;+}++function positiveInteger(value: string, option: string): number {+ const parsed = Number(value);+ if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error(`${option} requires a positive integer`);+ return parsed;+}++export function assertCommandOptions(args: ParsedArgs): void {+ const common = ["--json", "--color", "--no-color", "--verbose", "--debug"];+ const allowed = new Set(common);+ const add = (...items: readonly string[]): void => { for (const item of items) allowed.add(item); };+ switch (args.command) {+ case "programs": add("--max-wait-ms", "--runtime", "--limit"); break;+ case "runtime":+ add("--runtime");+ if (args.action === "use" || args.action === "unset") add("--workspace");+ if (args.action === "up" || args.action === "down") add("--max-wait-ms");+ if (args.action === "logs") add("--lines");+ if (args.action === "status") add("--limit");+ break;+ case "packages": break;+ case "auth":+ add("--runtime", "--slot");+ if (args.action === "login") add("--from");+ if (args.action === "status") add("--limit");+ break;+ case "activity": add("--runtime", "--watch", "--jsonl", "--limit"); break;+ case "paths": add("--runtime"); break;+ case "get": add("--workspace", "--output", "--to"); break;+ case "cancel": add("--runtime", "--reason"); break;+ case "result":+ if (args.action === "finish" || args.action === "discard") add("--runtime");+ if (args.action === "edit") {+ add("--workspace", "--title", "--note", "--highlight", "--clear-title", "--clear-note", "--clear-highlights", "--limit");+ }+ break;+ case "doctor": add("--workspace", "--limit"); break;+ case "status":+ add("--runtime", "--watch", "--limit");+ if (args.watch) add("--max-wait-ms");+ break;+ case "builds":+ case "history":+ add("--workspace", "--limit", "--before");+ if (args.command === "history") add("--source");+ break;+ case "inspect": add("--workspace", "--output", "--limit"); break;+ case "check":+ case "plan": add("--runtime", "--package-root", "--workspace", "--asset-root", "--limit"); break;+ case "build":+ add("--runtime", "--package-root", "--workspace", "--asset-root", "--follow", "--max-wait-ms", "--title", "--limit");+ break;+ }+ const invalid = args.seenOptions.find((item) => !allowed.has(item));+ if (invalid !== undefined) {+ const command = args.action === undefined ? args.command : `${args.command} ${args.action}`;+ throw new Error(`${invalid} does not apply to ${command}`);+ }+ if (args.seenOptions.includes("--color") && args.seenOptions.includes("--no-color")) {+ throw new Error("--color and --no-color are mutually exclusive");+ }+ if (args.command === "get" && args.output === undefined) {+ throw new Error("get requires --output with one public Output name");+ }+ if (args.command === "get" && args.to === undefined) {+ throw new Error("get requires --to with the export destination");+ }+}++export function usage(): string {+ return [+ "usage: hypit <command> [options]",+ "",+ "Run `hypit help` for commands or `hypit help <command>` for exact syntax.",+ ].join("\n");+}diff --git a/packages/cli/src/build-planning.ts b/packages/cli/src/build-planning.tsnew file mode 100644index 00000000..1fffbe53--- /dev/null+++ b/packages/cli/src/build-planning.ts@@ -0,0 +1,64 @@+import { resolve } from "node:path";++import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";+import type { NodeRuntimeHost } from "@hypit/runtime-host-node";+import { plannedNeeds } from "@hypit/runtime";+import type { BuildCatalogDescriptor } from "@hypit/runtime";+import type { BuildState, CapabilityRef } from "@hypit/protocol";++export function createCatalogDescriptor(options: {+ readonly source: string;+ readonly compilation: NodeCompiledSourceClosure;+ readonly run?: { readonly path: string };+}): BuildCatalogDescriptor {+ const publishedOutputs = options.compilation.exports.flatMap((item) => {+ if (item.ref.kind === "operation-result") {+ throw new Error(`public output ${item.name} was not lowered to a stable Record or Logical Output`);+ }+ return item.ref.kind === "logical-output" ? [{ name: item.name, ref: item.ref }] : [];+ });+ const names = new Set<string>();+ const outputs = new Set<string>();+ for (const published of publishedOutputs) {+ if (names.has(published.name)) throw new Error(`public Output name ${published.name} is repeated`);+ if (outputs.has(published.ref.id)) {+ throw new Error(`Logical Output ${published.ref.id} has more than one public name`);+ }+ names.add(published.name);+ outputs.add(published.ref.id);+ }+ return {+ source: { path: resolve(options.source) },+ ...(options.run === undefined ? {} : { run: { path: resolve(options.run.path) } }),+ publishedOutputs,+ };+}++function capabilityName(capability: CapabilityRef): string {+ return `${capability.module.name}@${capability.module.version}#${capability.name}`;+}++function demandedCapabilities(state: BuildState): readonly CapabilityRef[] {+ const found = new Map(plannedNeeds(state).map((need) => [capabilityName(need.capability), need.capability]));+ return [...found.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([, value]) => value);+}++export async function preflightPlan(host: NodeRuntimeHost, state: BuildState) {+ const capabilities = demandedCapabilities(state);+ const result = await host.preflight({ capabilities });+ return {+ ok: !result.diagnostics.some((item) => item.severity === "error"),+ capabilities: capabilities.map(capabilityName),+ diagnostics: result.diagnostics,+ } as const;+}++export function assertPreflight(preflight: Awaited<ReturnType<typeof preflightPlan>>): void {+ if (preflight === undefined || preflight.ok) return;+ const errors = preflight.diagnostics.filter((item) => item.severity === "error");+ throw new Error([+ `Runtime preflight failed for ${errors.length} demanded deployment requirement${errors.length === 1 ? "" : "s"}:`,+ ...errors.map((item) => ` ${item.code}${item.subject === undefined ? "" : ` (${item.subject})`}: ${item.message}`),+ "No Build was submitted and no external capability request was made.",+ ].join("\n"));+}diff --git a/packages/cli/src/commands/environment.ts b/packages/cli/src/commands/environment.tsnew file mode 100644index 00000000..6e9cb688--- /dev/null+++ b/packages/cli/src/commands/environment.ts@@ -0,0 +1,404 @@+import { readFile } from "node:fs/promises";+import { resolve } from "node:path";++import type { NodeRuntimeHost } from "@hypit/runtime-host-node";+import { hypitHostPackageRoot, inspectHostPackage, prepareHostPackages } from "@hypit/runtime-host-node";++import type { ParsedArgs } from "../arguments.js";+import type { CliDistribution } from "../distribution.js";+import { acquireOAuthCredential } from "../oauth.js";+import { writeCliOutput } from "../output.js";+import type { CliIo } from "../output.js";+import { hypitHostStateRoot, hypitProjectStateRoot } from "../paths.js";+import type { CliRuntimeController } from "../runtime-port.js";+import { queueLaneLines, summarizeQueueLanes } from "../runtime-view.js";+import type { OperationalWriter } from "./types.js";++export async function runEnvironmentCommand(input: {+ readonly args: ParsedArgs;+ readonly io: CliIo;+ readonly distribution: CliDistribution;+ readonly projectRoot: string;+ readonly packageRootForProject: () => Promise<string>;+ readonly runtimeHost: (profile: string, packageRoot?: string) => Promise<NodeRuntimeHost>;+ readonly runtimeController: (profile: string) => Promise<CliRuntimeController>;+ readonly write: OperationalWriter;+}): Promise<boolean> {+ const {+ args, io, distribution, projectRoot, packageRootForProject, runtimeHost, runtimeController, write,+ } = input;+ const reportProgramProgress = args.json || args.jsonl+ ? undefined+ : (event: { readonly id: string; readonly phase: "checking" | "installing" | "starting" | "waiting" | "ready" }): void => {+ const verb = {+ checking: "Checking",+ installing: "Installing",+ starting: "Starting",+ waiting: "Waiting for",+ ready: "Ready",+ }[event.phase];+ io.write(` · ${verb} ${event.id}\n`);+ };+ const reportPackageProgress = args.json || args.jsonl+ ? undefined+ : (event: { readonly specifier: string; readonly phase: "checking" | "installing" | "ready" }): void => {+ if (event.phase === "installing") io.write(` · Installing ${event.specifier}\n`);+ };++ if (args.command === "paths") {+ const runtimePaths = args.runtime === undefined+ ? undefined+ : await (await runtimeHost(args.runtime)).resolvePaths();+ const machine = {+ format: "hypit.cli-paths@1" as const,+ project: projectRoot,+ projectState: hypitProjectStateRoot(projectRoot),+ ...(args.runtime === undefined ? {} : { profile: args.runtime }),+ ...(runtimePaths === undefined ? {} : { runtimeData: runtimePaths.runtimeDataRoot }),+ hostState: hypitHostStateRoot(),+ machinePackages: hypitHostPackageRoot(),+ ...(distribution.packageRoot === undefined ? {} : { distribution: distribution.packageRoot }),+ };+ write(machine, "Hypit paths", "info", [+ ["Project", machine.project],+ ["Project state", machine.projectState],+ ["Runtime Profile", machine.profile ?? "not selected"],+ ["Runtime data", machine.runtimeData ?? "not selected"],+ ["Host state", machine.hostState],+ ["Machine packages", machine.machinePackages],+ ["Distribution", machine.distribution ?? "embedded"],+ ]);+ return true;+ }++ if (args.command === "packages") {+ if (args.action !== "install" && args.action !== "status") {+ throw new Error("packages takes install or status");+ }+ if (args.file === undefined) throw new Error(`packages ${args.action} requires package@exact-version`);+ const root = hypitHostPackageRoot();+ const existing = await inspectHostPackage(args.file, root);+ const reports = args.action === "install"+ ? await prepareHostPackages([args.file], {+ root,+ ...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }),+ })+ : existing === undefined ? [] : [existing];+ const ready = reports.length === 1;+ write({+ 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],+ ["Ready", String(ready)],+ ]);+ if (!ready) io.setExitCode?.(1);+ return true;+ }++ if (args.command === "doctor") {+ if (args.packageRoot !== undefined) {+ throw new Error("doctor reads all deployment selection from the Runtime Profile itself");+ }+ const profileInput = args.runtime ?? args.file;+ const profile = profileInput === undefined ? undefined : resolve(profileInput);+ const [runtimeResult, projectResult] = await Promise.all([+ profile === undefined ? undefined : (await runtimeHost(profile)).doctor(),+ distribution.diagnoseProjectResults(projectRoot, {+ packageRoot: await packageRootForProject(),+ ...(distribution.packageRoot === undefined+ ? {}+ : { distributionPackageRoot: distribution.packageRoot }),+ }),+ ]);+ const diagnostics = [...(runtimeResult?.diagnostics ?? []), ...projectResult.diagnostics];+ const machine = {+ format: "hypit.cli-doctor@3" as const,+ ok: !diagnostics.some((item) => item.severity === "error"),+ project: projectRoot,+ ...(profile === undefined ? {} : { profile }),+ diagnosticCount: diagnostics.length,+ diagnostics: diagnostics.slice(0, args.limit),+ ...(diagnostics.length <= args.limit ? {} : { omittedDiagnostics: diagnostics.length - args.limit }),+ };+ writeCliOutput(io, {+ json: args.json || args.jsonl,+ jsonl: args.jsonl,+ color: args.color,+ verbose: args.verbose,+ }, { kind: "doctor", machine });+ if (!machine.ok) io.setExitCode?.(1);+ return true;+ }++ if (args.command === "programs") {+ if (args.file !== undefined && args.runtime !== undefined) {+ throw new Error("programs reads all deployment selection from the Runtime Profile itself; provide that Profile only once");+ }+ if (args.packageRoot !== undefined) {+ throw new Error("programs reads all deployment selection from the Runtime Profile itself");+ }+ if (args.action !== "up" && args.action !== "down" && args.action !== "status") {+ throw new Error("programs takes up, down or status");+ }+ if (args.action !== "up" && args.maxWaitMs !== undefined) {+ throw new Error("--max-wait-ms applies to programs up");+ }+ const profileInput = args.runtime ?? args.file;+ if (profileInput === undefined) throw new Error("programs requires a Runtime Profile");+ const profile = resolve(profileInput);+ const host = await runtimeHost(profile);+ if (args.action === "up") {+ await host.prepare(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress });+ }+ const controller = await runtimeController(profile);+ const result = args.action === "up"+ ? await controller.programs.up({+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),+ })+ : args.action === "down"+ ? await controller.programs.down()+ : 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 lifecycleOk = args.action === "status" || desiredState;+ const shownPrograms = result.programs.filter((item) => item.state.state !== "ready").slice(0, args.limit);+ write({+ format: "hypit.cli-programs@2",+ action: args.action,+ ready,+ 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((item) => `${item.id}: ${item.state.state}`));+ if (!lifecycleOk) io.setExitCode?.(1);+ return true;+ }++ if (args.command === "runtime") {+ if (args.action !== "up" && args.action !== "down" && args.action !== "status" && args.action !== "logs") {+ throw new Error("runtime takes up, down, status or logs");+ }+ if (args.file !== undefined && args.runtime !== undefined) {+ throw new Error("runtime accepts the Runtime Profile either positionally or with --runtime, not both");+ }+ const profileInput = args.runtime ?? args.file;+ if (profileInput === undefined) throw new Error("runtime requires a Runtime Profile");+ const profile = resolve(profileInput);+ const controller = await runtimeController(profile);+ if (args.action === "up") {+ const packageRoot = await packageRootForProject();+ const host = await runtimeHost(profile, packageRoot);+ const prepared = await host.prepare(+ reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress },+ );+ const validated = await host.createRuntime();+ await validated.close();+ const external = await controller.programs.up({+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),+ });+ const processState = await controller.worker.up({+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ });+ const ok = processState.state === "running"+ && external.programs.every((item) => item.state.state === "ready");+ write({+ 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", processState.state],+ ["External programs", String(external.programs.length)],+ ]);+ if (!ok) io.setExitCode?.(1);+ return true;+ }+ 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 = lines.slice(-args.lines);+ write({+ 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", [+ ["Lines", `${shown.length}/${lines.length}`],+ ...(args.verbose ? [["Path", logs.path] as const] : []),+ ], shown.length === 0 ? ["No log output."] : shown);+ return true;+ }+ if (args.action === "down") {+ const worker = await controller.worker.down({+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ });+ write({ format: "hypit.cli-runtime-down@2", worker: worker.state },+ "Runtime Worker is down", "success", [["Worker", worker.state]],+ ["External programs were left running. Stop them explicitly with hypit programs down."]);+ return true;+ }++ const runtimeLoading = (await runtimeHost(profile)).openControl({ readOnly: true });+ let runtime: Awaited<typeof runtimeLoading> | undefined;+ try {+ const [worker, external, selectedRuntime] = await Promise.all([+ controller.worker.status(),+ controller.programs.report(),+ runtimeLoading,+ ]);+ runtime = selectedRuntime;+ const activity = await runtime.activity();+ const counts = Object.fromEntries([+ ["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"+ && external.programs.every((item) => item.state.state === "ready");+ const active = activity.builds.length;+ 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@2" as const,+ ready,+ attention,+ 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) } : {}),+ },+ };+ write(machine, "Runtime status", attention ? "warning" : ready ? "success" : "info", [+ ["Worker", worker.state],+ ["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`],+ ...(args.verbose ? [["Active requests", String(activity.capacity.length)] as const] : []),+ ], [+ ...unavailable.slice(0, args.limit).map((item) => `${item.id}: ${item.state.state}`),+ ...(args.verbose ? queueLaneLines(lanes.slice(0, args.limit)) : []),+ ]);+ } finally {+ if (runtime !== undefined) await runtime.close();+ else await runtimeLoading.then(async (loaded) => await loaded.close(), () => undefined);+ }+ return true;+ }++ if (args.command === "auth") {+ if (args.action !== "status" && args.action !== "login" && args.action !== "logout") {+ throw new Error("auth takes status, login or logout");+ }+ if (args.runtime === undefined) {+ throw new Error("auth requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>");+ }+ if (args.from !== undefined && args.action !== "login") throw new Error("--from applies only to auth login");+ const credentialsControl = await (await runtimeHost(args.runtime)).openCredentials(args.file!);+ try {+ let credentials = await credentialsControl.credentials(args.file!);+ if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);+ if (credentials.length === 0) throw new Error(`Endpoint ${args.file} has no matching credential`);+ if (args.slot === undefined && credentials.length > 1 && args.action !== "status") {+ throw new Error(`Endpoint ${args.file} has several credentials; select one with --slot`);+ }+ if (args.action === "status") {+ 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,+ }));+ write({+ 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.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`+ : "select a writable credential source in the Runtime Profile";+ throw new Error(`${item.label} cannot be written by this command; ${source}`);+ }+ const raw = item.acquisition !== undefined && args.from === undefined+ ? await acquireOAuthCredential(io, item.acquisition)+ : args.from === undefined+ ? await io.readSecret?.(`${item.label}: `)+ : await readFile(args.from, "utf8");+ if (raw === undefined) throw new Error("interactive credential input is unavailable; use --from <file>");+ const secret = raw.trim();+ if (secret.length === 0) throw new Error("credential input is empty");+ if (item.kind === "json") {+ try { JSON.parse(secret); } catch { throw new Error(`${item.label} is not valid JSON`); }+ }+ const stored = await credentialsControl.putCredential(item.endpoint, item.slot, secret);+ write({+ 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 credentialsControl.deleteCredential(item.endpoint, item.slot);+ write({+ 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],+ ]);+ }+ } finally {+ await credentialsControl.close();+ }+ return true;+ }++ return false;+}diff --git a/packages/cli/src/commands/execution.ts b/packages/cli/src/commands/execution.tsnew file mode 100644index 00000000..9d57fadf--- /dev/null+++ b/packages/cli/src/commands/execution.ts@@ -0,0 +1,305 @@+import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";+import type { NodeRuntimeHost } from "@hypit/runtime-host-node";++import type { ParsedArgs } from "../arguments.js";+import { buildObservationKey } from "../observation.js";+import type { CliIo } from "../output.js";+import type { CliRuntimeController } from "../runtime-port.js";+import { formatOperationProgress, queueLaneLines, summarizeQueueLanes } from "../runtime-view.js";+import { buildStatusView } from "../view.js";+import type { OperationalWriter } from "./types.js";++type OpenProjectResults = () => Promise<{+ readonly repository: BuildResultRepository;+ close(): void | Promise<void>;+}>;++export function isExecutionCommand(args: ParsedArgs): boolean {+ return args.command === "status" || args.command === "cancel" || args.command === "activity"+ || (args.command === "result" && (args.action === "finish" || args.action === "discard"));+}++/** Inspect or control accepted Build work. Observation never owns execution. */+export async function runExecutionCommand(input: {+ readonly args: ParsedArgs;+ readonly io: CliIo;+ readonly runtimeHost: (profile: string) => Promise<NodeRuntimeHost>;+ readonly runtimeController: (profile: string) => Promise<CliRuntimeController>;+ readonly openProjectResults: OpenProjectResults;+ readonly write: OperationalWriter;+}): Promise<void> {+ const { args, io, runtimeHost, runtimeController, openProjectResults, write } = input;+ if (args.command === "status" && args.runtime === undefined) {+ const openedResults = await openProjectResults();+ let result;+ try {+ result = await openedResults.repository.read(args.file!);+ } finally {+ await openedResults.close();+ }+ if (args.watch && result?.outcome === undefined) {+ throw new Error(`Build ${args.file} has no finished Result; select its Runtime to observe active execution`);+ }+ const finished = result?.outcome !== undefined;+ const build = result === undefined ? null : buildStatusView({ id: result.id, result });+ write({ format: "hypit.cli-status@3", build }, result === undefined+ ? "Build Result not found"+ : finished ? "Build Result is finished" : "Build Result is unfinished",+ result === undefined || !finished ? "warning" : "info", [+ ["Build", args.file!],+ ["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.",+ ]);+ if (result === undefined || !finished) io.setExitCode?.(1);+ return;+ }++ if (args.runtime === undefined) {+ throw new Error(`${args.command} requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>`);+ }+ const selectedHost = await runtimeHost(args.runtime);++ if (args.command === "result" && args.action === "discard") {+ const resultControl = await selectedHost.openResultControl();+ const discarded = await resultControl.discardSubmission(args.file!)+ .finally(async () => await resultControl.close());+ write({ 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 was removed."] : []);+ if (!discarded) io.setExitCode?.(1);+ return;+ }++ const runtime = await selectedHost.openControl({ readOnly: args.command !== "cancel" });+ try {+ if (args.command === "activity") {+ const controller = await runtimeController(args.runtime);+ let previous: string | undefined;+ const writeActivity = async (): Promise<void> => {+ const [activity, worker] = await Promise.all([+ runtime.activity(),+ controller.worker.status(),+ ]);+ 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 lanes = args.verbose ? summarizeQueueLanes(activity.capacity).slice(0, args.limit) : undefined;+ const currentView = JSON.stringify({+ worker: worker.state,+ builds,+ activeRequests: activity.capacity.length,+ ...(lanes === undefined ? {} : { lanes }),+ });+ if (args.watch && currentView === previous) return;+ previous = currentView;+ const value = {+ format: "hypit.cli-activity@2" as const,+ at: Date.now(),+ worker: worker.state,+ builds,+ ...(activity.builds.length <= args.limit ? {} : { omittedBuilds: activity.builds.length - args.limit }),+ activeRequests: activity.capacity.length,+ ...(lanes === undefined ? {} : { lanes }),+ };+ 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.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)}`)).slice(0, args.limit)+ : [];+ write(value, "Runtime activity", activity.builds.length === 0 ? "success" : "info", [+ ["Active Builds", String(activity.builds.length)],+ ["Active Operations", String(activeOperations.length)],+ ["Worker", worker.state],+ ], [+ ...buildLines,+ ...(operationLines.length === 0 ? [] : ["Operations:", ...operationLines]),+ ...(args.verbose ? queueLaneLines(lanes ?? []) : []),+ ]);+ };+ if (!args.watch) await writeActivity();+ else while (true) {+ await writeActivity();+ await new Promise((resolveWait) => setTimeout(resolveWait, 1_000));+ }+ return;+ }++ if (args.command === "status") {+ let view = await runtime.inspect(args.file!);+ let result: BuildResultManifest | undefined;+ let resultReadError: string | undefined;+ let openedResults: Awaited<ReturnType<OpenProjectResults>> | undefined;+ try {+ openedResults = await openProjectResults();+ if (args.watch && view !== undefined && view.issue === undefined) {+ const startedAt = Date.now();+ let delayMs = 100;+ let previous: string | undefined;+ const controller = await runtimeController(args.runtime);+ while (view !== undefined && view.issue === undefined) {+ const encoded = buildObservationKey(view);+ if (encoded !== previous && !args.json) {+ previous = encoded;+ io.write(` · ${view.id}: ${view.activity}`+ + `${view.operations.length === 0 ? "" : ` · ${view.operations.length} operation(s)`}\n`);+ delayMs = 100;+ } else {+ delayMs = Math.min(1_000, delayMs * 2);+ }+ const remaining = args.maxWaitMs === undefined+ ? undefined+ : args.maxWaitMs - (Date.now() - startedAt);+ if (remaining !== undefined && remaining <= 0) break;+ const worker = await controller.worker.status();+ if (worker.state !== "running") break;+ await new Promise((resolveWait) => setTimeout(resolveWait,+ remaining === undefined ? delayMs : Math.min(delayMs, remaining)));+ view = await runtime.inspect(args.file!);+ }+ }+ result = await openedResults.repository.read(args.file!);+ } catch (error) {+ resultReadError = error instanceof Error ? error.message : String(error);+ } finally {+ await openedResults?.close();+ }+ const found = view !== undefined || result !== undefined;+ const activity = view?.activity;+ const outcome = result?.outcome ?? view?.outcome;+ const issue = view?.issue;+ 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,+ });+ write({ format: "hypit.cli-status@3", build }, !found+ ? "Build not found"+ : issue !== undefined+ ? "Build needs attention"+ : args.watch+ ? activity === undefined ? "Build finished" : "Build still active"+ : "Build status",+ !found+ ? "warning"+ : issue !== undefined || resultReadError !== undefined+ ? "error"+ : outcome === "failed"+ ? "error"+ : args.watch && activity !== undefined ? "warning" : "info", [+ ["Build", args.file!],+ ...(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.state}`+ : `${operation.endpoint}: ${formatOperationProgress(operation.progress)}`)+ .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);+ return;+ }++ if (args.command === "result") {+ const before = await runtime.inspect(args.file!);+ if (before !== undefined && before.activity !== "saving-result") {+ throw new Error(`Build ${args.file} is still ${before.activity}; there is no Result write to finish`);+ }+ if (before !== undefined && before.issue === undefined) {+ const worker = await (await selectedHost.controller()).worker.status();+ if (worker.state === "running") {+ throw new Error(`Build ${args.file} Result is currently being written by the Runtime Worker`);+ }+ }+ const resultControl = await selectedHost.openResultControl();+ const finished = await resultControl.finishResult(args.file!)+ .finally(async () => await resultControl.close());+ if (finished === undefined) {+ const openedResults = await openProjectResults();+ const existing = await openedResults.repository.read(args.file!)+ .finally(async () => await openedResults.close());+ if (existing?.outcome === undefined) {+ write({ format: "hypit.cli-result-finish@2", build: args.file!, found: false },+ "Result cannot be finished", "warning", [["Build", args.file!]],+ ["No decided Result write exists for this Build."]);+ io.setExitCode?.(1);+ return;+ }+ write({ format: "hypit.cli-result-finish@2", build: args.file!, outcome: existing.outcome },+ "Result already finished", "info", [["Build", args.file!], ["Outcome", existing.outcome]]);+ return;+ }+ write({+ format: "hypit.cli-result-finish@2",+ build: args.file!,+ outcome: finished.outcome,+ ...(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 ? [] : [`Attention ${finished.issue.message}`]);+ if (finished.issue !== undefined) io.setExitCode?.(1);+ return;+ }++ const active = await runtime.cancel(args.file!, args.reason);+ const openedResults = active === undefined ? await openProjectResults() : undefined;+ const finished = openedResults === undefined+ ? undefined+ : await openedResults.repository.read(args.file!).finally(async () => await openedResults.close());+ 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@3" as const,+ requested: active?.cancellationRequested === true,+ build,+ };+ const title = active === undefined && finished === undefined+ ? "Build not found"+ : active === undefined ? "Build already finished" : "Build cancellation requested";+ write(machine, title,+ active === undefined && finished === undefined ? "warning" : active === undefined ? "info" : "success", [+ ["Build", args.file!], ...(build === null ? [] : [["Work", build.work.state] as const]),+ ], active === undefined && finished?.outcome !== undefined+ ? [`No running work was changed; this Build is already ${finished.outcome}.`]+ : []);+ if (active === undefined && finished === undefined) io.setExitCode?.(1);+ } finally {+ await runtime.close();+ }+}diff --git a/packages/cli/src/commands/results.ts b/packages/cli/src/commands/results.tsnew file mode 100644index 00000000..97b4a7cd--- /dev/null+++ b/packages/cli/src/commands/results.ts@@ -0,0 +1,167 @@+import { resolve } from "node:path";++import type { BuildResultRepository } from "@hypit/build-result";++import type { ParsedArgs } from "../arguments.js";+import { exportBuildResultOutput } from "../result-export.js";+import { browseBuildOutputHistory } from "../result-query.js";+import {+ buildCreatedAtIso,+ buildResultView,+ cliTypeName,+ outputView,+ projectPath,+} from "../view.js";+import type { OperationalWriter } from "./types.js";++export function isProjectResultCommand(args: ParsedArgs): boolean {+ return args.command === "builds" || args.command === "history" || args.command === "inspect"+ || args.command === "get" || (args.command === "result" && args.action === "edit");+}++/** Execute commands that need only project-owned Result history, never a Runtime. */+export async function runProjectResultCommand(input: {+ readonly args: ParsedArgs;+ readonly projectRoot: string;+ readonly repository: BuildResultRepository;+ readonly write: OperationalWriter;+}): Promise<void> {+ const { args, projectRoot, repository, write } = input;+ if (args.command === "builds") {+ const page = await repository.browse({+ limit: args.limit,+ ...(args.before === undefined ? {} : { before: args.before }),+ });+ const builds = page.results.map((manifest) => ({+ id: manifest.id,+ createdAt: buildCreatedAtIso(manifest.id),+ ...(manifest.title === undefined ? {} : { title: manifest.title }),+ outcome: manifest.outcome,+ ...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.path, projectRoot) }),+ 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,+ }));+ write({+ format: "hypit.cli-builds@3",+ builds,+ ...(page.next === undefined ? {} : { next: page.next }),+ }, "Build results", "info", [["Builds", String(builds.length)]],+ builds.map((item) => {+ 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 source = args.source === undefined ? undefined : resolve(args.source);+ const page = await browseBuildOutputHistory(repository, {+ projectRoot,+ output: args.file!,+ ...(source === undefined ? {} : { source }),+ ...(args.before === undefined ? {} : { before: args.before }),+ limit: args.limit,+ });+ const entries = await Promise.all(page.results.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!),+ })));+ write({+ format: "hypit.cli-history@4",+ output: args.file!,+ ...(source === undefined ? {} : { source: projectPath(source, projectRoot) }),+ entries,+ ...(page.next === undefined ? {} : { next: page.next }),+ }, entries.length === 0 ? "No matching Output" : "Output history",+ entries.length === 0 ? "warning" : "info", [+ ["Output", args.file!],+ ...(source === undefined ? [] : [["Source", projectPath(source, projectRoot)] as const]),+ ["Builds", String(entries.length)],+ ], entries.map((item) => {+ const label = item.title === undefined ? item.build : `${item.title} · ${item.build}`;+ return `${label}: ${item.outcome} · ${item.output.kind} · ${item.output.type} · ${item.createdAt}`;+ }).concat(page.next === undefined ? [] : [`Older hypit history ${args.file} --before ${page.next}`]));+ 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 build = await buildResultView(repository, manifest, {+ projectRoot,+ ...(args.output === undefined ? {} : { output: args.output }),+ limit: args.limit,+ });+ write({ format: "hypit.cli-inspect@4", 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))],+ ], [+ ...(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}`+ + `${item.mediaType === undefined ? "" : ` · ${item.mediaType}`}`+ + `${item.size === undefined ? "" : ` · ${item.size} bytes`}`),+ ...(build.omittedOutputs === undefined ? [] : [+ `${build.omittedOutputs} more Outputs · use --limit <count> or --output <name>`,+ ]),+ ]);+ return;+ }++ if (args.command === "result") {+ const manifest = await repository.updatePresentation(args.file!, {+ ...(args.clearTitle ? { title: null } : args.title === undefined ? {} : { title: args.title }),+ ...(args.clearNote ? { note: null } : args.note === undefined ? {} : { note: args.note }),+ ...(args.clearHighlights+ ? { highlightedOutputs: [] }+ : args.highlightedOutputs.length === 0 ? {} : { highlightedOutputs: args.highlightedOutputs }),+ });+ const presentation = {+ format: "hypit.cli-result-edit@3" as const,+ build: manifest.id,+ title: manifest.title ?? null,+ note: manifest.note ?? null,+ highlightedOutputCount: manifest.highlightedOutputs?.length ?? 0,+ highlightedOutputs: manifest.highlightedOutputs?.slice(0, args.limit) ?? [],+ ...((manifest.highlightedOutputs?.length ?? 0) <= args.limit+ ? {}+ : { omittedHighlightedOutputs: manifest.highlightedOutputs!.length - args.limit }),+ };+ write(presentation, "Build Result updated", "success", [+ ["Build", manifest.id],+ ["Title", manifest.title ?? "—"],+ ["Highlighted", String(manifest.highlightedOutputs?.length ?? 0)],+ ], manifest.note === undefined ? [] : [`Note ${manifest.note}`]);+ return;+ }++ const exported = await exportBuildResultOutput(repository, args.file!, args.output!, args.to!);+ const machine = {+ format: "hypit.cli-get@4" as const,+ build: exported.build,+ output: exported.output,+ type: cliTypeName(exported.type),+ kind: exported.kind,+ path: exported.path,+ };+ write(machine, "Build Output exported", "success", [+ ["Build", exported.build],+ ["Output", exported.output],+ ["Type", machine.type],+ ["Kind", exported.kind],+ ["Path", exported.path],+ ]);+}diff --git a/packages/cli/src/commands/types.ts b/packages/cli/src/commands/types.tsnew file mode 100644index 00000000..cf46f054--- /dev/null+++ b/packages/cli/src/commands/types.ts@@ -0,0 +1,9 @@+import type { CliMachineView } from "../output.js";++export type OperationalWriter = (+ machine: CliMachineView,+ title: string,+ status?: "success" | "warning" | "error" | "info",+ facts?: readonly (readonly [string, string])[],+ lines?: readonly string[],+) => void;diff --git a/packages/cli/src/distribution.ts b/packages/cli/src/distribution.tsindex 7d0b1893..2a294124 100644--- a/packages/cli/src/distribution.ts+++ b/packages/cli/src/distribution.ts@@ -46,7 +46,7 @@ export type CliDistribution = {readonly distributionPackageRoot?: string;}): Promise<NodeRuntimeHost>;/** Open project-owned Result history even when no Runtime Profile is selected. */- openProjectResults?(projectRoot: string, options: {+ openProjectResults(projectRoot: string, options: {readonly packageRoot: string;readonly distributionPackageRoot?: string;}): Promise<{@@ -55,7 +55,7 @@ export type CliDistribution = {close(): void | Promise<void>;}>;/** Actively diagnose this project's selected Result Store without reading its history. */- diagnoseProjectResults?(projectRoot: string, options: {+ diagnoseProjectResults(projectRoot: string, options: {readonly packageRoot: string;readonly distributionPackageRoot?: string;}): Promise<{diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 61778ab4..20d1a149 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -21,6 +21,7 @@ export type {CliOutputView,PublicOutputKind,} from "./view.js";+export type { OperationalMachineView } from "./machine-view.js";export type {CliCompilerOptions,CliDistribution,diff --git a/packages/cli/src/machine-view.ts b/packages/cli/src/machine-view.tsnew file mode 100644index 00000000..e9ca531f--- /dev/null+++ b/packages/cli/src/machine-view.ts@@ -0,0 +1,27 @@+import type { CliBuildResultView, CliBuildStatusView, CliOutputView } from "./view.js";++type ProgramStateView = { readonly id: string; readonly state: string; readonly action?: string };+type AttentionView = { readonly message: string; readonly action?: string };++export type OperationalMachineView =+ | { readonly format: "hypit.cli-runtime-selection@2"; readonly selected: boolean; readonly removed?: boolean; readonly profile?: string; readonly project?: string }+ | { readonly format: "hypit.cli-paths@1"; readonly project: string; readonly projectState: string; readonly profile?: string; readonly runtimeData?: string; readonly hostState: string; readonly machinePackages: string; readonly distribution?: string }+ | { readonly format: "hypit.cli-package@2"; readonly action: "install" | "status"; readonly package: string; readonly ready: boolean }+ | { readonly format: "hypit.cli-programs@2"; readonly action: "up" | "down" | "status"; readonly ready: boolean; readonly programs: readonly ProgramStateView[]; readonly omittedPrograms?: number }+ | { readonly format: "hypit.cli-runtime-up@2"; readonly ready: boolean; readonly worker: string; readonly preparedPackages: number; readonly programs: { readonly total: number; readonly ready: number } }+ | { readonly format: "hypit.cli-runtime-logs@2"; readonly lines: readonly string[]; readonly totalLines: number; readonly omittedLines: number; readonly path?: string }+ | { readonly format: "hypit.cli-runtime-down@2"; readonly worker: string }+ | { readonly format: "hypit.cli-runtime-status@2"; readonly ready: boolean; readonly attention: boolean; readonly worker: { readonly state: string; readonly configuration?: string }; readonly builds: Readonly<Record<string, number>>; readonly programs: { readonly total: number; readonly ready: number; readonly unavailable: readonly ProgramStateView[] }; readonly capacity: { readonly active: number; readonly lanes?: readonly { readonly pool: string; readonly lane: string; readonly inFlight: number }[] } }+ | { readonly format: "hypit.cli-auth-status@2"; readonly endpoint: string; readonly credentials: readonly { readonly endpoint: string; readonly slot: string; readonly label: string; readonly kind: string; readonly configured: boolean; readonly writable: boolean }[]; readonly omittedCredentials?: number }+ | { readonly format: "hypit.cli-auth-change@2"; readonly endpoint: string; readonly slot: string; readonly configured: boolean; readonly changed?: boolean }+ | { readonly format: "hypit.cli-builds@3"; readonly builds: readonly { readonly id: string; readonly createdAt: string; readonly title?: string; readonly outcome: string; readonly run?: string; readonly targetCount: number; readonly targets?: readonly string[]; readonly omittedTargets?: number; readonly outputCount: number }[]; readonly next?: string }+ | { readonly format: "hypit.cli-history@4"; readonly output: string; readonly source?: string; readonly entries: readonly { readonly build: string; readonly title?: string; readonly createdAt: string; readonly outcome: string; readonly output: CliOutputView }[]; readonly next?: string }+ | { readonly format: "hypit.cli-inspect@4"; readonly build: CliBuildResultView }+ | { readonly format: "hypit.cli-result-edit@3"; readonly build: string; readonly title: string | null; readonly note: string | null; readonly highlightedOutputCount: number; readonly highlightedOutputs: readonly string[]; readonly omittedHighlightedOutputs?: number }+ | { readonly format: "hypit.cli-get@4"; readonly build: string; readonly output: string; readonly type: string; readonly kind: "scalar" | "resource" | "composite"; readonly path: string }+ | { readonly format: "hypit.cli-status@3"; readonly build: CliBuildStatusView | null }+ | { readonly format: "hypit.cli-activity@2"; readonly at: number; readonly worker: string; readonly builds: readonly { readonly id: string; readonly work: CliBuildStatusView["work"]; readonly outcome?: string; readonly attention?: AttentionView }[]; readonly omittedBuilds?: number; readonly activeRequests: number; readonly lanes?: readonly { readonly pool: string; readonly lane: string; readonly inFlight: number }[] }+ | { readonly format: "hypit.cli-result-discard@2"; readonly build: string; readonly discarded: boolean }+ | { readonly format: "hypit.cli-result-finish@2"; readonly build: string; readonly found?: false; readonly outcome?: string; readonly attention?: AttentionView }+ | { readonly format: "hypit.cli-cancel@3"; readonly requested: boolean; readonly build: CliBuildStatusView | null }+ | { readonly format: "hypit.cli-build@3"; readonly build: CliBuildStatusView };diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex ce3a4494..618ac277 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -1,22 +1,8 @@-import { createHash, randomBytes } from "node:crypto";-import { createServer } from "node:http";-import { spawn } from "node:child_process";-import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";-import { readFile, stat } from "node:fs/promises";+import { randomBytes } from "node:crypto";+import { dirname, isAbsolute, relative, resolve, sep } from "node:path";-import { FileBuildResultRepository } from "@hypit/build-result";-import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";-import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";import type { NodeRuntimeHost } from "@hypit/runtime-host-node";-import {- hypitHostPackageRoot,- inspectHostPackage,- prepareHostPackages,-} from "@hypit/runtime-host-node";-import { plannedNeeds } from "@hypit/runtime";-import type { BuildCatalogDescriptor, CapacityReservation, OperationProgress } from "@hypit/runtime";import { orderedBuildId } from "@hypit/protocol";-import type { BuildState, CapabilityRef } from "@hypit/protocol";import { parseSourceHeader } from "@hypit/source";import { unreachedGenerations } from "./reachability.js";@@ -24,16 +10,25 @@ import { typecheckProjectPackages } from "./package-typecheck.js";import { checkRunFile, collectRunFrontends, loadRunFile } from "./run-file.js";import type { CliDistribution } from "./distribution.js";import type {- CliBuildSubmission,- CliManagedProgramProgress,CliRuntime,- CliRuntimeControl,CliRuntimeController,} from "./runtime-port.js";import { writeCliHelp, writeCliOutput } from "./output.js";-import type { CliColorMode, CliIo, CliMachineView } from "./output.js";-import { exportBuildResultOutput } from "./result-export.js";-import { hypitHostStateRoot, hypitProjectStateRoot } from "./paths.js";+import type { CliIo, CliMachineView } from "./output.js";+import {+ assertCommandOptions,+ commandAllowsMissingPositional,+ isKnownCommand,+ parseArgs,+ usage,+} from "./arguments.js";+import { assertPreflight, createCatalogDescriptor, preflightPlan } from "./build-planning.js";+import { observeBuild } from "./observation.js";+import { isProjectResultCommand, runProjectResultCommand } from "./commands/results.js";+import { runEnvironmentCommand } from "./commands/environment.js";+import { isExecutionCommand, runExecutionCommand } from "./commands/execution.js";+import { inlineValuePreview } from "./runtime-view.js";+import { resolvePackageRoot } from "./project-context.js";import { loadDiscoveredSourcePackages } from "./source-packages.js";import {clearRuntimeProfile,@@ -41,850 +36,19 @@ import {selectRuntimeProfile,} from "./runtime-selection.js";import {- buildCreatedAtIso,- buildResultView,buildStatusView,cliTypeName,- outputView,projectPath,} from "./view.js";-type ParsedArgs = {- readonly command: string | undefined;- /** Second command word for scoped commands such as runtime and cancel. */- readonly action: string | undefined;- readonly file: string | undefined;- /** Canonical containment boundary for Author and Run Sources plus source assets. */- readonly workspaceRoot: string | undefined;- readonly assetRoots: readonly string[];- /** Host directory whose node_modules contains selected packages. */- readonly packageRoot: string | undefined;- readonly runtime: string | undefined;- readonly follow: boolean;- readonly maxWaitMs: number | undefined;- readonly output: string | undefined;- readonly title: string | undefined;- readonly note: string | undefined;- readonly highlightedOutputs: readonly string[];- readonly clearTitle: boolean;- readonly clearNote: boolean;- readonly clearHighlights: boolean;- readonly limit: number;- readonly lines: number;- readonly before: string | undefined;- readonly to: string | undefined;- readonly json: boolean;- readonly color: CliColorMode;- readonly verbose: boolean;- readonly watch: boolean;- readonly jsonl: boolean;- readonly readyFile: string | undefined;- readonly workerOwner: string | undefined;- readonly reason: string | undefined;- readonly slot: string | undefined;- readonly from: string | undefined;- /** Exact historical source path filter. It is Host presentation, never Build identity. */- readonly source: string | undefined;- /** Exact option spellings seen after the positional command. */- readonly seenOptions: readonly string[];-};--const HYPIHUB_OAUTH_CLIENT_ID = "hyc_d5d5e8e7131b0c877756e66c";--// Keep the callback page independent from a network request, but use the same-// mark shipped by hypit.ai (rather than a hand-drawn approximation).-const HYPIHUB_MARK_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="158.2 -39.5 415.6 415.6" aria-hidden="true"><defs><linearGradient id="hypit-callback-mark" x1="246.21386109" y1="324.13157352" x2="485.13742708" y2="22.56333286" gradientTransform="translate(0 337.46521538) scale(1 -1)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#e83f5f"/><stop offset=".14" stop-color="#e94765"/><stop offset=".33" stop-color="#ec5774"/><stop offset=".56" stop-color="#f1738c"/><stop offset=".8" stop-color="#f599af"/><stop offset=".88" stop-color="#f6a9bd"/></linearGradient></defs><path d="M549.67231627,138.36559516c-9.03995973-13.04594537-23.93013015-20.81603972-39.78785439-20.81603972h-141.20754521c-18.56362718,0-37.6714659,11.24702323-44.746216,28.41986963l-42.72053713,114.61681504c-6.9538001,17.00658197-6.86310202,36.35627455,3.35595582,51.63954686,10.26440688,15.34370695,29.26643886,24.41388399,47.72425931,24.41388399h129.97565371c21.3451426,0,40.66461787-13.42386941,48.13240067-33.40849469l44.88226312-120.28567569c5.54794526-14.87508482,3.46179716-31.53396006-5.57816258-44.56481984v-.03021732h-.03021732v.01513172ZM471.42693057,288.67353473c-1.42099809,3.80945775-5.12464911,6.3793597-9.19111551,6.3793597h-126.15104116c-6.56075586,0-10.09811937-4.23273084-11.32261265-6.03165297s-3.77924044-6.69680298-1.26981925-12.7587194l36.05396299-100.13473985c3.46177409-9.59927994,12.21450786-16.43213004,22.40334838-16.96123293.49886251-.03021732,1.01283367-.03021732,1.54193656-.03021732h113.996991s18.91133391,2.14662887,14.04367038,22.08585897l-40.10529767,107.46647552h0l-.00002307-.01513172ZM251.97398813,265.21202671s-33.80152739-17.52055313-26.69654845-49.3720026l44.85202273-124.30679305c7.22590587-20.02997431,26.24304651-33.39336296,47.54284008-33.39336296h143.64135391c9.44810109,0,18.29153294,4.58043756,23.74873399,12.30520594l20.99748201,29.75019271h-170.7763187c-13.15175211,0-24.92787822,8.17828184-29.50831579,20.51372816l-53.80126132,144.51816352h0l.00001153-.01513172ZM201.25658839,207.07215861s-33.81664758-17.52055313-26.69655421-49.3720026l44.8520285-124.30679305C226.65308874,13.36338865,245.67022938,0,266.95491429,0h135.9166086c9.44810109,0,18.29153294,4.58043756,23.74875705,12.30520594l20.99745894,29.75019271h-163.02130994c-13.15130994,0-24.92786669,8.17828184-29.50831579,20.51372816l-53.80126132,144.51816352h-.03022885l-.0000346-.01513172Z" fill="url(#hypit-callback-mark)"/></svg>`;--function base64url(bytes: Uint8Array): string {- return Buffer.from(bytes).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");-}-function createPublicBuildId(now = Date.now()): string {return orderedBuildId(now, randomBytes(5).toString("hex").toUpperCase());}-async function hypiHubOAuthLogin(io: CliIo): Promise<string> {- const verifier = base64url(randomBytes(32));- const challenge = base64url(createHash("sha256").update(verifier).digest());- const state = base64url(randomBytes(24));- const server = createServer();- const callback = new Promise<string>((resolveCode, reject) => {- let settled = false;- let closeRequested = false;- const closeServer = (): void => {- if (closeRequested) return;- closeRequested = true;- server.close();- server.closeIdleConnections?.();- };- const closeAllConnections = (): void => {- server.closeAllConnections?.();- server.unref();- };- server.on("request", (request, response) => {- // Browsers commonly fetch /favicon.ico after rendering the callback.- // The old one-shot listener left that second connection unanswered,- // keeping the local server (and therefore the CLI) alive forever after- // a successful login.- if (settled) {- response.writeHead(204, { "cache-control": "no-store", connection: "close" });- response.end();- return;- }- try {- const url = new URL(request.url ?? "/", "http://127.0.0.1");- if (url.pathname !== "/callback") throw new Error("unexpected OAuth callback path");- if (url.searchParams.get("state") !== state) throw new Error("HypiHub OAuth state mismatch");- const error = url.searchParams.get("error");- if (error !== null) throw new Error(`HypiHub OAuth authorization failed: ${error}`);- const code = url.searchParams.get("code");- if (code === null || code.length === 0) throw new Error("HypiHub OAuth callback contained no code");- response.writeHead(200, {- "cache-control": "no-store",- connection: "close",- "content-type": "text/html; charset=utf-8",- });- response.end(oauthCallbackPage(true), closeAllConnections);- settled = true;- resolveCode(code);- } catch (error) {- response.writeHead(400, {- "cache-control": "no-store",- connection: "close",- "content-type": "text/html; charset=utf-8",- });- response.end(oauthCallbackPage(false), closeAllConnections);- settled = true;- reject(error);- } finally {- // Resolve the OAuth operation immediately; a browser may keep the- // callback connection around for its favicon request. The server is- // closed and unref'ed so that request cannot keep the CLI alive.- closeServer();- server.unref();- }- });- server.once("error", reject);- });- await new Promise<void>((resolveListen, rejectListen) => {- server.listen(0, "127.0.0.1", () => resolveListen());- server.once("error", rejectListen);- });- const address = server.address();- if (address === null || typeof address === "string") throw new Error("could not open a local OAuth callback");- const redirectUri = `http://127.0.0.1:${address.port}/callback`;- // Open the site's SPA consent surface rather than the protocol endpoint.- // The latter can only read a browser session from an Authorization header,- // while the login page stores the session in localStorage. Returning there- // after login would therefore bounce straight back to /login forever. The- // consent page reads that localStorage token and calls /oauth/authorize with- // the required header.- const authorize = new URL("https://hypit.ai/oauth/consent");- authorize.search = new URLSearchParams({- response_type: "code", client_id: HYPIHUB_OAUTH_CLIENT_ID, redirect_uri: redirectUri,- scope: "user:profile user:inference", state, code_challenge: challenge, code_challenge_method: "S256",- }).toString();- io.write(`Opening HypiHub login: ${authorize}\n`);- const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";- const openerArgs = process.platform === "win32" ? ["/c", "start", "", authorize.toString()] : [authorize.toString()];- spawn(opener, openerArgs, { stdio: "ignore", detached: true, windowsHide: true }).unref();- const code = await callback;- const tokenResponse = await fetch("https://hypit.ai/oauth/token", {- method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" },- body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: HYPIHUB_OAUTH_CLIENT_ID, code_verifier: verifier }),- signal: AbortSignal.timeout(15_000),- });- const body = await tokenResponse.text();- if (!tokenResponse.ok) throw new Error(`HypiHub OAuth token exchange failed (${tokenResponse.status}): ${body.slice(0, 200)}`);- const parsed = JSON.parse(body) as { access_token?: unknown };- if (typeof parsed.access_token !== "string" || parsed.access_token.length === 0) throw new Error("HypiHub OAuth returned no access token");- return parsed.access_token;-}--/**- * The loopback callback is the last screen a person sees during login. Keep it- * self-contained: relying on a remote stylesheet or image makes a successful- * login look broken when the network is settling, and the old plain-text body- * had no visual identity at all.- */-function oauthCallbackPage(success: boolean): string {- const title = success ? "Signed in to Hypit" : "Hypit sign-in failed";- const heading = success ? "Hypit is signed in" : "Hypit sign-in failed";- const message = success- ? "Your HypiHub session is ready. You can close this window."- : "The sign-in could not be completed. You can close this window and try again.";- const tone = success ? "success" : "error";- const favicon = `data:image/svg+xml,${encodeURIComponent(HYPIHUB_MARK_SVG)}`;- return `<!doctype html>-<html lang="en">- <head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">- <meta name="color-scheme" content="light dark">- <link rel="icon" href="${favicon}">- <title>${title}</title>- <style>- :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }- * { box-sizing: border-box; }- body { margin: 0; min-height: 100vh; display: grid; place-items: center; color: #18181b; background: #f7f6f3; }- main { width: min(100% - 48px, 560px); padding: 48px 42px 52px; border: 1px solid #e2dfdb; border-radius: 16px; background: #fff; box-shadow: 0 18px 50px rgba(24,24,27,.08); }- .brand { display: inline-flex; align-items: center; gap: 10px; color: #18181b; font-size: 18px; font-weight: 650; letter-spacing: -.04em; }- .brand svg { width: 28px; height: 28px; }- .wordmark { background: linear-gradient(110deg, #e83f5f, #f6a9bd); -webkit-background-clip: text; background-clip: text; color: transparent; }- .mark { width: 58px; height: 58px; margin: 72px 0 28px; display: grid; place-items: center; border: 1px solid #ddd9d5; border-radius: 14px; background: #fff; color: #e83f5f; }- .mark.success { color: #e83f5f; }- .mark.error { color: #c73d45; border-color: #e2c9c9; background: #fffafa; }- h1 { margin: 0; font-size: clamp(26px, 7vw, 34px); line-height: 1.08; letter-spacing: -.035em; }- p { margin: 14px 0 0; color: #66636a; font-size: 15px; line-height: 1.6; }- @media (prefers-color-scheme: dark) {- body { color: #f7f2f4; background: #111114; }- .brand { color: #f7f2f4; }- main { border-color: #3a3036; background: #19171b; box-shadow: 0 24px 70px rgba(0,0,0,.36); }- .mark { border-color: #3a3036; background: #19171b; }- .mark.error { border-color: #6b3f40; background: #291d1e; }- p { color: #bdb3b8; }- }- </style>- </head>- <body>- <main>- <div class="brand" aria-label="Hypit">- ${HYPIHUB_MARK_SVG}- <span class="wordmark">hypit</span>- </div>- <div class="mark ${tone}" aria-hidden="true">- ${success ? '<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="square"><path d="m5 12 4 4L19 6"/></svg>' : '<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="square"><path d="M6 6 18 18M18 6 6 18"/></svg>'}- </div>- <h1>${heading}</h1>- <p>${message}</p>- </main>- </body>-</html>`;-}--async function nearestProjectPackageRoot(start: string): Promise<string | undefined> {- let directory = resolve(start);- while (true) {- const candidate = resolve(directory, "package.json");- try {- if ((await stat(candidate)).isFile()) return directory;- } catch (error) {- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;- }- const parent = dirname(directory);- if (parent === directory) return undefined;- directory = parent;- }-}--async function resolvePackageRoot(projectStart: string): Promise<string> {- // The Distribution is a separate read-only fallback. Package discovery must- // retain the project root even when this lightweight project has no package.json.- return await nearestProjectPackageRoot(projectStart) ?? resolve(projectStart);-}--function parseArgs(argv: readonly string[]): ParsedArgs {- const [command, ...tail] = argv;- const scoped = command === "programs" || command === "runtime" || command === "auth" || command === "result"- || command === "packages";- const action = scoped ? tail[0] : undefined;- const positional = scoped ? tail.slice(1) : tail;- const noFile = command === "builds" || command === "activity" || command === "paths";- const hasFile = !noFile && positional[0] !== undefined && !positional[0]!.startsWith("--");- const file = hasFile ? positional[0] : undefined;- const rest = noFile || !hasFile ? positional : positional.slice(1);- let workspaceRoot: string | undefined;- const assetRoots: string[] = [];- let packageRoot: string | undefined;- let runtime: string | undefined;- let follow = false;- let maxWaitMs: number | undefined;- let output: string | undefined;- let title: string | undefined;- let note: string | undefined;- const highlightedOutputs: string[] = [];- let clearTitle = false;- let clearNote = false;- let clearHighlights = false;- let limit = 20;- let lines = 50;- let before: string | undefined;- let to: string | undefined;- let json = false;- let color: CliColorMode = "auto";- let verbose = false;- let watch = false;- let jsonl = false;- let readyFile: string | undefined;- let workerOwner: string | undefined;- let reason: string | undefined;- let slot: string | undefined;- let from: string | undefined;- let source: string | undefined;- const seenOptions = new Set<string>();- for (let index = 0; index < rest.length; index += 1) {- const item = rest[index]!;- if (item.startsWith("--")) {- const repeatable = [- "--json", "--jsonl", "--watch", "--verbose", "--debug",- "--no-color", "--follow", "--asset-root", "--highlight",- ].includes(item);- if (!repeatable && seenOptions.has(item)) throw new Error(`${item} cannot be repeated`);- seenOptions.add(item);- }- if (item === "--json") {- json = true;- continue;- }- if (item === "--jsonl") {- jsonl = true;- continue;- }- if (item === "--watch") {- watch = true;- continue;- }- if (item === "--verbose") {- verbose = true;- continue;- }- if (item === "--debug") {- continue;- }- if (item === "--no-color") {- color = "never";- continue;- }- if (item === "--color") {- const value = rest[index + 1];- if (value !== "auto" && value !== "always" && value !== "never") {- throw new Error("--color requires auto, always or never");- }- color = value;- index += 1;- continue;- }- if (item === "--workspace") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--workspace requires a directory");- workspaceRoot = resolve(value);- index += 1;- continue;- }- if (item === "--asset-root") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--asset-root requires a directory");- assetRoots.push(resolve(value));- index += 1;- continue;- }- if (item === "--package-root") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--package-root requires a directory");- packageRoot = resolve(value);- index += 1;- continue;- }- if (item === "--runtime") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--runtime requires a Runtime Profile");- runtime = resolve(value);- index += 1;- continue;- }- if (item === "--out") {- throw new Error("--out does not apply to Build submission; use `get <build-id> --output <name> --to <path>` to export one Result Output");- }- if (item === "--output") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--output requires a public Output name");- output = value;- index += 1;- continue;- }- if (item === "--title") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--title requires text");- title = value;- index += 1;- continue;- }- if (item === "--note") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--note requires text");- note = value;- index += 1;- continue;- }- if (item === "--highlight") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--highlight requires an Output name");- highlightedOutputs.push(value);- index += 1;- continue;- }- if (item === "--clear-title") {- clearTitle = true;- continue;- }- if (item === "--clear-note") {- clearNote = true;- continue;- }- if (item === "--clear-highlights") {- clearHighlights = true;- continue;- }- if (item === "--limit") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--limit requires a positive integer");- limit = Number(value);- if (!Number.isSafeInteger(limit) || limit < 1) throw new Error("--limit requires a positive integer");- 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");- before = value;- index += 1;- continue;- }- if (item === "--to") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--to requires a file path");- to = resolve(value);- index += 1;- continue;- }- if (item === "--follow") {- follow = 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");- maxWaitMs = Number(value);- if (!Number.isSafeInteger(maxWaitMs) || maxWaitMs < 0) {- throw new Error("--max-wait-ms must be a non-negative safe integer");- }- index += 1;- continue;- }- if (item === "--ready-file") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--ready-file requires a path");- readyFile = resolve(value);- index += 1;- continue;- }- if (item === "--worker-owner") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--worker-owner requires an identity");- workerOwner = value;- index += 1;- continue;- }- if (item === "--reason") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--reason requires text");- reason = value;- index += 1;- continue;- }- if (item === "--slot") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--slot requires a credential slot");- slot = value;- index += 1;- continue;- }- if (item === "--from") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--from requires a credential file");- from = resolve(value);- index += 1;- continue;- }- if (item === "--source") {- const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--source requires a source path");- source = resolve(value);- index += 1;- continue;- }- throw new Error(`unknown option ${item}`);- }- return {- command,- action,- file,- workspaceRoot,- assetRoots,- packageRoot,- runtime,- follow,- maxWaitMs,- output,- title,- note,- highlightedOutputs,- clearTitle,- clearNote,- clearHighlights,- limit,- lines,- before,- to,- json,- color,- verbose,- watch,- jsonl,- readyFile,- workerOwner,- reason,- slot,- from,- source,- seenOptions: [...seenOptions],- };-}--function assertCommandOptions(args: ParsedArgs): void {- const common = ["--json", "--color", "--no-color", "--verbose", "--debug"];- const allowed = new Set(common);- const add = (...items: readonly string[]): void => { for (const item of items) allowed.add(item); };- switch (args.command) {- case "programs":- // 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", "--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", "--limit");- break;- case "paths":- add("--runtime");- break;- case "get":- add("--workspace", "--output", "--to");- break;- case "cancel":- add("--runtime", "--reason");- break;- case "result":- if (args.action === "finish" || args.action === "discard") add("--runtime");- if (args.action === "edit") {- add("--workspace", "--title", "--note", "--highlight", "--clear-title", "--clear-note", "--clear-highlights", "--limit");- }- break;- case "doctor":- add("--workspace", "--limit");- break;- case "status":- add("--runtime", "--watch", "--limit");- if (args.watch) add("--max-wait-ms");- break;- case "builds":- case "history":- add("--workspace", "--limit", "--before");- if (args.command === "history") add("--source");- break;- case "inspect":- add("--workspace", "--output", "--limit");- break;- case "check":- case "plan":- add("--runtime", "--package-root", "--workspace", "--asset-root", "--limit");- break;- case "build":- add("--runtime", "--package-root", "--workspace", "--asset-root", "--follow",- "--max-wait-ms", "--title", "--limit");- break;- }- const invalid = args.seenOptions.find((item) => !allowed.has(item));- if (invalid !== undefined) {- const command = args.action === undefined ? args.command : `${args.command} ${args.action}`;- throw new Error(`${invalid} does not apply to ${command}`);- }- if (args.seenOptions.includes("--color") && args.seenOptions.includes("--no-color")) {- throw new Error("--color and --no-color are mutually exclusive");- }- if (args.command === "get" && args.output === undefined) {- throw new Error("get requires --output with one public Output name");- }- if (args.command === "get" && args.to === undefined) {- throw new Error("get requires --to with the export destination");- }-}--function usage(): string {- return [- "usage: hypit <command> [options]",- "",- "Run `hypit help` for commands or `hypit help <command>` for exact syntax.",- ].join("\n");-}--function createCatalogDescriptor(options: {- readonly source: string;- readonly compilation: NodeCompiledSourceClosure;- readonly run?: { readonly path: string };-}): BuildCatalogDescriptor {- const publishedOutputs = options.compilation.exports.flatMap((item) => {- if (item.ref.kind === "operation-result") {- throw new Error(`public output ${item.name} was not lowered to a stable Record or Logical Output`);- }- return item.ref.kind === "logical-output" ? [{ name: item.name, ref: item.ref }] : [];- });- const names = new Set<string>();- const outputs = new Set<string>();- for (const published of publishedOutputs) {- if (names.has(published.name)) throw new Error(`public Output name ${published.name} is repeated`);- if (outputs.has(published.ref.id)) {- throw new Error(`Logical Output ${published.ref.id} has more than one public name`);- }- names.add(published.name);- outputs.add(published.ref.id);- }- return {- source: {- path: resolve(options.source),- },- ...(options.run === undefined ? {} : { run: {- path: resolve(options.run.path),- } }),- publishedOutputs,- };-}--function demandedCapabilities(state: BuildState): readonly CapabilityRef[] {- const found = new Map(plannedNeeds(state).map((need) => [capabilityName(need.capability), need.capability]));- return [...found.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([, value]) => value);-}--function capabilityName(capability: CapabilityRef): string {- return `${capability.module.name}@${capability.module.version}#${capability.name}`;-}--async function preflightPlan(- host: NodeRuntimeHost,- state: BuildState,-) {- const capabilities = demandedCapabilities(state);- const result = await host.preflight({ capabilities });- return {- ok: !result.diagnostics.some((item) => item.severity === "error"),- capabilities: capabilities.map(capabilityName),- diagnostics: result.diagnostics,- } as const;-}--function assertPreflight(- preflight: Awaited<ReturnType<typeof preflightPlan>>,-): void {- if (preflight === undefined || preflight.ok) return;- const errors = preflight.diagnostics.filter((item) => item.severity === "error");- throw new Error([- `Runtime preflight failed for ${errors.length} demanded deployment requirement${errors.length === 1 ? "" : "s"}:`,- ...errors.map((item) => ` ${item.code}${item.subject === undefined ? "" : ` (${item.subject})`}: ${item.message}`),- "No Build was submitted and no external capability request was made.",- ].join("\n"));-}-async function loadRuntime(host: NodeRuntimeHost): Promise<CliRuntime> {return await host.createRuntime();}-async function loadRuntimeControl(- host: NodeRuntimeHost,- readOnly = true,-): Promise<CliRuntimeControl> {- return await host.openControl({ readOnly });-}--function formatOperationProgress(progress: OperationProgress): string {- if (progress.completed === undefined) return progress.phase;- const amount = progress.total === undefined- ? String(progress.completed)- : `${progress.completed}/${progress.total}`;- return `${progress.phase} · ${amount}${progress.unit === undefined ? "" : ` ${progress.unit}`}`;-}--type QueueLaneSummary = {- readonly pool: string;- readonly lane: string;- readonly inFlight: number;-};--/** Derive the Provider → capability view from generic tickets; no model registry participates. */-function summarizeQueueLanes(capacity: readonly CapacityReservation[]): readonly QueueLaneSummary[] {- const groups = new Map<string, QueueLaneSummary>();- for (const ticket of capacity) {- if (ticket.queue === undefined) continue;- const key = `${ticket.queue.pool}\u0000${ticket.queue.lane}`;- const previous = groups.get(key);- groups.set(key, {- pool: ticket.queue.pool,- lane: ticket.queue.lane,- inFlight: (previous?.inFlight ?? 0) + 1,- });- }- return [...groups.values()].sort((left, right) =>- left.pool.localeCompare(right.pool) || left.lane.localeCompare(right.lane));-}--function queueLaneLines(groups: readonly QueueLaneSummary[]): readonly string[] {- const lines: string[] = [];- let pool: string | undefined;- for (const group of groups) {- if (group.pool !== pool) {- pool = group.pool;- lines.push(pool);- }- lines.push(` ${group.lane}: ${group.inFlight} remote`);- }- return lines;-}--function inlineValuePreview(value: unknown, limit = 240): string {- const encoded = JSON.stringify(value);- if (encoded.length <= limit) return encoded;- return `${encoded.slice(0, Math.max(0, limit - 3))}...`;-}--async function observeBuild(- runtime: Pick<CliRuntimeControl, "inspect">,- initial: CliBuildSubmission,- options: {- readonly maxWaitMs?: number;- readonly controller?: CliRuntimeController;- readonly readResult: () => Promise<BuildResultManifest | undefined>;- readonly onProgress?: (value: {- readonly build: string;- readonly phase: string;- readonly operations: Readonly<Record<string, number>>;- readonly activity: readonly string[];- }) => void;- },-): Promise<CliBuildSubmission> {- let current = initial;- let lastProgress: string | undefined;- let pollDelayMs = 100;- let observedActivity = false;- const startedAt = Date.now();- const finishFromResult = async (): Promise<CliBuildSubmission> => {- const result = await options.readResult();- if (result?.outcome === undefined) {- throw new Error(`Build ${current.id} left active Runtime state without a finished Result`);- }- return {- id: current.id,- state: current.state,- completion: {- build: current.id,- outcome: result.outcome,- ...(result.failure === undefined ? {} : { reason: result.failure }),- },- };- };- while ("view" in current && current.view.issue === undefined) {- const elapsedMs = Date.now() - startedAt;- const remainingMs = options.maxWaitMs === undefined- ? undefined- : options.maxWaitMs - elapsedMs;- if (remainingMs !== undefined && remainingMs <= 0) break;- const waitMs = remainingMs === undefined- ? pollDelayMs- : Math.min(pollDelayMs, remainingMs);- await new Promise((resolveWait) => setTimeout(resolveWait, waitMs));- const view = await runtime.inspect(current.id);- observedActivity = true;- if (view === undefined) {- current = await finishFromResult();- break;- }- current = {- id: current.id,- state: current.state,- view,- };- if (current.view.issue === undefined- && options.controller !== undefined) {- const worker = await options.controller.worker.status();- if (worker.state !== "running") {- throw new Error(- `Runtime Worker is ${worker.state}; Build ${current.id} remains durable. `- + `Run hypit runtime up, then run hypit status ${current.id} --watch again`,- );- }- }- const operations = Object.fromEntries([...new Set(view.operations.map((item) => item.status))]- .sort().map((state) => [state, view.operations.filter((item) => item.status === state).length]));- const activity = view.operations- .filter((item) => item.status === "pending")- .map((item) => `${item.endpoint}: ${item.progress === undefined- ? item.status- : formatOperationProgress(item.progress)}`);- const nextProgress = JSON.stringify({- buildActivity: view.activity,- outcome: view.outcome,- operations,- activity: view.operations.map((item) => ({- endpoint: item.endpoint,- status: item.status,- progress: item.progress,- })),- });- if (nextProgress !== lastProgress) {- lastProgress = nextProgress;- pollDelayMs = 100;- options.onProgress?.({- build: current.id,- phase: view.activity,- operations,- activity,- });- } else {- pollDelayMs = Math.min(1_000, pollDelayMs * 2);- }- }- if (observedActivity && "view" in current) {- const view = await runtime.inspect(current.id);- if (view === undefined) {- return await finishFromResult();- }- current = {- id: current.id,- state: current.state,- view,- };- }- return current;-}-export async function runCli(argv: readonly string[],io: CliIo,@@ -917,23 +81,6 @@ export async function runCli(color: args.color,verbose: args.verbose,}, { kind: "operational", machine, title, status, facts, lines });- const reportProgramProgress = args.json || args.jsonl- ? undefined- : (event: CliManagedProgramProgress): void => {- const verb = {- checking: "Checking",- installing: "Installing",- starting: "Starting",- waiting: "Waiting for",- ready: "Ready",- }[event.phase];- io.write(` · ${verb} ${event.id}\n`);- };- const reportPackageProgress = args.json || args.jsonl- ? undefined- : (event: { readonly specifier: string; readonly phase: "checking" | "installing" | "ready" }): void => {- if (event.phase === "installing") io.write(` · Installing ${event.specifier}\n`);- };const runtimeHosts = new Map<string, Promise<NodeRuntimeHost>>();const runtimeHost = async (path: string, requestedPackageRoot?: string): Promise<NodeRuntimeHost> => {const profile = resolve(path);@@ -952,22 +99,11 @@ export async function runCli(return await opened;};const projectResults = async (projectRoot = commandProjectRoot()) => {- if (distribution.openProjectResults !== undefined) {- const packageRoot = await packageRootForProject(projectRoot);- return await distribution.openProjectResults(projectRoot, {- packageRoot,- ...(distribution.packageRoot === undefined ? {} : { distributionPackageRoot: distribution.packageRoot }),- });- }- const root = join(projectRoot, ".hypit", "results");- return {- location: {- root: projectRoot,- selection: { use: "@hypit/build-result-fs", config: { path: ".hypit/results" } },- },- repository: new FileBuildResultRepository(root),- close() {},- } as const;+ const packageRoot = await packageRootForProject(projectRoot);+ return await distribution.openProjectResults(projectRoot, {+ packageRoot,+ ...(distribution.packageRoot === undefined ? {} : { distributionPackageRoot: distribution.packageRoot }),+ });};if (args.command === "_worker") {if (args.file === undefined || args.readyFile === undefined || args.workerOwner === undefined) {@@ -1003,7 +139,7 @@ export async function runCli(throw new Error("runtime unset does not take a Runtime Profile");}assertCommandOptions(args);- const cleared = await clearRuntimeProfile(process.cwd());+ const cleared = await clearRuntimeProfile(args.workspaceRoot ?? process.cwd());writeOperational({format: "hypit.cli-runtime-selection@2",selected: false,@@ -1022,7 +158,8 @@ export async function runCli(let runtimeNeedsHint = runtimeWasExplicit;if (args.runtime === undefined && !positionalRuntime) {const sourceScoped = args.command === "check" || args.command === "plan" || args.command === "build";- const start = sourceScoped && args.file !== undefined ? dirname(resolve(args.file)) : process.cwd();+ const start = args.workspaceRoot+ ?? (sourceScoped && args.file !== undefined ? dirname(resolve(args.file)) : process.cwd());const selected = await findRuntimeProfile(start);if (selected !== undefined) {args = { ...args, runtime: selected.profile };@@ -1032,19 +169,8 @@ export async function runCli(|| isAbsolute(cwdFromProject);}}- const known = args.command === "check" || args.command === "plan"- || args.command === "build" || args.command === "status" || args.command === "builds"- || args.command === "history"- || args.command === "inspect" || args.command === "get" || args.command === "cancel"- || args.command === "result"- || args.command === "doctor" || args.command === "programs"- || args.command === "runtime" || args.command === "activity" || args.command === "paths"- || 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 === "programs" || args.command === "runtime" || args.command === "doctor";- if (!operational || (!fileOptional && args.file === undefined)) {+ if (!isKnownCommand(args.command)+ || (!commandAllowsMissingPositional(args.command) && args.file === undefined)) {throw new Error(usage());}if (args.watch && args.command !== "activity" && args.command !== "status") {@@ -1084,778 +210,39 @@ export async function runCli(packageRoot,});};- if (args.command === "paths") {- const projectRoot = selectedRuntimeProjectRoot ?? process.cwd();- const runtimePaths = args.runtime === undefined- ? undefined- : await (await runtimeHost(args.runtime)).resolvePaths();- const machine = {- format: "hypit.cli-paths@1" as const,- project: projectRoot,- projectState: hypitProjectStateRoot(projectRoot),- profile: args.runtime,- runtimeData: runtimePaths?.runtimeDataRoot,- hostState: hypitHostStateRoot(),- machinePackages: hypitHostPackageRoot(),- distribution: distribution.packageRoot,- };- writeOperational(machine, "Hypit paths", "info", [- ["Project", machine.project],- ["Project state", machine.projectState],- ["Runtime Profile", machine.profile ?? "not selected"],- ["Runtime data", machine.runtimeData ?? "not selected"],- ["Host state", machine.hostState],- ["Machine packages", machine.machinePackages],- ["Distribution", machine.distribution ?? "embedded"],- ]);- return;- }- if (args.command === "packages") {- if (args.action !== "install" && args.action !== "status") {- throw new Error("packages takes install or status");- }- if (args.file === undefined) throw new Error(`packages ${args.action} requires package@exact-version`);- const root = hypitHostPackageRoot();- const existing = await inspectHostPackage(args.file, root);- const reports = args.action === "install"- ? await prepareHostPackages([args.file], {- root,- ...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }),- })- : existing === undefined ? [] : [existing];- const ready = reports.length === 1;- writeOperational({- 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],- ["Ready", String(ready)],- ]);- if (!ready) io.setExitCode?.(1);- return;- }- if (args.command === "doctor") {- if (args.packageRoot !== undefined) {- throw new Error("doctor reads all deployment selection from the Runtime Profile itself");- }- const profileInput = args.runtime ?? args.file;- if (profileInput === undefined) {- throw new Error("doctor requires a Runtime Profile; run hypit runtime use <profile> or provide it positionally");- }- const profile = resolve(profileInput);- const [result, projectResult] = await Promise.all([- (await runtimeHost(profile)).doctor(),- distribution.diagnoseProjectResults === undefined- ? undefined- : distribution.diagnoseProjectResults(commandProjectRoot(), {- packageRoot: await packageRootForProject(),- ...(distribution.packageRoot === undefined- ? {}- : { distributionPackageRoot: distribution.packageRoot }),- }),- ]);- const diagnostics = [...result.diagnostics, ...(projectResult?.diagnostics ?? [])];- const machine = {- format: "hypit.cli-doctor@2" as const,- ok: !diagnostics.some((item) => item.severity === "error"),- 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 });- if (!machine.ok) io.setExitCode?.(1);- return;- }- if (args.command === "programs") {- if (args.file !== undefined && args.runtime !== undefined) {- throw new Error("programs reads all deployment selection from the Runtime Profile itself; provide that Profile only once");- }- if (args.packageRoot !== undefined) {- throw new Error("programs reads all deployment selection from the Runtime Profile itself");- }- if (args.action !== "up" && args.action !== "down" && args.action !== "status") {- throw new Error("programs takes up, down or status");- }- if (args.action !== "up" && args.maxWaitMs !== undefined) {- throw new Error("--max-wait-ms applies to programs up");- }- const profileInput = args.runtime ?? args.file;- if (profileInput === undefined) throw new Error("programs requires a Runtime Profile");- const profile = resolve(profileInput);- const host = await runtimeHost(profile);- const prepared = args.action === "up"- ? await host.prepare(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress })- : [];- const controller = await runtimeController(profile);- const result = args.action === "up"- ? await controller.programs.up({- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),- ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),- })- : args.action === "down"- ? await controller.programs.down()- : 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 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,- 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((item) => `${item.id}: ${item.state.state}`));- if (!lifecycleOk) io.setExitCode?.(1);- return;- }- if (args.command === "runtime") {- if (args.action !== "up" && args.action !== "down" && args.action !== "status" && args.action !== "logs") {- throw new Error("runtime takes up, down, status or logs");- }- if (args.file !== undefined && args.runtime !== undefined) {- throw new Error("runtime accepts the Runtime Profile either positionally or with --runtime, not both");- }- const profileInput = args.runtime ?? args.file;- if (profileInput === undefined) throw new Error("runtime requires a Runtime Profile");- const profile = resolve(profileInput);- const controller = await runtimeController(profile);- if (args.action === "up") {- const packageRoot = await packageRootForProject();- const host = await runtimeHost(profile, packageRoot);- const prepared = await host.prepare(- reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress },- );- // Read the Runtime Profile before starting the Worker or its programs.- const validated = await loadRuntime(host);- await validated.close();- const external = await controller.programs.up({- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),- ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),- });- const processState = await controller.worker.up({- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),- });- const ok = processState.state === "running"- && external.programs.every((item) => item.state.state === "ready");- 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", processState.state],- ["External programs", String(external.programs.length)],- ]);- if (!ok) io.setExitCode?.(1);- return;- }- 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 = lines.slice(-args.lines);- writeOperational({- 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", [- ["Lines", `${shown.length}/${lines.length}`],- ...(args.verbose ? [["Path", logs.path] as const] : []),- ], shown.length === 0 ? ["No log output."] : shown);- return;- }- if (args.action === "down") {- const worker = await controller.worker.down({- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),- });- 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;- }- // These are independent views over one Profile. Load them concurrently without inventing a- // second registry; each selected package remains responsible for its own report.- const runtimeLoading = loadRuntimeControl(await runtimeHost(profile));- let runtime: CliRuntimeControl | undefined;- try {- const loaded = await Promise.all([- controller.worker.status(),- controller.programs.report(),- runtimeLoading,- ]);- const [worker, external, selectedRuntime] = loaded;- runtime = selectedRuntime;- const activity = await runtime.activity();- const counts = Object.fromEntries(- [- ["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"- && external.programs.every((item) => item.state.state === "ready");- const active = activity.builds.length;- 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@2" as const,- ready,- attention,- 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],- ["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`],- ...(args.verbose ? [["Active requests", String(activity.capacity.length)] as const] : []),- ], [- ...unavailable.slice(0, args.limit).map((item) => `${item.id}: ${item.state.state}`),- ...(args.verbose ? queueLaneLines(lanes.slice(0, args.limit)) : []),- ]);- } finally {- if (runtime !== undefined) await runtime.close();- else await runtimeLoading.then(async (loaded) => await loaded.close(), () => undefined);- }- return;- }- if (args.command === "auth") {- if (args.action !== "status" && args.action !== "login" && args.action !== "logout") {- throw new Error("auth takes status, login or logout");- }- if (args.runtime === undefined) {- throw new Error("auth requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>");- }- if (args.from !== undefined && args.action !== "login") throw new Error("--from applies only to auth login");- const runtime = await (await runtimeHost(args.runtime)).openCredentials(args.file!);- try {- let credentials = await runtime.credentials(args.file!);- if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);- if (credentials.length === 0) throw new Error(`Endpoint ${args.file} has no matching credential`);- if (args.slot === undefined && credentials.length > 1 && args.action !== "status") {- throw new Error(`Endpoint ${args.file} has several credentials; select one with --slot`);- }- if (args.action === "status") {- 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.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`- : "select a writable credential source in the Runtime Profile";- throw new Error(- `${item.label} cannot be written by this command; ${source}`,- );- }- const oauth = item.ref.store === "os" && /hypihub/iu.test(`${item.endpoint} ${item.ref.key}`);- const raw = oauth && args.from === undefined- ? await hypiHubOAuthLogin(io)- : args.from === undefined- ? await io.readSecret?.(`${item.label}: `)- : await readFile(args.from, "utf8");- if (raw === undefined) throw new Error("interactive credential input is unavailable; use --from <file>");- const secret = raw.trim();- if (secret.length === 0) throw new Error("credential input is empty");- if (item.kind === "json") {- 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({- 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({- 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],- ]);- }- } finally {- await runtime.close();- }- return;- }- if (args.command === "builds" || args.command === "history" || args.command === "inspect"- || args.command === "get" || (args.command === "result" && args.action === "edit")) {+ if (await runEnvironmentCommand({+ args,+ io,+ distribution,+ projectRoot: args.command === "paths" ? selectedRuntimeProjectRoot ?? process.cwd() : commandProjectRoot(),+ packageRootForProject,+ runtimeHost,+ runtimeController,+ write: writeOperational,+ })) return;+ if (isProjectResultCommand(args)) {const results = await projectResults();- const repository = results.repository;try {- if (args.command === "builds") {- const page = await repository.browse({ limit: args.limit, ...(args.before === undefined ? {} : { before: args.before }) });- const builds = page.results.map((manifest) => ({- id: manifest.id,- createdAt: buildCreatedAtIso(manifest.id),- ...(manifest.title === undefined ? {} : { title: manifest.title }),- outcome: manifest.outcome,- ...(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@3", builds, ...(page.next === undefined ? {} : { next: page.next }) },- "Build results", "info", [["Builds", String(builds.length)]],- builds.map((item) => {- 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 matches = page.results.flatMap((manifest) => {- if (source !== undefined && manifest.source.path !== source) return [];- return manifest.outputs[args.file!] === undefined ? [] : [manifest];- });- 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@3",- output: args.file,- ...(source === undefined ? {} : { source: projectPath(source, commandProjectRoot()) }),- entries,- ...(page.next === undefined ? {} : { next: page.next }),- }, entries.length === 0 ? "No matching Output" : "Output history",- entries.length === 0 ? "warning" : "info", [- ["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 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))],- ], [- ...(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;- }- if (args.command === "result") {- const manifest = await repository.updatePresentation(args.file!, {- ...(args.clearTitle ? { title: null } : args.title === undefined ? {} : { title: args.title }),- ...(args.clearNote ? { note: null } : args.note === undefined ? {} : { note: args.note }),- ...(args.clearHighlights- ? { highlightedOutputs: [] }- : args.highlightedOutputs.length === 0 ? {} : { highlightedOutputs: args.highlightedOutputs }),- });- const presentation = {- format: "hypit.cli-result-edit@3",- build: manifest.id,- title: manifest.title ?? null,- note: manifest.note ?? null,- 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],- ["Title", manifest.title ?? "—"],- ["Highlighted", String(manifest.highlightedOutputs?.length ?? 0)],- ], manifest.note === undefined ? [] : [`Note ${manifest.note}`]);- return;- }- const exported = await exportBuildResultOutput(repository, args.file!, args.output!, args.to!);- 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", machine.type],- ["Kind", exported.kind],- ["Path", exported.path],- ]);- return;+ await runProjectResultCommand({+ args,+ projectRoot: commandProjectRoot(),+ repository: results.repository,+ write: writeOperational,+ });} finally {await results.close();}- }- if (args.command === "status" && args.runtime === undefined) {- const openedResults = await projectResults();- let result;- try {- result = await openedResults.repository.read(args.file!);- } finally {- await openedResults.close();- }- if (args.watch && result?.outcome === undefined) {- throw new Error(- `Build ${args.file} has no finished Result; select its Runtime to observe active execution`,- );- }- const finished = result?.outcome !== undefined;- const build = result === undefined ? null : buildStatusView({ id: result.id, result });- const machine = {- 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!],- ["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.",- ]);- if (result === undefined || !finished) io.setExitCode?.(1);return;}- if (args.command === "status" || args.command === "cancel" || args.command === "activity"- || (args.command === "result" && (args.action === "finish" || args.action === "discard"))- ) {- if (args.runtime === undefined) {- throw new Error(- `${args.command} requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>`,- );- }- const selectedHost = await runtimeHost(args.runtime);- const runtime = await loadRuntimeControl(- selectedHost,- args.command !== "cancel",- );- try {- if (args.command === "activity") {- const controller = await runtimeController(args.runtime);- let previous: string | undefined;- const writeActivity = async (): Promise<void> => {- const [activity, worker] = await Promise.all([- runtime.activity(),- controller.worker.status(),- ]);- const currentView = JSON.stringify({- builds: activity.builds,- capacity: activity.capacity,- worker,- });- 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@2",- at: Date.now(),- 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.limit).map((item) =>- `${item.id}: ${buildStatusView({ id: item.id, runtime: item }).work.state}`- + `${item.cancellationRequested ? " · cancelling" : ""}`- + `${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)}`)).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.state],- ], [- ...buildLines,- ...(operationLines.length === 0 ? [] : ["Operations:", ...operationLines]),- ...(args.verbose ? queueLaneLines(summarizeQueueLanes(activity.capacity)) : []),- ]);- };- if (!args.watch) await writeActivity();- else while (true) {- await writeActivity();- await new Promise((resolveWait) => setTimeout(resolveWait, 1_000));- }- } else if (args.command === "status") {- let view = await runtime.inspect(args.file!);- let result: BuildResultManifest | undefined;- let resultReadError: string | undefined;- let openedResults: Awaited<ReturnType<typeof projectResults>> | undefined;- try {- openedResults = await projectResults();- if (args.watch && view !== undefined && view.issue === undefined) {- const startedAt = Date.now();- let delayMs = 100;- let previous: string | undefined;- const controller = await runtimeController(args.runtime);- while (view !== undefined && view.issue === undefined) {- const encoded = JSON.stringify(view);- if (encoded !== previous && !args.json) {- previous = encoded;- io.write(` · ${view.id}: ${view.activity}`- + `${view.operations.length === 0 ? "" : ` · ${view.operations.length} operation(s)`}\n`);- delayMs = 100;- } else {- delayMs = Math.min(1_000, delayMs * 2);- }- const remaining = args.maxWaitMs === undefined- ? undefined- : args.maxWaitMs - (Date.now() - startedAt);- if (remaining !== undefined && remaining <= 0) break;- const worker = await controller.worker.status();- if (worker.state !== "running") break;- await new Promise((resolveWait) => setTimeout(resolveWait,- remaining === undefined ? delayMs : Math.min(delayMs, remaining)));- view = await runtime.inspect(args.file!);- }- }- result = await openedResults.repository.read(args.file!);- } catch (error) {- resultReadError = error instanceof Error ? error.message : String(error);- } finally {- await openedResults?.close();- }- const found = view !== undefined || result !== undefined;- const activity = view?.activity;- const outcome = result?.outcome ?? view?.outcome;- const issue = view?.issue;- 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"- : issue !== undefined- ? "Build needs attention"- : args.watch- ? activity === undefined ? "Build finished" : "Build still active"- : "Build status",- !found- ? "warning"- : issue !== undefined || resultReadError !== undefined- ? "error"- : outcome === "failed"- ? "error"- : args.watch && activity !== undefined ? "warning" : "info", [- ["Build", args.file!],- ...(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.state}`- : `${operation.endpoint}: ${formatOperationProgress(operation.progress)}`)- .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@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 was removed.",- ] : []);- if (!discarded) io.setExitCode?.(1);- return;- }- const before = await runtime.inspect(args.file!);- if (before !== undefined && before.activity !== "saving-result") {- throw new Error(`Build ${args.file} is still ${before.activity}; there is no Result write to finish`);- }- if (before !== undefined && before.issue === undefined) {- const worker = await (await selectedHost.controller()).worker.status();- if (worker.state === "running") {- throw new Error(`Build ${args.file} Result is currently being written by the Runtime Worker`);- }- }- const resultControl = await selectedHost.openResultControl();- const finished = await resultControl.finishResult(args.file!)- .finally(async () => await resultControl.close());- if (finished === undefined) {- 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@2", build: args.file, found: false },- "Build not found", "warning", [["Build", args.file!]]);- io.setExitCode?.(1);- return;- }- 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@2",- build: args.file,- outcome: finished.outcome,- ...(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 ? [] : [`Attention ${finished.issue.message}`]);- if (finished.issue !== undefined) io.setExitCode?.(1);- } else {- const active = await runtime.cancel(args.file!, args.reason);- const openedResults = active === undefined ? await projectResults() : undefined;- 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@3",- requested: active?.cancellationRequested === true,- 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!], ...(build === null ? [] : [["Work", build.work.state] as const]),- ], active === undefined && finished?.outcome !== undefined- ? [`No running work was changed; this Build is already ${finished.outcome}.`]- : []);- if (active === undefined && finished === undefined) io.setExitCode?.(1);- }- } finally {- await runtime.close();- }+ if (isExecutionCommand(args)) {+ await runExecutionCommand({+ args,+ io,+ runtimeHost,+ runtimeController,+ openProjectResults: projectResults,+ write: writeOperational,+ });return;}const runtimePaths = args.runtime === undefined@@ -2095,7 +482,7 @@ export async function runCli(operationLimit: args.limit,});const machine = {- format: "hypit.cli-build@3",+ format: "hypit.cli-build@3" as const,build: args.title === undefined || buildView.title !== undefined? buildView: { ...buildView, title: args.title },diff --git a/packages/cli/src/oauth.ts b/packages/cli/src/oauth.tsnew file mode 100644index 00000000..5c9384c5--- /dev/null+++ b/packages/cli/src/oauth.ts@@ -0,0 +1,115 @@+import { createHash, randomBytes } from "node:crypto";+import { createServer } from "node:http";+import { spawn } from "node:child_process";++import type { CredentialAcquisition } from "@hypit/runtime";++import type { CliIo } from "./output.js";++function base64url(bytes: Uint8Array): string {+ return Buffer.from(bytes).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");+}++/** Acquire one OAuth credential from the exact data declared by its Endpoint package. */+export async function acquireOAuthCredential(+ io: CliIo,+ acquisition: CredentialAcquisition,+): Promise<string> {+ const verifier = base64url(randomBytes(32));+ // S256 is part of OAuth PKCE. It authenticates this browser exchange; it is not content identity.+ const challenge = base64url(createHash("sha256").update(verifier).digest());+ const state = base64url(randomBytes(24));+ const server = createServer();+ const callback = new Promise<string>((resolveCode, reject) => {+ let settled = false;+ server.on("request", (request, response) => {+ if (settled) {+ response.writeHead(204, { "cache-control": "no-store", connection: "close" });+ response.end();+ return;+ }+ try {+ const url = new URL(request.url ?? "/", "http://127.0.0.1");+ if (url.pathname !== "/callback") throw new Error("unexpected OAuth callback path");+ if (url.searchParams.get("state") !== state) throw new Error("OAuth state mismatch");+ const authorizationError = url.searchParams.get("error");+ if (authorizationError !== null) throw new Error(`OAuth authorization failed: ${authorizationError}`);+ const code = url.searchParams.get("code");+ if (code === null || code.length === 0) throw new Error("OAuth callback contained no code");+ response.writeHead(200, {+ "cache-control": "no-store",+ connection: "close",+ "content-type": "text/html; charset=utf-8",+ });+ response.end(callbackPage(true));+ settled = true;+ resolveCode(code);+ } catch (error) {+ response.writeHead(400, {+ "cache-control": "no-store",+ connection: "close",+ "content-type": "text/html; charset=utf-8",+ });+ response.end(callbackPage(false));+ settled = true;+ reject(error);+ } finally {+ server.close();+ server.closeIdleConnections?.();+ }+ });+ server.once("error", reject);+ });+ await new Promise<void>((resolveListen, rejectListen) => {+ server.listen(0, "127.0.0.1", () => resolveListen());+ server.once("error", rejectListen);+ });+ const address = server.address();+ if (address === null || typeof address === "string") throw new Error("could not open a local OAuth callback");+ const redirectUri = `http://127.0.0.1:${address.port}/callback`;+ const authorize = new URL(acquisition.authorizationEndpoint);+ authorize.searchParams.set("response_type", "code");+ authorize.searchParams.set("client_id", acquisition.clientId);+ authorize.searchParams.set("redirect_uri", redirectUri);+ authorize.searchParams.set("scope", acquisition.scopes.join(" "));+ authorize.searchParams.set("state", state);+ authorize.searchParams.set("code_challenge", challenge);+ authorize.searchParams.set("code_challenge_method", "S256");+ io.write(`Opening sign-in: ${authorize}\n`);+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";+ const openerArgs = process.platform === "win32" ? ["/c", "start", "", authorize.toString()] : [authorize.toString()];+ spawn(opener, openerArgs, { stdio: "ignore", detached: true, windowsHide: true }).unref();+ const code = await callback;+ const tokenResponse = await fetch(acquisition.tokenEndpoint, {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ grant_type: "authorization_code",+ code,+ redirect_uri: redirectUri,+ client_id: acquisition.clientId,+ code_verifier: verifier,+ }),+ });+ const body = await tokenResponse.text();+ if (!tokenResponse.ok) throw new Error(`OAuth token exchange failed (${tokenResponse.status}): ${body.slice(0, 200)}`);+ const parsed = JSON.parse(body) as { access_token?: unknown };+ if (typeof parsed.access_token !== "string" || parsed.access_token.length === 0) {+ throw new Error("OAuth token response contained no access token");+ }+ return parsed.access_token;+}++function callbackPage(success: boolean): string {+ const title = success ? "Signed in to Hypit" : "Hypit sign-in failed";+ const heading = success ? "Hypit is signed in" : "Hypit sign-in failed";+ const message = success+ ? "Your credential is ready. You can close this window."+ : "The sign-in could not be completed. You can close this window and try again.";+ const tone = success ? "success" : "error";+ return `<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<meta name="color-scheme" content="dark"><title>${title}</title><style>+:root{color-scheme:dark;font-family:ui-sans-serif,system-ui,sans-serif}*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;color:#f7f2f4;background:#111114}main{width:min(100% - 40px,460px);padding:42px 38px 36px;border:1px solid #3a3036;background:#19171b}.brand{color:#ed98b9;font-weight:700}.mark{margin:34px 0 24px;color:#ed98b9}.mark.error{color:#f08d86}h1{margin:0;font-size:32px}p{color:#bdb3b8;line-height:1.6}+</style></head><body><main><div class="brand">HYPIT</div><div class="mark ${tone}">${success ? "✓" : "×"}</div><h1>${heading}</h1><p>${message}</p></main></body></html>`;+}diff --git a/packages/cli/src/observation.ts b/packages/cli/src/observation.tsnew file mode 100644index 00000000..aea5231f--- /dev/null+++ b/packages/cli/src/observation.ts@@ -0,0 +1,104 @@+import type { BuildResultManifest } from "@hypit/build-result";++import type { CliBuildSubmission, CliBuildView, CliRuntimeControl, CliRuntimeController } from "./runtime-port.js";+import { formatOperationProgress } from "./runtime-view.js";++export type BuildProgressView = {+ readonly build: string;+ readonly phase: string;+ readonly operations: Readonly<Record<string, number>>;+ readonly activity: readonly string[];+};++function operationCounts(view: CliBuildView): Readonly<Record<string, number>> {+ return Object.fromEntries([...new Set(view.operations.map((item) => item.status))]+ .sort().map((state) => [state, view.operations.filter((item) => item.status === state).length]));+}++/** Stable product-state projection for watch output and polling backoff. */+export function buildObservationKey(view: CliBuildView): string {+ return JSON.stringify({+ phase: view.activity,+ outcome: view.outcome,+ issue: view.issue,+ cancellationRequested: view.cancellationRequested,+ operations: operationCounts(view),+ });+}++/** Observe one submitted Build. This reads accepted state only and never performs execution work. */+export async function observeBuild(+ runtime: Pick<CliRuntimeControl, "inspect">,+ initial: CliBuildSubmission,+ options: {+ readonly maxWaitMs?: number;+ readonly controller?: CliRuntimeController;+ readonly readResult: () => Promise<BuildResultManifest | undefined>;+ readonly onProgress?: (value: BuildProgressView) => void;+ },+): Promise<CliBuildSubmission> {+ let current = initial;+ let lastProgress: string | undefined;+ let pollDelayMs = 100;+ let observedActivity = false;+ const startedAt = Date.now();+ const finishFromResult = async (): Promise<CliBuildSubmission> => {+ const result = await options.readResult();+ if (result?.outcome === undefined) {+ throw new Error(`Build ${current.id} left active Runtime state without a finished Result`);+ }+ return {+ id: current.id,+ state: current.state,+ completion: {+ build: current.id,+ outcome: result.outcome,+ ...(result.failure === undefined ? {} : { reason: result.failure }),+ },+ };+ };+ while ("view" in current && current.view.issue === undefined) {+ const elapsedMs = Date.now() - startedAt;+ const remainingMs = options.maxWaitMs === undefined ? undefined : options.maxWaitMs - elapsedMs;+ if (remainingMs !== undefined && remainingMs <= 0) break;+ const waitMs = remainingMs === undefined ? pollDelayMs : Math.min(pollDelayMs, remainingMs);+ await new Promise((resolveWait) => setTimeout(resolveWait, waitMs));+ const view = await runtime.inspect(current.id);+ observedActivity = true;+ if (view === undefined) {+ current = await finishFromResult();+ break;+ }+ current = { id: current.id, state: current.state, view };+ if (current.view.issue === undefined && options.controller !== undefined) {+ const worker = await options.controller.worker.status();+ if (worker.state !== "running") {+ throw new Error(+ `Runtime Worker is ${worker.state}; Build ${current.id} remains durable. `+ + `Run hypit runtime up, then run hypit status ${current.id} --watch again`,+ );+ }+ }+ const operations = operationCounts(view);+ const activity = view.operations+ .filter((item) => item.status === "pending")+ .map((item) => `${item.endpoint}: ${item.progress === undefined+ ? item.status+ : formatOperationProgress(item.progress)}`);+ // Default observation reacts to product state, not every raw Provider progress detail.+ const nextProgress = buildObservationKey(view);+ if (nextProgress !== lastProgress) {+ lastProgress = nextProgress;+ pollDelayMs = 100;+ options.onProgress?.({ build: current.id, phase: view.activity, operations, activity });+ } else {+ pollDelayMs = Math.min(1_000, pollDelayMs * 2);+ }+ }+ if (observedActivity && "view" in current) {+ const view = await runtime.inspect(current.id);+ if (view === undefined) return await finishFromResult();+ current = { id: current.id, state: current.state, view };+ }+ return current;+}diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex 7e6abd1c..8f9574ae 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -1,5 +1,7 @@import { relative, resolve } from "node:path";+import type { OperationalMachineView } from "./machine-view.js";+export type CliTerminal = {readonly isTTY: boolean;readonly color: boolean;@@ -33,9 +35,10 @@ export type CliDiagnostic = {};export type DoctorOutput = {- readonly format: "hypit.cli-doctor@2";+ readonly format: "hypit.cli-doctor@3";readonly ok: boolean;- readonly profile: string;+ readonly project: string;+ readonly profile?: string;readonly diagnosticCount: number;readonly diagnostics: readonly CliDiagnostic[];readonly omittedDiagnostics?: number;@@ -110,7 +113,7 @@ export type PlanOutput = {readonly preflight?: PlanPreflight;};-export type CliMachineView = Readonly<Record<string, unknown>>;+export type CliMachineView = OperationalMachineView;export type CliPresentation =| {@@ -196,7 +199,8 @@ function heading(status: "success" | "warning" | "error" | "info", text: string,function renderDoctor(view: Extract<CliPresentation, { kind: "doctor" }>, io: CliIo, colors: Palette): string {const lines = [colors.accent(colors.strong("Hypit Doctor")), ""];lines.push(...facts([- ["Profile", shortPath(view.machine.profile)],+ ["Project", shortPath(view.machine.project)],+ ...(view.machine.profile === undefined ? [] : [["Profile", shortPath(view.machine.profile)] as const]),], colors));lines.push("");if (view.machine.diagnostics.length === 0) {@@ -239,19 +243,17 @@ function renderAuthorCheck(if (readable.length > 0) {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) {+ const width = Math.max(...ordered.map((item) => item.name.length));+ for (const item of ordered) {lines.push(` ${colors.accent(item.name.padEnd(width))} ${item.type}`);}- 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 ((view.machine.omittedOutputs ?? 0) > 0) {+ lines.push(` ${colors.dim(`${view.machine.omittedOutputs} 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)) {+ for (const item of view.machine.details.values) {lines.push(` ${colors.accent(item.name)} ${item.type}`);}}@@ -403,10 +405,10 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi],doctor: [colors.accent(colors.strong("hypit doctor")),- colors.dim("Diagnose one complete declarative Runtime Profile without submitting work."),+ colors.dim("Diagnose project Results and, when selected or supplied, one Runtime Profile."),""," hypit doctor [<runtime-profile>] [--workspace <project>]",- " Checks the Runtime deployment and the project's selected Result Store.",+ " Without a Runtime Profile, checks only the project's selected Result Store.",],plan: [colors.accent(colors.strong("hypit plan")),@@ -431,8 +433,8 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.accent(colors.strong("hypit runtime")),colors.dim("Select a project Runtime Profile, then operate its durable Worker."),"",- " hypit runtime use <profile> select the Profile for this project",- " hypit runtime unset remove only the local selection",+ " hypit runtime use <profile> [--workspace <project>] select the project Profile",+ " hypit runtime unset [--workspace <project>] remove only that 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>] [--lines <count>]",@@ -500,7 +502,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi],history: [colors.accent(colors.strong("hypit history")),- colors.dim("Find project Build Outputs from local result manifests."),+ colors.dim("Find one named Output across project-owned Build Results."),""," hypit history <output-name> [--workspace <project>] [--source <author-source>] [--limit <count>] [--before <build-id>]",],diff --git a/packages/cli/src/project-context.ts b/packages/cli/src/project-context.tsnew file mode 100644index 00000000..7fd2b2c7--- /dev/null+++ b/packages/cli/src/project-context.ts@@ -0,0 +1,22 @@+import { stat } from "node:fs/promises";+import { dirname, resolve } from "node:path";++async function nearestProjectPackageRoot(start: string): Promise<string | undefined> {+ let directory = resolve(start);+ while (true) {+ const candidate = resolve(directory, "package.json");+ try {+ if ((await stat(candidate)).isFile()) return directory;+ } catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;+ }+ const parent = dirname(directory);+ if (parent === directory) return undefined;+ directory = parent;+ }+}++/** Resolve package discovery independently from project-owned Result storage. */+export async function resolvePackageRoot(projectStart: string): Promise<string> {+ return await nearestProjectPackageRoot(projectStart) ?? resolve(projectStart);+}diff --git a/packages/cli/src/result-query.ts b/packages/cli/src/result-query.tsnew file mode 100644index 00000000..83dc7f50--- /dev/null+++ b/packages/cli/src/result-query.ts@@ -0,0 +1,46 @@+import { resolve } from "node:path";++import type { BuildResultRepository, FinishedBuildResultManifest } from "@hypit/build-result";++export type BuildOutputHistoryPage = {+ readonly results: readonly FinishedBuildResultManifest[];+ /** Read older Builds strictly before this id. */+ readonly next?: string;+};++/**+ * Collect a page of matching Outputs rather than filtering one arbitrary page of Builds. This is a+ * request-local scan over the Repository's own chronological cursor; it creates no index or history.+ */+export async function browseBuildOutputHistory(+ repository: BuildResultRepository,+ request: {+ readonly projectRoot: string;+ readonly output: string;+ readonly source?: string;+ readonly before?: string;+ readonly limit: number;+ },+): Promise<BuildOutputHistoryPage> {+ const source = request.source === undefined ? undefined : resolve(request.source);+ const pageSize = Math.max(32, request.limit);+ let before = request.before;+ const matches: FinishedBuildResultManifest[] = [];+ while (matches.length < request.limit) {+ const page = await repository.browse({ limit: pageSize, ...(before === undefined ? {} : { before }) });+ if (page.results.length === 0) return { results: matches };+ for (let index = 0; index < page.results.length; index += 1) {+ const manifest = page.results[index]!;+ const sameSource = source === undefined+ || resolve(request.projectRoot, manifest.source.path) === source;+ if (sameSource && manifest.outputs[request.output] !== undefined) matches.push(manifest);+ if (matches.length === request.limit) {+ const hasOlder = index < page.results.length - 1 || page.next !== undefined;+ return { results: matches, ...(hasOlder ? { next: manifest.id } : {}) };+ }+ }+ if (page.next === undefined) return { results: matches };+ before = page.next;+ }+ return { results: matches };+}diff --git a/packages/cli/src/runtime-view.ts b/packages/cli/src/runtime-view.tsnew file mode 100644index 00000000..fb5cb36f--- /dev/null+++ b/packages/cli/src/runtime-view.ts@@ -0,0 +1,51 @@+import type { CapacityReservation, OperationProgress } from "@hypit/runtime";++export type QueueLaneSummary = {+ readonly pool: string;+ readonly lane: string;+ readonly inFlight: number;+};++export function formatOperationProgress(progress: OperationProgress): string {+ if (progress.completed === undefined) return progress.phase;+ const amount = progress.total === undefined+ ? String(progress.completed)+ : `${progress.completed}/${progress.total}`;+ return `${progress.phase} · ${amount}${progress.unit === undefined ? "" : ` ${progress.unit}`}`;+}++/** Derive the Provider → capability view from generic capacity tickets. */+export function summarizeQueueLanes(capacity: readonly CapacityReservation[]): readonly QueueLaneSummary[] {+ const groups = new Map<string, QueueLaneSummary>();+ for (const ticket of capacity) {+ if (ticket.queue === undefined) continue;+ const key = `${ticket.queue.pool}\u0000${ticket.queue.lane}`;+ const previous = groups.get(key);+ groups.set(key, {+ pool: ticket.queue.pool,+ lane: ticket.queue.lane,+ inFlight: (previous?.inFlight ?? 0) + 1,+ });+ }+ return [...groups.values()].sort((left, right) =>+ left.pool.localeCompare(right.pool) || left.lane.localeCompare(right.lane));+}++export function queueLaneLines(groups: readonly QueueLaneSummary[]): readonly string[] {+ const lines: string[] = [];+ let pool: string | undefined;+ for (const group of groups) {+ if (group.pool !== pool) {+ pool = group.pool;+ lines.push(pool);+ }+ lines.push(` ${group.lane}: ${group.inFlight} remote`);+ }+ return lines;+}++export function inlineValuePreview(value: unknown, limit = 240): string {+ const encoded = JSON.stringify(value);+ if (encoded.length <= limit) return encoded;+ return `${encoded.slice(0, Math.max(0, limit - 3))}...`;+}diff --git a/packages/cli/src/view.ts b/packages/cli/src/view.tsindex d92ac1af..2f89da39 100644--- a/packages/cli/src/view.ts+++ b/packages/cli/src/view.ts@@ -3,7 +3,7 @@ import { isAbsolute, relative, resolve, sep } from "node:path";import type {BuildResultManifest,BuildResultRepository,- RepositoryBuildResultOutput,+ RepositoryBuildResultOutputDescription,} from "@hypit/build-result";import { buildIdCreatedAt } from "@hypit/protocol";import type { TypeRef } from "@hypit/protocol";@@ -17,6 +17,8 @@ export type CliOutputView = {readonly kind: PublicOutputKind;readonly target: boolean;readonly highlighted: boolean;+ readonly mediaType?: string;+ readonly size?: number;};export type CliBuildSummary = {@@ -92,27 +94,25 @@ export function buildCreatedAtIso(build: string): string {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);+ const output = await repository.describeOutput(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),+ kind: output.kind,target: manifest.targets.includes(name),highlighted: manifest.highlightedOutputs?.includes(name) === true,+ ...(output.kind === "resource" ? {+ mediaType: output.mediaType,+ size: output.size,+ } : {}),};}diff --git a/packages/cli/test/build-programs.test.ts b/packages/cli/test/build-programs.test.tsindex 79dca4f9..22a1eb28 100644--- a/packages/cli/test/build-programs.test.ts+++ b/packages/cli/test/build-programs.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";+import { FileBuildResultRepository } from "@hypit/build-result";import { createRunFrontendHostFacet } from "@hypit/run";import { runCli } from "../src/main.js";@@ -88,6 +89,15 @@ function distribution(}),extendExecutionProgram: (program: unknown) => program,}),+ openProjectResults: async (projectRoot: string) => ({+ location: {+ root: projectRoot,+ selection: { use: "test.results", config: {} },+ },+ repository: new FileBuildResultRepository(join(projectRoot, ".hypit", "results")),+ close() {},+ }),+ diagnoseProjectResults: async () => ({ diagnostics: [] }),openRuntimeHost: async (path: string) => ({profile: path,resolvePaths: async () => ({}),diff --git a/packages/cli/test/build-results.test.ts b/packages/cli/test/build-results.test.tsindex 5dbe1d1e..8dc35626 100644--- a/packages/cli/test/build-results.test.ts+++ b/packages/cli/test/build-results.test.ts@@ -35,8 +35,8 @@ async function fixture(root: string): Promise<void> {const result = await FileBuildResult.create(join(root, ".hypit", "results"), {id: "bld_20260902T110000000Z_0000000001",title: "episode-stage",- source: { path: join(root, "main.svml") },- run: { path: join(root, "build.svrun") },+ source: { path: "main.svml" },+ run: { path: "build.svrun" },targets: ["stage.value"],publishedOutputs: [{ name: "stage.value", output: "logical:stage" }],});@@ -47,11 +47,27 @@ async function fixture(root: string): Promise<void> {await result.finish({ outcome: "complete" });}+function resultDistribution(): CliDistribution {+ return {+ async openProjectResults(projectRoot: string) {+ return {+ location: {+ root: projectRoot,+ selection: { use: "test.results", config: {} },+ },+ repository: new FileBuildResultRepository(join(projectRoot, ".hypit", "results")),+ close() {},+ };+ },+ async diagnoseProjectResults() { return { diagnostics: [] }; },+ } as unknown as CliDistribution;+}+async function jsonCommand(args: readonly string[], root: string): Promise<unknown> {let output = "";await runCli([...args, "--workspace", root, "--json"], {write(text) { output += text; },- }, {} as CliDistribution);+ }, resultDistribution());return JSON.parse(output);}@@ -110,6 +126,37 @@ test("builds, history, inspect and get read project Build Results without openin}});+test("history scans older pages for matches and compares project-relative source paths", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-cli-history-"));+ try {+ await fixture(root);+ const repository = new FileBuildResultRepository(join(root, ".hypit", "results"));+ for (const id of [+ "bld_20260902T110000001Z_0000000001",+ "bld_20260902T110000002Z_0000000001",+ ]) {+ const writer = await repository.create({+ id,+ source: { path: "other.svml" },+ targets: [],+ publishedOutputs: [],+ });+ await writer.finish({ outcome: "failed", failure: "fixture without the requested Output" });+ }++ const history = await jsonCommand([+ "history", "stage.value", "--source", join(root, "main.svml"), "--limit", "1",+ ], root) as {+ readonly source: string;+ readonly entries: readonly { readonly build: string }[];+ };+ assert.equal(history.source, "main.svml");+ assert.deepEqual(history.entries.map((item) => item.build), ["bld_20260902T110000000Z_0000000001"]);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});+test("get exports Resource bytes and a self-contained Composite directory", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-cli-get-"));const build = "bld_20260902T110000010Z_0000000001";@@ -202,22 +249,22 @@ test("get requires an exact Output name and an explicit destination", async () =try {const silent = { write() {} };await assert.rejects(- runCli(["get", "bld_20260902T110000000Z_0000000001", "--workspace", root], silent, {} as CliDistribution),+ runCli(["get", "bld_20260902T110000000Z_0000000001", "--workspace", root], silent, resultDistribution()),/get requires --output/u,);await assert.rejects(runCli(["get", "bld_20260902T110000000Z_0000000001", "--output", "stage.value", "--workspace", root,- ], silent, {} as CliDistribution),+ ], silent, resultDistribution()),/get requires --to/u,);await assert.rejects(runCli(["history", "--source", join(root, "main.svml"), "--workspace", root], silent,- {} as CliDistribution),+ resultDistribution()),/history requires one exact Output name/u,);await assert.rejects(- runCli(["history", "stage.value", "--pin", "--workspace", root], silent, {} as CliDistribution),+ runCli(["history", "stage.value", "--pin", "--workspace", root], silent, resultDistribution()),/unknown option --pin/u,);} finally {diff --git a/packages/cli/test/control-commands.test.ts b/packages/cli/test/control-commands.test.tsindex 9c8792af..eecb3652 100644--- a/packages/cli/test/control-commands.test.ts+++ b/packages/cli/test/control-commands.test.ts@@ -279,7 +279,7 @@ test("result discard invokes only the exact one-shot Result control", async () ="result", "discard", "build-submitting", "--runtime", "/tmp/runtime.json", "--json",], { write: (text) => { output += text; } }, distribution);- assert.deepEqual(calls, ["discard:build-submitting", "result-control.close", "control.close"]);+ assert.deepEqual(calls, ["discard:build-submitting", "result-control.close"]);assert.deepEqual(JSON.parse(output), {format: "hypit.cli-result-discard@2", build: "build-submitting", discarded: true,});@@ -318,6 +318,32 @@ test("command options fail closed instead of being silently ignored", async () =);});+test("doctor diagnoses project Results without requiring a Runtime Profile", async () => {+ const calls: string[] = [];+ const distribution = {+ async diagnoseProjectResults(projectRoot: string) {+ calls.push(`results:${projectRoot}`);+ return { diagnostics: [] };+ },+ async openRuntimeHost() {+ calls.push("runtime");+ throw new Error("doctor without a Profile must not open a Runtime");+ },+ } as unknown as CliDistribution;+ let output = "";+ await runCli(["doctor", "--workspace", "/tmp/hypit-project", "--json"], {+ write(text) { output += text; },+ }, distribution);+ assert.deepEqual(calls, ["results:/tmp/hypit-project"]);+ assert.deepEqual(JSON.parse(output), {+ format: "hypit.cli-doctor@3",+ ok: true,+ project: "/tmp/hypit-project",+ diagnosticCount: 0,+ diagnostics: [],+ });+});+test("auth opens only one Endpoint credential control, never the execution Runtime", async () => {const calls: string[] = [];const credentials = {diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.tsindex 494c8e3c..11eb8b85 100644--- a/packages/cli/test/output.test.ts+++ b/packages/cli/test/output.test.ts@@ -37,8 +37,9 @@ test("author check exposes author-facing Outputs, not graph or resource identititest("JSON mode writes exactly the stable command view", () => {const machine = {- format: "hypit.cli-doctor@2" as const,+ format: "hypit.cli-doctor@3" as const,ok: false,+ project: "/project",profile: "/project/hypit.runtime.ts",diagnosticCount: 1,diagnostics: [{ severity: "error" as const, code: "MISSING", message: "not found" }],diff --git a/packages/cli/test/runtime-selection.test.ts b/packages/cli/test/runtime-selection.test.tsindex 0900ce1b..83c470b5 100644--- a/packages/cli/test/runtime-selection.test.ts+++ b/packages/cli/test/runtime-selection.test.ts@@ -58,10 +58,10 @@ test("runtime use lets later CLI commands reuse the selected Profile", async ()} as unknown as CliDistribution;process.chdir(root);- await runCli(["runtime", "use", profile, "--json"], { write() {} }, distribution);+ await runCli(["runtime", "use", profile, "--workspace", root, "--json"], { write() {} }, distribution);await runCli(["activity", "--json"], { write() {} }, distribution);await runCli(["activity", "--runtime", otherProfile, "--json"], { write() {} }, distribution);- await runCli(["runtime", "unset", "--json"], { write() {} }, distribution);+ await runCli(["runtime", "unset", "--workspace", root, "--json"], { write() {} }, distribution);assert.deepEqual(calls, [`activity:${await realpath(profile)}`,diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.tsindex 2c058b1e..a3a87f03 100644--- a/packages/endpoint-kit/src/index.ts+++ b/packages/endpoint-kit/src/index.ts@@ -9,6 +9,7 @@ import type {} from "@hypit/protocol";import type {ResourceStore,+ CredentialAcquisition,CredentialRef,CredentialValue,OperationFailure,@@ -131,6 +132,7 @@ export type EndpointCredentialDescription = {readonly label: string;readonly kind: "secret" | "json";readonly ref: CredentialRef;+ readonly acquisition?: CredentialAcquisition;};type EndpointCapabilityBase = {@@ -165,6 +167,7 @@ export type DefineEndpointPackageOptions = {readonly credentialInputs?: Readonly<Record<string, {readonly label: string;readonly kind?: "secret" | "json";+ readonly acquisition?: CredentialAcquisition;}>>;/** Total capacity shared by every lane under this configured Provider pool. */readonly defaultConcurrency?: number;@@ -231,6 +234,7 @@ export function defineEndpointPackage(options: DefineEndpointPackageOptions): Enlabel,kind,ref: structuredClone(ref),+ ...(input?.acquisition === undefined ? {} : { acquisition: structuredClone(input.acquisition) }),} satisfies EndpointCredentialDescription;});const fulfills = options.capabilities.map((item) => ({diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.tsindex b275283c..faf43a41 100644--- a/packages/provider-hypihub/src/provider.ts+++ b/packages/provider-hypihub/src/provider.ts@@ -252,7 +252,18 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}};return defineEndpointPackage({module: hypiHubProviderModuleRef, facet: "gateway", instance: options.instance ?? "hypihub.default", pool: options.pool ?? options.instance ?? "hypihub.default",- credentials: { apiKey: options.apiKey ?? credentialRef("os", "hypihub.oauth") }, credentialInputs: { apiKey: { label: "HypiHub login" } }, defaultConcurrency: options.defaultConcurrency ?? 3,+ credentials: { apiKey: options.apiKey ?? credentialRef("os", "hypihub.oauth") },+ credentialInputs: { apiKey: {+ label: "HypiHub login",+ acquisition: {+ kind: "oauth2-pkce",+ authorizationEndpoint: "https://hypit.ai/oauth/consent",+ tokenEndpoint: "https://hypit.ai/oauth/token",+ clientId: "hyc_d5d5e8e7131b0c877756e66c",+ scopes: ["user:profile", "user:inference"],+ },+ } },+ defaultConcurrency: options.defaultConcurrency ?? 4,capabilities: [...hypiHubRoutes.filter((route) => options.audio !== false || route.media !== "audio")diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.tsindex 4df01367..2ffbc64a 100644--- a/packages/provider-hypihub/test/provider.test.ts+++ b/packages/provider-hypihub/test/provider.test.ts@@ -30,6 +30,13 @@ async function endpointFor(request: Need, fetch: typeof globalThis.fetch): Promireturn resolution.registration.endpoint;}+test("HypiHub declares its own credential acquisition flow", () => {+ const [credential] = createHypiHubProvider().credentials;+ assert.equal(credential?.acquisition?.kind, "oauth2-pkce");+ assert.equal(credential?.acquisition?.authorizationEndpoint, "https://hypit.ai/oauth/consent");+ assert.equal(credential?.acquisition?.tokenEndpoint, "https://hypit.ai/oauth/token");+});+test("HypiHub exposes VoiceDesign by default and permits an explicit alternate audio Provider", async () => {const registry = new EndpointRegistry();await createHypiHubProvider({ fetch: async () => { throw new Error("audio must not call fetch"); } }).install(registry);diff --git a/packages/runtime-host-node/src/index.ts b/packages/runtime-host-node/src/index.tsindex 44f6ac7f..5d5e8bfd 100644--- a/packages/runtime-host-node/src/index.ts+++ b/packages/runtime-host-node/src/index.ts@@ -10,6 +10,7 @@ import type {BuildCatalogDescriptor,BuildCompletion,CapacityReservation,+ CredentialAcquisition,CredentialRef,OperationSnapshot,RuntimeWorkerRunOptions,@@ -61,6 +62,7 @@ export type RuntimeHostCredentialStatus = {readonly label: string;readonly kind: "secret" | "json";readonly ref: CredentialRef;+ readonly acquisition?: CredentialAcquisition;readonly configured: boolean;readonly writable: boolean;};diff --git a/packages/runtime-local/test/local.test.ts b/packages/runtime-local/test/local.test.tsindex 05df30e4..ee378b60 100644--- a/packages/runtime-local/test/local.test.ts+++ b/packages/runtime-local/test/local.test.ts@@ -497,6 +497,7 @@ test("an interrupted Result write finishes explicitly without rerunning the Builread: async (build) => await base.read(build),updatePresentation: async (build, update) => await base.updatePresentation(build, update),browse: async (request) => await base.browse(request),+ describeOutput: async (build, output) => await base.describeOutput(build, output),resolve: async (build, output) => await base.resolve(build, output),openFile: async (build, file) => await base.openFile(build, file),};@@ -545,6 +546,7 @@ test("a failed Result creation leaves no active Build", async () => {async read() { return undefined; },async updatePresentation() { throw new Error("result repository refused update"); },async browse() { return { results: [] }; },+ async describeOutput() { return undefined; },async resolve() { return undefined; },async openFile() { return undefined; },};diff --git a/packages/runtime/src/credentials.ts b/packages/runtime/src/credentials.tsindex d3f7b242..1c46bbe0 100644--- a/packages/runtime/src/credentials.ts+++ b/packages/runtime/src/credentials.ts@@ -11,6 +11,15 @@ export type CredentialValue = {readonly expiresAt?: number;};+/** Host-facing way to acquire one credential; Provider-specific values stay in its Endpoint package. */+export type CredentialAcquisition = {+ readonly kind: "oauth2-pkce";+ readonly authorizationEndpoint: string;+ readonly tokenEndpoint: string;+ readonly clientId: string;+ readonly scopes: readonly string[];+};+export type CredentialStore = {resolve(ref: CredentialRef): Promise<CredentialValue | undefined>;};diff --git a/packages/studio/test/build-library.test.ts b/packages/studio/test/build-library.test.tsindex 86a14c35..e8396784 100644--- a/packages/studio/test/build-library.test.ts+++ b/packages/studio/test/build-library.test.ts@@ -50,6 +50,16 @@ test("Studio library joins this environment's Builds with project Build Result fasync updatePresentation() { throw new Error("read-only fixture"); },async read(build) { return manifests.find((item) => item.id === build); },async browse() { return { results: manifests }; },+ async describeOutput(build, output) {+ const manifest = manifests.find((item) => item.id === build);+ const value = manifest?.outputs[output as "final.video"];+ return value === undefined ? undefined : {+ type: value.type,+ kind: "resource",+ size: value.value.size,+ mediaType: value.value.mediaType,+ };+ },async resolve(build, output) {const manifest = manifests.find((item) => item.id === build);const value = manifest?.outputs[output as "final.video"];