The Open Standard for Generative UI
Refactor CLI (#1174)
ABac1176a7fcfa
diff --git a/.changeset/cli-catalog-keys.md b/.changeset/cli-catalog-keys.mdnew file mode 100644index 000000000..320533830--- /dev/null+++ b/.changeset/cli-catalog-keys.md@@ -0,0 +1,7 @@+---+"@openuidev/cli": minor+---++Internal restructure of the CLI: each command is a folder, shared process state is a `CliContext` passed top-down, and telemetry is a `Telemetry` class with typed per-command methods.++`openui create --help` loads template and backend-framework names from the catalog (bundled keys if the fetch fails). `--template` and `--backend-framework` accept catalog keys only (`openui-cloud`, `openui-self-hosted`, `default`, `langgraph`, `vercel-ai-sdk`, `vercel-eve`); short names like `cloud` and `eve` no longer resolve. `--verbose` is a global flag, so it works before or after the command.diff --git a/.gitignore b/.gitignoreindex 51fd674d0..7e4d0234d 100644--- a/.gitignore+++ b/.gitignore@@ -62,3 +62,6 @@ draft/# Local raw-asset drop folder (copied into docs/public to serve)/assets/++# Accidental CLI template checkouts+packages/openui-cli/src/templates/diff --git a/packages/openui-cli/src/commands/create-app.ts b/packages/openui-cli/src/commands/create-app.tsdeleted file mode 100644index 875666713..000000000--- a/packages/openui-cli/src/commands/create-app.ts+++ /dev/null@@ -1,897 +0,0 @@-import * as fs from "node:fs";-import * as os from "node:os";-import * as path from "node:path";--import { resolveCloudApiKey, THESYS_KEYS_URL } from "../auth/mint";-import { printLogTail, QUIET_COMMAND_CAPTURE_LIMIT } from "../lib/command-output";-import { aiSetupFromTemplate, createFunnelProps } from "../lib/create-telemetry";-import type { CreateAppOptions, EnvResult, OverlayName, TemplateName } from "../lib/create-types";-import {- resolveInstallPackageManager,- type PackageManagerName,-} from "../lib/detect-package-manager";-import { runDevCommand } from "../lib/dev-server";-import {- findExample,- groupedExampleChoices,- loadExamplesCatalog,- rejectConflictingScaffoldSelectors,- type ExampleProject,-} from "../lib/examples-catalog";-import { runSkillInstall, shouldInstallSkill } from "../lib/install-skill";-import {- applyOverlay,- OVERLAYS_DIR,- resolveOverlay,- type OverlayManifest,- type TemplateOverlay,-} from "../lib/overlays";-import { mutedNpmEnv, runCommand } from "../lib/process-runner";-import { resolveArgs } from "../lib/resolve-args";-import { resolveTemplateSource } from "../lib/scaffold-template";-import { withSpinner } from "../lib/spinner";-import { resolveAvailableTarget } from "../lib/target-dir";-import { CliCancelledError, CreateError, telemetry } from "../lib/telemetry";-import {- DEFAULT_TEMPLATE_KEY,- findCatalogOverlay,- findCatalogTemplate,- loadTemplatesCatalog,- type CatalogOverlay,- type CatalogTemplate,-} from "../lib/templates-catalog";-import { cliErrorProperties, processErrorProperties } from "../lib/utils";--import { runCreateExample } from "./create-example";--function shouldCopyTemplatePath(templateDir: string, src: string): boolean {- const rel = path.relative(templateDir, src);- if (!rel) return true;- const top = rel.split(path.sep)[0] ?? "";- // Copy the base template only; selected backend overlays are applied later.- // Also exclude install/build artifacts that may sit in a template directory.- return ![OVERLAYS_DIR, "node_modules", ".next", ".turbo", "dist"].includes(top);-}--function restoreDotfiles(projectDir: string) {- // Templates ship `gitignore` un-dotted: npm silently strips `.gitignore`- // files (at any depth) from published packages, so a dotted copy never- // reaches the scaffold — and freshly created apps would commit `.env`.- // Restore the real name here instead.- const plain = path.join(projectDir, "gitignore");- if (fs.existsSync(plain)) {- fs.renameSync(plain, path.join(projectDir, ".gitignore"));- }-}--function buildAppId(name: string): string {- // Stable per-scaffold identity (see writeEnv). Slugified because the name is- // free-form and APP_ID lands in .env and ?app_id= query params; the random- // suffix keeps two same-named apps in one org from colliding.- const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");- return `${slug}-${Math.random().toString(36).slice(2, 8)}`;-}--function requiredApiKeyEnv(template: TemplateName): "THESYS_API_KEY" | "OPENAI_API_KEY" {- return template === "openui-cloud" ? "THESYS_API_KEY" : "OPENAI_API_KEY";-}--/** Match npm/pnpm install: keep dependency keys alphabetically sorted. */-function sortPackageRecord<T>(record: Record<string, T>): Record<string, T> {- return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));-}--function rewritePackageJson(- projectDir: string,- name: string,- packageManager: PackageManagerName,- overlayPackageJson?: OverlayManifest["packageJson"],-) {- // package.json: set the project name and de-vendor monorepo-local deps- // (workspace:* / file: / catalog:) to the published "latest". link: deps are- // rewritten to an absolute file: path so locally-linked packages (e.g.- // @openuidev/thesys) keep resolving against the developer's checkout under any- // package manager — npm rejects link:, and ~ isn't expanded. Temporary, until- // these packages are published.- const pkgPath = path.join(projectDir, "package.json");- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8")) as {- name: string;- scripts?: Record<string, string>;- dependencies?: Record<string, string>;- devDependencies?: Record<string, string>;- pnpm?: unknown;- };- pkg.name = name;- if (packageManager !== "pnpm") delete pkg.pnpm;-- if (overlayPackageJson) {- pkg.dependencies ??= {};- for (const dependency of overlayPackageJson.removeDependencies ?? []) {- delete pkg.dependencies[dependency];- }- Object.assign(pkg.dependencies, overlayPackageJson.dependencies ?? {});- Object.assign((pkg.devDependencies ??= {}), overlayPackageJson.devDependencies ?? {});- Object.assign((pkg.scripts ??= {}), overlayPackageJson.scripts ?? {});- }-- for (const section of ["dependencies", "devDependencies"] as const) {- const deps = pkg[section];- if (!deps) continue;- for (const key of Object.keys(deps)) {- const v = deps[key];- if (!v) continue;- if (v.startsWith("link:")) {- const target = v.slice("link:".length);- const abs = target.startsWith("~")- ? path.join(os.homedir(), target.slice(1))- : path.resolve(target);- deps[key] = `file:${abs}`;- continue;- }- // workspace:/file:/catalog: are monorepo-only protocols npm/yarn/bun- // can't resolve standalone — pin them to the published "latest".- if (/^(workspace:|file:|catalog:)/.test(v)) deps[key] = "latest";- }- // Object.assign appends overlay packages at the end; re-sort so the- // scaffolded package.json matches what `npm install` / `pnpm add` write.- pkg[section] = sortPackageRecord(deps);- }- fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");-- // Keep the copied npm lockfile's root package metadata aligned so npm ci can- // consume the template without having to rewrite or re-resolve it.- const lockPath = path.join(projectDir, "package-lock.json");- if (fs.existsSync(lockPath)) {- const lock = JSON.parse(fs.readFileSync(lockPath, "utf8")) as {- name?: string;- packages?: Record<- string,- {- name?: string;- dependencies?: Record<string, string>;- devDependencies?: Record<string, string>;- }- >;- };- lock.name = name;- const lockRoot = lock.packages?.[""];- if (lockRoot) {- lockRoot.name = name;- lockRoot.dependencies = pkg.dependencies;- lockRoot.devDependencies = pkg.devDependencies;- }- fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + "\n");- }-}--export async function runCreateApp(options: CreateAppOptions): Promise<void> {- const interactive = !options.noInteractive;- const packageManager = resolveInstallPackageManager();- const t0 = Date.now();- telemetry.register({ interactive, package_manager: packageManager.name });- telemetry.capture("cli_create_started", {- ...createFunnelProps("create_started"),- interactive,- has_name_arg: Boolean(options.name),- has_template_arg: Boolean(options.template),- has_backend_framework_arg: Boolean(options.backendFramework),- has_example_arg: Boolean(options.example),- has_api_key_arg: Boolean(options.apiKey),- has_auth_arg: Boolean(options.auth),- no_install: Boolean(options.noInstall),- immediate_arg: options.immediate,- });-- rejectConflictingScaffoldSelectors({- example: options.example,- backendFramework: options.backendFramework,- template: options.template,- });-- // Interactive runs always scaffold the Cloud backend; openui-self-hosted stays- // available, but only when requested explicitly with --template.- if (!interactive && !options.example && !options.template) {- throw new CreateError(- "args_resolution",- "Missing required argument --template",- "invalid_input",- "MISSING_REQUIRED_ARG",- );- }-- let examples: ExampleProject[] = [];- let template: TemplateName | undefined;- let templateEntry: CatalogTemplate | undefined;- if (options.example) {- examples = await loadExamplesCatalog();- findExample(options.example, examples);- } else if (interactive) {- const [catalog, loadedExamples] = await Promise.all([- loadTemplatesCatalog(),- loadExamplesCatalog(),- ]);- examples = loadedExamples;- template = options.template ?? DEFAULT_TEMPLATE_KEY;- templateEntry = findCatalogTemplate(catalog, template);- if (options.backendFramework) {- findCatalogOverlay(templateEntry, options.backendFramework);- }- } else {- const catalog = await loadTemplatesCatalog();- template = options.template ?? DEFAULT_TEMPLATE_KEY;- templateEntry = findCatalogTemplate(catalog, template);- if (options.backendFramework) {- findCatalogOverlay(templateEntry, options.backendFramework);- }- }-- const nameArgs = await resolveArgs(- {- name: options.name- ? { value: options.name }- : {- prompt: { type: "input", message: "Project name?", default: "openui-agent" },- required: true,- },- },- interactive,- );- const { name, targetDir } = await resolveAvailableTarget(- (nameArgs as { name: string }).name,- interactive,- );-- const selected = await resolveCreateSelection({- backendFramework: options.backendFramework,- example: options.example,- examples,- overlays: templateEntry?.overlays ?? [],- interactive,- });- if (selected.kind === "example") {- await runCreateExample({- options,- interactive,- packageManager,- t0,- name,- targetDir,- example: selected.example,- });- return;- }- if (!template || !templateEntry) {- throw new CreateError(- "args_resolution",- "Missing required argument --template",- "invalid_input",- "MISSING_REQUIRED_ARG",- );- }-- const backendFramework = selected.overlay;- findCatalogOverlay(templateEntry, backendFramework);-- const aiSetup = aiSetupFromTemplate(template);- telemetry.register({ template, ai_setup: aiSetup, backend_framework: backendFramework });- telemetry.capture("cli_ai_setup_selected", {- ...createFunnelProps("ai_setup_selected"),- template,- ai_setup: aiSetup,- });- telemetry.capture("cli_backend_framework_selected", {- ...createFunnelProps("backend_framework_selected"),- backend_framework: backendFramework,- backend_framework_source: options.backendFramework- ? "flag"- : interactive- ? "prompt"- : "default",- });-- telemetry.capture("cli_env_resolution_started", {- ...createFunnelProps("env_resolution_started"),- template,- ai_setup: aiSetup,- });- const envResult =- template === "openui-self-hosted"- ? await resolveChatEnv(interactive)- : await resolveCloudEnv(name, options, interactive);-- const installSkill = await shouldInstallSkill(options.skill, interactive);- telemetry.capture("cli_skill_installed", {- ...createFunnelProps("skill_prompt_resolved"),- skill_installed: installSkill,- });-- const immediateResolution = resolveImmediate(options.immediate, options.noInstall, interactive);- const apiKeyEnv = requiredApiKeyEnv(template);- const apiKeyAvailable = envResult.envWritten || Boolean(process.env[apiKeyEnv]?.trim());- const devStartBlockedByMissingApiKey = immediateResolution.immediate && !apiKeyAvailable;- telemetry.capture("cli_immediate_selected", {- immediate: immediateResolution.immediate,- dependency_install_requested: immediateResolution.installDependencies,- selection_source: immediateResolution.source,- });-- let overlay: TemplateOverlay | undefined;- const runScaffold = async () => {- const { dir: templateDir } = await resolveTemplateSource(template);- telemetry.capture("cli_scaffold_started", {- ...createFunnelProps("scaffold_started"),- template,- ai_setup: aiSetup,- });- try {- overlay = resolveOverlay(templateDir, backendFramework);- fs.cpSync(templateDir, targetDir, {- recursive: true,- filter: (src) => shouldCopyTemplatePath(templateDir, src),- });- restoreDotfiles(targetDir);- applyOverlay(targetDir, overlay);- rewritePackageJson(targetDir, name, packageManager.name, overlay?.manifest.packageJson);- // An overlay that changes dependencies without a lock must not keep the base lock- const overlayShipsNpmLock = Boolean(- overlay && fs.existsSync(path.join(overlay.dir, "package-lock.json")),- );- if (packageManager.name !== "npm" || (overlay && !overlayShipsNpmLock)) {- fs.rmSync(path.join(targetDir, "package-lock.json"), { force: true });- }- // The Cloud template ships pnpm's lock/workspace files for reproducible pnpm- // installs and native-build policy. A framework changes dependencies, so- // regenerate its lock; non-pnpm scaffolds do not need either pnpm file.- if (packageManager.name !== "pnpm" || backendFramework !== "default") {- fs.rmSync(path.join(targetDir, "pnpm-lock.yaml"), { force: true });- }- if (packageManager.name !== "pnpm") {- fs.rmSync(path.join(targetDir, "pnpm-workspace.yaml"), { force: true });- }- await writeEnv(- targetDir,- envResult,- template === "openui-cloud" ? buildAppId(name) : undefined,- );- } catch (err) {- const properties = cliErrorProperties(err, {- failure_stage: "scaffold",- error_class: "filesystem",- error_code: "SCAFFOLD_FAILED",- });- telemetry.capture("cli_scaffold_failed", {- ...createFunnelProps("scaffold_failed"),- template,- ai_setup: aiSetup,- ...properties,- });- throw new CreateError(- properties.failure_stage,- err instanceof Error ? err.message : String(err),- properties.error_class,- properties.error_code,- );- } finally {- fs.rmSync(templateDir, { recursive: true, force: true });- }- };-- console.info();- if (options.verbose) {- console.info(`Scaffolding ${template} into "${name}"...\n`);- await runScaffold();- } else {- await withSpinner("Scaffolding...", runScaffold);- console.info("✓ Scaffolded");- }- telemetry.capture("cli_scaffold_succeeded", {- ...createFunnelProps("scaffold_succeeded"),- template,- ai_setup: aiSetup,- });- telemetry.capture("cli_env_resolved", {- ...createFunnelProps("env_written"),- template,- ai_setup: aiSetup,- env_written: envResult.envWritten,- auth_method: envResult.authMethod,- auth_succeeded: envResult.authSucceeded,- });-- // Framework scaffolds without an npm lock must resolve ranges against the- // registry (`npm install`). When a backend overlay ships package-lock.json,- // keep the normal `npm ci` path. --prefer-offline is only safe for `npm ci`,- // where the lockfile pins exact versions and cache hits are content-addressed;- // bare `npm install` can fail with ETARGET on a stale packument cache.- const frameworkInstall = backendFramework !== "default";- const hasNpmLock = fs.existsSync(path.join(targetDir, "package-lock.json"));- const installCmd =- frameworkInstall && packageManager.name === "npm" && !hasNpmLock- ? "npm install --no-audit --no-fund --progress=false"- : frameworkInstall && packageManager.name === "pnpm"- ? "pnpm install --no-frozen-lockfile"- : packageManager.installCmd;- const installArgs =- frameworkInstall && packageManager.name === "npm" && !hasNpmLock- ? ["install", "--no-audit", "--no-fund", "--progress=false"]- : frameworkInstall && packageManager.name === "pnpm"- ? ["install", "--no-frozen-lockfile"]- : packageManager.installArgs;- let dependencyInstalled = false;-- if (!immediateResolution.installDependencies) {- telemetry.capture("cli_dependency_install_skipped", {- skip_reason: "no_install_flag",- });- console.info(`Skipping dependency install (--no-install). Run \`${installCmd}\` later.`);- } else {- telemetry.capture("cli_dependency_install_started", {- ...createFunnelProps("dependency_install_started"),- template,- ai_setup: aiSetup,- });- const runInstall = () =>- options.verbose- ? runCommand(packageManager.runCmd, installArgs, targetDir)- : runCommand(packageManager.runCmd, installArgs, targetDir, {- echo: false,- stdin: "ignore",- captureLimit: QUIET_COMMAND_CAPTURE_LIMIT,- env: mutedNpmEnv(),- });-- if (options.verbose) {- console.info(`Installing dependencies with: ${installCmd}\n`);- }- const installResult = options.verbose- ? await runInstall()- : await withSpinner("Installing dependencies...", runInstall);- if (!installResult.error && installResult.status === 0) {- dependencyInstalled = true;- if (!options.verbose) {- console.info("✓ Dependencies installed");- }- telemetry.capture("cli_dependency_install_succeeded", {- ...createFunnelProps("dependency_install_succeeded"),- template,- ai_setup: aiSetup,- dependency_installed: dependencyInstalled,- });- } else {- if (!options.verbose) {- printLogTail(installResult.diagnosticTail, "install log (tail)");- }- const properties = processErrorProperties(installResult, "dependency_install", {- error_class: "dependency",- error_code: "NONZERO_EXIT",- });- if (properties.error_class === "user_cancelled") {- telemetry.capture("cli_dependency_install_cancelled", {- ...createFunnelProps("dependency_install_cancelled"),- template,- ai_setup: aiSetup,- dependency_installed: false,- ...properties,- });- throw new CliCancelledError(- "dependency_install",- properties.cancellation_exit_code ?? 0,- properties,- );- }- telemetry.capture("cli_dependency_install_failed", {- ...createFunnelProps("dependency_install_failed"),- template,- ai_setup: aiSetup,- dependency_installed: dependencyInstalled,- ...properties,- });- const { failure_stage, error_class, error_code, ...metadata } = properties;- throw new CreateError(- failure_stage,- "dependency install failed",- error_class,- error_code,- metadata,- );- }- }-- let skillInstalled = false;- if (installSkill) {- telemetry.capture("cli_skill_install_started", {- ...createFunnelProps("skill_install_started"),- skill_installed: installSkill,- });- const runSkill = () =>- options.verbose- ? runSkillInstall(targetDir)- : runSkillInstall(targetDir, {- echo: false,- stdin: "ignore",- captureLimit: QUIET_COMMAND_CAPTURE_LIMIT,- });- if (options.verbose) {- console.info("Installing OpenUI agent skill...\n");- }- const skillResult = options.verbose- ? await runSkill()- : await withSpinner("Installing OpenUI agent skill...", runSkill);- skillInstalled = !skillResult.error && skillResult.status === 0;- if (skillInstalled) {- if (!options.verbose) {- console.info("✓ OpenUI agent skill installed");- }- telemetry.capture("cli_skill_install_finished", {- ...createFunnelProps("skill_install_finished"),- skill_installed: true,- duration_ms: skillResult.durationMs,- exit_code: skillResult.status,- });- } else {- const properties = processErrorProperties(skillResult, "skill_install", {- error_class: "dependency",- error_code: "SKILL_INSTALL_FAILED",- });- if (properties.error_class === "user_cancelled") {- telemetry.capture("cli_skill_install_cancelled", {- ...createFunnelProps("skill_install_cancelled"),- skill_installed: false,- ...properties,- });- throw new CliCancelledError(- "skill_install",- properties.cancellation_exit_code ?? 0,- properties,- );- }- telemetry.capture("cli_skill_install_failed", {- ...createFunnelProps("skill_install_failed"),- skill_installed: false,- ...properties,- });- console.warn(- "\nCould not install the OpenUI agent skill automatically.\n" +- "You can install it manually later with:\n\n" +- " npx skills add thesysdev/skills --skill openui\n",- );- }- }-- const devCmd = packageManager.runCmd;- const startDev =- immediateResolution.immediate && dependencyInstalled && !devStartBlockedByMissingApiKey;-- telemetry.capture("cli_create_succeeded", {- ...createFunnelProps("create_succeeded"),- template,- ai_setup: aiSetup,- duration_ms: Date.now() - t0,- skill_installed: skillInstalled,- env_written: envResult.envWritten,- dependency_installed: dependencyInstalled,- });- console.info(- getStartedMessage({- name,- devCmd,- template,- backendGettingStarted: overlay?.manifest.gettingStarted,- skillInstalled,- envWritten: envResult.envWritten,- startDev,- installCmd,- dependencyInstalled,- }),- );-- if (devStartBlockedByMissingApiKey) {- telemetry.capture("cli_dev_command_skipped", {- skip_reason: "missing_api_key",- required_env: apiKeyEnv,- });- return;- }-- if (!startDev) {- telemetry.capture("cli_dev_command_skipped", {- skip_reason: options.noInstall ? "dependencies_not_installed" : "not_immediate",- });- return;- }-- telemetry.capture("cli_dev_command_started", {- package_manager: packageManager.name,- });- const devResult = await runDevCommand(devCmd, targetDir);- const stoppedNormally =- devResult.status === 0 ||- devResult.status === 130 ||- devResult.status === 143 ||- devResult.signal === "SIGINT" ||- devResult.signal === "SIGTERM";-- if (stoppedNormally) {- telemetry.capture("cli_dev_command_stopped", {- package_manager: packageManager.name,- duration_ms: devResult.durationMs,- exit_code: devResult.status,- failure_signal: devResult.signal,- });- } else {- const exitCode = devResult.status ?? 1;- const properties = processErrorProperties(devResult, "dev_server", {- error_class: "process",- error_code: "NONZERO_EXIT",- });- telemetry.capture("cli_dev_command_failed", {- package_manager: packageManager.name,- failure_reason: devResult.error ? "spawn_error" : "nonzero_exit",- ...properties,- });- console.error(- `\nDevelopment server exited. Retry with:\n\n> cd ${name}\n> ${devCmd} run dev\n`,- );- process.exitCode = exitCode;- }-}--const isInteractiveTerminal = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);--function resolveImmediate(- immediate: boolean | undefined,- noInstall: boolean | undefined,- interactive: boolean,-): {- immediate: boolean;- installDependencies: boolean;- source: "flag" | "interactive_default" | "no_install" | "noninteractive_default";-} {- if (noInstall) {- return { immediate: false, installDependencies: false, source: "no_install" };- }- if (immediate !== undefined) {- return {- immediate,- installDependencies: true,- source: "flag",- };- }- if (!interactive || !isInteractiveTerminal()) {- return {- immediate: false,- installDependencies: true,- source: "noninteractive_default",- };- }- return { immediate: true, installDependencies: true, source: "interactive_default" };-}--async function writeEnv(targetDir: string, result: EnvResult, appId?: string): Promise<void> {- // APP_ID is the scaffold's stable identity: the frontend-token route sends- // it as `app_id`, so every conversation this app creates is bound to it and- // apps sharing one org API key stay isolated from each other. It must stay- // stable for the app's lifetime — regenerating it orphans existing threads.- const content = `${result.envContent ?? ""}${appId ? `APP_ID=${appId}\n` : ""}`;- if (!content) return;- await fs.promises.writeFile(path.join(targetDir, ".env"), content);-}--async function promptForProviderKey(): Promise<string | null> {- try {- const { input } = await import("@inquirer/prompts");- const apiKey = (- await input({- message: "Enter your OpenAI-compatible provider API key (leave blank to skip):",- })- ).trim();- return apiKey || null;- } catch (error) {- const { ExitPromptError } = await import("@inquirer/core");- if (error instanceof ExitPromptError) {- throw new CliCancelledError("environment_resolution");- }- throw error;- }-}--async function resolveChatEnv(interactive: boolean): Promise<EnvResult> {- const apiKey = interactive ? await promptForProviderKey() : null;-- // Always write a file, so the scaffold has a .env to edit rather than one the- // user must know to create. Without a key the entries stay commented out: an- // empty `OPENAI_API_KEY=` would shadow a key already exported in the shell.- const lines = apiKey- ? [`OPENAI_API_KEY=${apiKey}`]- : [- "# Your OpenAI-compatible provider key. Uncomment and fill it in.",- "# OPENAI_API_KEY=sk-your-key-here",- "# Optional:",- "# OPENAI_MODEL=gpt-5.2",- "# OPENAI_BASE_URL=https://api.openai.com/v1",- ];-- return {- // False without a key, so the immediate dev-server gate and the- // "add your API key" message still apply even though .env now exists.- envWritten: apiKey != null,- envContent: lines.join("\n") + "\n",- };-}--async function resolveCloudEnv(- name: string,- options: CreateAppOptions,- interactive: boolean,-): Promise<EnvResult> {- let apiKey: string | null = null;- let authMethod: EnvResult["authMethod"];- try {- telemetry.capture("cli_cloud_auth_started", {- ...createFunnelProps("cloud_auth_started"),- auth_method: options.auth ?? (options.apiKey ? "apikey-flag" : undefined),- });- const resolved = await resolveCloudApiKey({- apiKey: options.apiKey,- auth: options.auth,- projectName: name,- interactive,- });- apiKey = resolved.key;- authMethod = resolved.method;- telemetry.capture("cli_cloud_auth_method", {- ...createFunnelProps("cloud_auth_resolved"),- auth_method: resolved.method,- auth_succeeded: apiKey != null,- });- } catch (err) {- if (err instanceof CliCancelledError) {- telemetry.capture("cli_cloud_auth_cancelled", {- ...createFunnelProps("cloud_auth_cancelled"),- auth_method: options.auth ?? (options.apiKey ? "apikey-flag" : undefined),- auth_succeeded: false,- ...cliErrorProperties(err),- });- throw err;- }- const msg = err instanceof Error ? err.message : String(err);- const properties = cliErrorProperties(err, {- failure_stage: "cloud_auth",- error_class: "authentication",- error_code: "AUTH_FAILED",- });- telemetry.capture("cli_cloud_auth_failed", {- ...createFunnelProps("cloud_auth_failed"),- auth_method: options.auth ?? (options.apiKey ? "apikey-flag" : undefined),- auth_succeeded: false,- ...properties,- });- console.error(`\n[!] Could not obtain an API key: ${msg}`);- console.error(` Add THESYS_API_KEY to .env later (keys: ${THESYS_KEYS_URL}).\n`);- }- const lines = [`THESYS_API_KEY=${apiKey ?? ""}`, `DEMO_USER_ID=demo-user`];- return {- envWritten: apiKey != null,- envContent: lines.join("\n") + "\n",- authMethod,- authSucceeded: apiKey != null,- };-}--function getStartedMessage(o: {- name: string;- devCmd: string;- template: TemplateName;- backendGettingStarted?: string;- skillInstalled: boolean;- envWritten: boolean;- startDev: boolean;- installCmd: string;- dependencyInstalled: boolean;-}): string {- const skillMessage = o.skillInstalled- ? "The OpenUI agent skill was installed.\nAI coding assistants will use it to help you build with OpenUI.\n"- : "";-- const envNote =- o.template === "openui-cloud"- ? o.envWritten- ? "✅ .env created with your OpenUI Cloud API key + base URL."- : `[!] .env created without a key. Add THESYS_API_KEY=… (get one at ${THESYS_KEYS_URL}).`- : o.envWritten- ? "✅ .env created with your API key."- : "Add your API key to .env:\nOPENAI_API_KEY=sk-your-key-here";-- const nextStep = o.startDev- ? `Starting the development server in "${o.name}"...\n\n> ${o.devCmd} run dev`- : [- `> cd ${o.name}`,- ...(o.dependencyInstalled ? [] : [`> ${o.installCmd}`]),- `> ${o.devCmd} run dev`,- ].join("\n");-- const deployHint = "Share a preview:\n> npx @openuidev/cli@latest deploy";-- const frameworkNote = o.backendGettingStarted?.replaceAll("{{packageManager}}", o.devCmd) ?? "";-- return `\n${[skillMessage.trim(), "Done!", envNote, frameworkNote, nextStep, deployHint]- .filter(Boolean)- .join("\n\n")}\n`;-}--const OPENUI_EXAMPLES_CHOICE = "openui-examples";-const GO_BACK_CHOICE = "__back__";--async function resolveCreateSelection(params: {- backendFramework?: OverlayName;- example?: string;- examples: ExampleProject[];- overlays: CatalogOverlay[];- interactive: boolean;-}): Promise<- { kind: "overlay"; overlay: OverlayName } | { kind: "example"; example: ExampleProject }-> {- const { backendFramework, example, examples, overlays, interactive } = params;- if (example) return { kind: "example", example: findExample(example, examples) };- if (backendFramework) return { kind: "overlay", overlay: backendFramework };- if (!interactive) return { kind: "overlay", overlay: "default" };-- const { select, Separator } = await import("@inquirer/prompts");- const prompt = async <T extends string>(- message: string,- choices: unknown[],- pageSize: number,- ) => {- try {- return (await select({- message,- choices: choices as never,- pageSize,- loop: false,- })) as T;- } catch (err) {- const { ExitPromptError } = await import("@inquirer/core");- if (err instanceof ExitPromptError) {- throw new CliCancelledError("args_resolution");- }- throw err;- }- };-- for (;;) {- const starterChoices: unknown[] = overlays.map((overlay) => ({- value: overlay.key,- name: overlay.name,- description: overlay.description,- }));- if (examples.length > 0) {- starterChoices.push(new Separator());- starterChoices.push({- value: OPENUI_EXAMPLES_CHOICE,- name: "Scaffold from OpenUI Examples",- description: "Browse examples from the OpenUI repo",- });- }-- const selected = await prompt<string>(- "Choose your backend framework",- starterChoices,- starterChoices.length,- );- if (selected !== OPENUI_EXAMPLES_CHOICE) {- return { kind: "overlay", overlay: selected as OverlayName };- }-- const exampleSelected = await prompt<string>(- "Select an OpenUI example",- [- { value: GO_BACK_CHOICE, name: "← Back" },- new Separator(),- ...groupedExampleChoices(examples, Separator),- ],- 10,- );- if (exampleSelected === GO_BACK_CHOICE) continue;- return { kind: "example", example: findExample(exampleSelected, examples) };- }-}diff --git a/packages/openui-cli/src/commands/create/command.ts b/packages/openui-cli/src/commands/create/command.tsnew file mode 100644index 000000000..4b3ef243b--- /dev/null+++ b/packages/openui-cli/src/commands/create/command.ts@@ -0,0 +1,74 @@+import { Command } from "commander";++import { normalizeAuth } from "../../lib/auth/mint";+import { context } from "../../lib/context";+import { rejectConflictingScaffoldSelectors } from "./lib/examples-catalog";+import { printCreateHelp } from "./lib/help";+import { rejectConflictingImmediateFlags } from "./lib/resolve";++import { runCreateApp } from "./run";++export const createCommand = new Command("create")+ .description(+ "Scaffold a Next.js agent app with the recommended OpenUI Cloud backend or your own provider",+ )+ .option("-n, --name <string>", "Project name (interactive default: openui-agent)")+ .option("-t, --template <template>", "AI backend to use (default: openui-cloud)")+ .option("--backend-framework <framework>", "Backend framework to use")+ .option("-e, --example <example>", "Create from an example in examples/examples.json")+ .option("--api-key <key>", "OpenUI Cloud API key (cloud template; skips sign-in)")+ .option("--auth <method>", "Cloud auth method: oauth | skip (manual is deprecated)")+ .option("--skill", "Install the OpenUI agent skill for AI coding assistants")+ .option("--no-skill", "Skip installing the OpenUI agent skill")+ .option("--no-interactive", "Fail with error if required args are missing")+ .option("--no-install", "Scaffold without running the package install")+ .option("-i, --immediate", "Start the development server after installing dependencies")+ .option("--no-immediate", "Install dependencies without starting the development server")+ .helpOption(false)+ .option("-h, --help", "display help for command")+ .action(+ async (options: {+ name?: string;+ template?: string;+ backendFramework?: string;+ example?: string;+ apiKey?: string;+ auth?: string;+ skill?: boolean;+ interactive: boolean;+ install: boolean;+ immediate?: boolean;+ help?: boolean;+ }) => {+ if (options.help) {+ await printCreateHelp(createCommand);+ return;+ }++ rejectConflictingImmediateFlags(context.argv.slice(2));+ rejectConflictingScaffoldSelectors({+ example: options.example,+ backendFramework: options.backendFramework,+ template: options.template,+ });++ await runCreateApp(+ {+ name: options.name,+ template: options.template,+ backendFramework: options.backendFramework,+ example: options.example,+ apiKey: options.apiKey,+ auth: normalizeAuth(options.auth),+ skill: options.skill,+ noInteractive: !options.interactive,+ noInstall: !options.install,+ immediate: options.immediate,+ },+ context,+ );+ },+ );++// `openui help create` calls help() (sync) then, if it doesn't exit, dispatches `--help`.+createCommand.help = (() => undefined) as Command["help"];diff --git a/packages/openui-cli/src/commands/create-example.ts b/packages/openui-cli/src/commands/create/lib/create-example.tssimilarity index 54%rename from packages/openui-cli/src/commands/create-example.tsrename to packages/openui-cli/src/commands/create/lib/create-example.tsindex 4133877db..d3b4c5896 100644--- a/packages/openui-cli/src/commands/create-example.ts+++ b/packages/openui-cli/src/commands/create/lib/create-example.ts@@ -1,22 +1,20 @@import * as path from "node:path";-import { printLogTail, QUIET_COMMAND_CAPTURE_LIMIT } from "../lib/command-output";-import { createFunnelProps } from "../lib/create-telemetry";-import type { CreateAppOptions, EnvResult } from "../lib/create-types";-import { resolveInstallPackageManager } from "../lib/detect-package-manager";-import { upsertEnvVar } from "../lib/env";-import type { ExampleProject } from "../lib/examples-catalog";-import { runSkillInstall, shouldInstallSkill } from "../lib/install-skill";+import { resolveInstallPackageManager } from "../../../lib/detect-package-manager";+import { CliCancelledError, cliErrorProperties, CreateError } from "../../../lib/errors";+import { withSpinner } from "../../../lib/spinner";+import type { CreateAppOptions, EnvResult } from "./create-types";+import { writeEnvVar } from "./env";+import type { ExampleProject } from "./examples-catalog";+import { installRequestedSkill, shouldInstallSkill } from "./install-skill";import {exampleDevCommand,exampleLayout,isNestedExample,scaffoldExample,type ExampleLayout,-} from "../lib/scaffold-example";-import { withSpinner } from "../lib/spinner";-import { CliCancelledError, CreateError, telemetry } from "../lib/telemetry";-import { cliErrorProperties, processErrorProperties } from "../lib/utils";+} from "./scaffold-example";+import type { CreateTelemetryClient } from "./telemetry";export async function runCreateExample(params: {options: CreateAppOptions;@@ -26,38 +24,31 @@ export async function runCreateExample(params: {name: string;targetDir: string;example: ExampleProject;+ tel: CreateTelemetryClient;+ verbose: boolean;}): Promise<void> {- const { options, interactive, packageManager, t0, name, targetDir, example } = params;+ const { options, interactive, packageManager, t0, name, targetDir, example, tel, verbose } =+ params;- telemetry.register({ example: example.name, project_category: "example" });- telemetry.capture("cli_example_selected", {- ...createFunnelProps("example_selected"),+ tel.registerContext({ example: example.name, project_category: "example" });+ tel.trackExampleSelected({example: example.name,example_source: options.example ? "flag" : interactive ? "prompt" : "default",});- telemetry.capture("cli_env_resolution_started", {- ...createFunnelProps("env_resolution_started"),- example: example.name,- });+ tel.trackEnvResolutionStarted({ example: example.name });const envResult = await resolveExampleEnv(example, interactive);const installSkill = await shouldInstallSkill(options.skill, false);- telemetry.capture("cli_skill_installed", {- ...createFunnelProps("skill_prompt_resolved"),- skill_installed: installSkill,- });- telemetry.capture("cli_immediate_selected", {+ tel.trackSkillInstalled({ skill_installed: installSkill });+ tel.trackImmediateSelected({immediate: false,dependency_install_requested: false,selection_source: "no_install",});console.info();- telemetry.capture("cli_scaffold_started", {- ...createFunnelProps("scaffold_started"),- example: example.name,- });+ tel.trackScaffoldStarted({ example: example.name });let layout: ExampleLayout | undefined;try {const runScaffold = () =>@@ -67,10 +58,8 @@ export async function runCreateExample(params: {name,packageManager: packageManager.name,});- layout = options.verbose- ? await runScaffold()- : await withSpinner("Scaffolding...", runScaffold);- if (!options.verbose) {+ layout = verbose ? await runScaffold() : await withSpinner("Scaffolding...", runScaffold);+ if (!verbose) {console.info("✓ Scaffolded");}} catch (err) {@@ -79,8 +68,7 @@ export async function runCreateExample(params: {error_class: "filesystem",error_code: "SCAFFOLD_FAILED",});- telemetry.capture("cli_scaffold_failed", {- ...createFunnelProps("scaffold_failed"),+ tel.trackScaffoldFailed({example: example.name,...properties,});@@ -91,14 +79,11 @@ export async function runCreateExample(params: {properties.error_code,);}- telemetry.capture("cli_scaffold_succeeded", {- ...createFunnelProps("scaffold_succeeded"),- example: example.name,- });+ tel.trackScaffoldSucceeded({ example: example.name });try {if (envResult.envKeyValue && example.envKey) {- upsertEnvVar(path.join(targetDir, example.envFile), example.envKey, envResult.envKeyValue);+ writeEnvVar(path.join(targetDir, example.envFile), example.envKey, envResult.envKeyValue);}} catch (err) {const properties = cliErrorProperties(err, {@@ -113,25 +98,29 @@ export async function runCreateExample(params: {properties.error_code,);}- telemetry.capture("cli_env_resolved", {- ...createFunnelProps("env_written"),+ tel.trackEnvResolved({example: example.name,env_written: envResult.envWritten,});layout ??= exampleLayout(targetDir);const installCmd = packageManager.installCmd;- telemetry.capture("cli_dependency_install_skipped", {+ tel.trackDependencyInstallSkipped({skip_reason: "example_scaffold_only",});- telemetry.capture("cli_dev_command_skipped", {+ tel.trackDevCommandSkipped({skip_reason: "not_immediate",});- const skillInstalled = await installExampleSkill(installSkill, options.verbose, targetDir);+ const skillInstalled = await installRequestedSkill({+ enabled: installSkill,+ verbose,+ targetDir,+ tel,+ printFailureLog: true,+ });- telemetry.capture("cli_create_succeeded", {- ...createFunnelProps("create_succeeded"),+ tel.trackCreateSucceeded({example: example.name,duration_ms: Date.now() - t0,skill_installed: skillInstalled,@@ -195,77 +184,6 @@ async function promptForProviderKey(envKey: string): Promise<string | null> {}}-async function installExampleSkill(- enabled: boolean,- verbose: boolean | undefined,- targetDir: string,-): Promise<boolean> {- if (!enabled) return false;-- telemetry.capture("cli_skill_install_started", {- ...createFunnelProps("skill_install_started"),- skill_installed: true,- });- const runSkill = () =>- verbose- ? runSkillInstall(targetDir)- : runSkillInstall(targetDir, {- echo: false,- stdin: "ignore",- captureLimit: QUIET_COMMAND_CAPTURE_LIMIT,- });- if (verbose) {- console.info("Installing OpenUI agent skill...\n");- }- const skillResult = verbose- ? await runSkill()- : await withSpinner("Installing OpenUI agent skill...", runSkill);- const skillInstalled = !skillResult.error && skillResult.status === 0;- if (skillInstalled) {- if (!verbose) {- console.info("✓ OpenUI agent skill installed");- }- telemetry.capture("cli_skill_install_finished", {- ...createFunnelProps("skill_install_finished"),- skill_installed: true,- duration_ms: skillResult.durationMs,- exit_code: skillResult.status,- });- return true;- }-- const properties = processErrorProperties(skillResult, "skill_install", {- error_class: "dependency",- error_code: "SKILL_INSTALL_FAILED",- });- if (properties.error_class === "user_cancelled") {- telemetry.capture("cli_skill_install_cancelled", {- ...createFunnelProps("skill_install_cancelled"),- skill_installed: false,- ...properties,- });- throw new CliCancelledError(- "skill_install",- properties.cancellation_exit_code ?? 0,- properties,- );- }- telemetry.capture("cli_skill_install_failed", {- ...createFunnelProps("skill_install_failed"),- skill_installed: false,- ...properties,- });- if (!verbose) {- printLogTail(skillResult.diagnosticTail, "skill install log (tail)");- }- console.warn(- "\nCould not install the OpenUI agent skill automatically.\n" +- "You can install it manually later with:\n\n" +- " npx skills add thesysdev/skills --skill openui\n",- );- return false;-}-function posixJoin(...parts: string[]): string {return parts.filter((part) => part && part !== ".").join("/");}diff --git a/packages/openui-cli/src/lib/create-types.ts b/packages/openui-cli/src/commands/create/lib/create-types.tssimilarity index 75%rename from packages/openui-cli/src/lib/create-types.tsrename to packages/openui-cli/src/commands/create/lib/create-types.tsindex 573cb040e..daedb2807 100644--- a/packages/openui-cli/src/lib/create-types.ts+++ b/packages/openui-cli/src/commands/create/lib/create-types.ts@@ -1,4 +1,4 @@-import type { CloudAuthMethod, ResolvedAuthMethod } from "../auth/mint";+import type { CloudAuthMethod, ResolvedAuthMethod } from "../../../lib/auth/mint";/** Template `key` from `templates/templates.json`. */export type TemplateName = string;@@ -14,7 +14,6 @@ export interface CreateAppOptions {noInteractive?: boolean;noInstall?: boolean;immediate?: boolean;- verbose?: boolean;apiKey?: string;auth?: CloudAuthMethod;}@@ -23,7 +22,9 @@ export type AiSetup = "openui_cloud" | "openai_compatible_provider";export type EnvResult = {envWritten: boolean;- envContent?: string;+ envVars?: Record<string, string>;+ /** Comment-only `.env` body when there are no assignments to upsert. */+ envStub?: string;authMethod?: ResolvedAuthMethod;authSucceeded?: boolean;};diff --git a/packages/openui-cli/src/lib/dev-server.ts b/packages/openui-cli/src/commands/create/lib/dev-server.tssimilarity index 95%rename from packages/openui-cli/src/lib/dev-server.tsrename to packages/openui-cli/src/commands/create/lib/dev-server.tsindex e1e1e50e3..52ab4c52b 100644--- a/packages/openui-cli/src/lib/dev-server.ts+++ b/packages/openui-cli/src/commands/create/lib/dev-server.ts@@ -1,6 +1,6 @@import * as http from "node:http";-import { runCommand, type CommandResult } from "./process-runner";+import { runCommand, type CommandResult } from "../../../lib/process-runner";function isServerReady(url: string): Promise<boolean> {return new Promise((resolve) => {diff --git a/packages/openui-cli/src/commands/create/lib/env.ts b/packages/openui-cli/src/commands/create/lib/env.tsnew file mode 100644index 000000000..c5ef33bc3--- /dev/null+++ b/packages/openui-cli/src/commands/create/lib/env.ts@@ -0,0 +1,149 @@+import * as fs from "node:fs";+import * as path from "node:path";++import { resolveCloudApiKey, THESYS_KEYS_URL } from "../../../lib/auth/mint";+import { DEFAULT_ENV_FILE, upsertEnvVar } from "../../../lib/env";+import { CliCancelledError, cliErrorProperties } from "../../../lib/errors";+import type { CreateAppOptions, EnvResult, TemplateName } from "./create-types";+import type { CreateTelemetryClient } from "./telemetry";++export function buildAppId(name: string): string {+ // Stable per-scaffold identity (see writeEnv). Slugified because the name is+ // free-form and APP_ID lands in .env and ?app_id= query params; the random+ // suffix keeps two same-named apps in one org from colliding.+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");+ return `${slug}-${Math.random().toString(36).slice(2, 8)}`;+}++export function requiredApiKeyEnv(template: TemplateName): "THESYS_API_KEY" | "OPENAI_API_KEY" {+ return template === "openui-cloud" ? "THESYS_API_KEY" : "OPENAI_API_KEY";+}++export function writeEnvVar(filePath: string, name: string, value: string): void {+ upsertEnvVar(filePath, name, value);+}++export async function writeEnv(+ targetDir: string,+ result: EnvResult,+ appId?: string,+): Promise<void> {+ // APP_ID is the scaffold's stable identity: the frontend-token route sends+ // it as `app_id`, so every conversation this app creates is bound to it and+ // apps sharing one org API key stay isolated from each other. It must stay+ // stable for the app's lifetime — regenerating it orphans existing threads.+ const dest = path.join(targetDir, DEFAULT_ENV_FILE);+ const vars = { ...result.envVars };+ if (appId) vars["APP_ID"] = appId;+ const names = Object.keys(vars);+ if (names.length === 0) {+ if (!result.envStub) return;+ await fs.promises.writeFile(dest, result.envStub);+ return;+ }+ for (const name of names) {+ writeEnvVar(dest, name, vars[name] ?? "");+ }+}++async function promptForProviderKey(): Promise<string | null> {+ try {+ const { input } = await import("@inquirer/prompts");+ const apiKey = (+ await input({+ message: "Enter your OpenAI-compatible provider API key (leave blank to skip):",+ })+ ).trim();+ return apiKey || null;+ } catch (error) {+ const { ExitPromptError } = await import("@inquirer/core");+ if (error instanceof ExitPromptError) {+ throw new CliCancelledError("environment_resolution");+ }+ throw error;+ }+}++export async function resolveChatEnv(interactive: boolean): Promise<EnvResult> {+ const apiKey = interactive ? await promptForProviderKey() : null;++ // Always write a file, so the scaffold has a .env to edit rather than one the+ // user must know to create. Without a key the entries stay commented out: an+ // empty `OPENAI_API_KEY=` would shadow a key already exported in the shell.+ if (apiKey) {+ return { envWritten: true, envVars: { OPENAI_API_KEY: apiKey } };+ }++ return {+ // False without a key, so the immediate dev-server gate and the+ // "add your API key" message still apply even though .env now exists.+ envWritten: false,+ envStub: [+ "# Your OpenAI-compatible provider key. Uncomment and fill it in.",+ "# OPENAI_API_KEY=sk-your-key-here",+ "# Optional:",+ "# OPENAI_MODEL=gpt-5.2",+ "# OPENAI_BASE_URL=https://api.openai.com/v1",+ "",+ ].join("\n"),+ };+}++export async function resolveCloudEnv(+ name: string,+ options: CreateAppOptions,+ interactive: boolean,+ tel: CreateTelemetryClient,+): Promise<EnvResult> {+ let apiKey: string | null = null;+ let authMethod: EnvResult["authMethod"];+ try {+ tel.trackCloudAuthStarted({+ auth_method: options.auth ?? (options.apiKey ? "apikey-flag" : undefined),+ });+ const resolved = await resolveCloudApiKey({+ apiKey: options.apiKey,+ auth: options.auth,+ projectName: name,+ interactive,+ tel: tel.authClient(),+ });+ apiKey = resolved.key;+ authMethod = resolved.method;+ tel.trackCloudAuthMethod({+ auth_method: resolved.method,+ auth_succeeded: apiKey != null,+ });+ } catch (err) {+ if (err instanceof CliCancelledError) {+ tel.trackCloudAuthCancelled({+ auth_method: options.auth ?? (options.apiKey ? "apikey-flag" : undefined),+ auth_succeeded: false,+ ...cliErrorProperties(err),+ });+ throw err;+ }+ const msg = err instanceof Error ? err.message : String(err);+ const properties = cliErrorProperties(err, {+ failure_stage: "cloud_auth",+ error_class: "authentication",+ error_code: "AUTH_FAILED",+ });+ tel.trackCloudAuthFailed({+ auth_method: options.auth ?? (options.apiKey ? "apikey-flag" : undefined),+ auth_succeeded: false,+ ...properties,+ });+ console.error(`\n[!] Could not obtain an API key: ${msg}`);+ console.error(` Add THESYS_API_KEY to .env later (keys: ${THESYS_KEYS_URL}).\n`);+ }+ return {+ envWritten: apiKey != null,+ envVars: {+ THESYS_API_KEY: apiKey ?? "",+ DEMO_USER_ID: "demo-user",+ },+ authMethod,+ authSucceeded: apiKey != null,+ };+}diff --git a/packages/openui-cli/src/lib/examples-catalog.ts b/packages/openui-cli/src/commands/create/lib/examples-catalog.tssimilarity index 97%rename from packages/openui-cli/src/lib/examples-catalog.tsrename to packages/openui-cli/src/commands/create/lib/examples-catalog.tsindex bf30efcc8..e0204166c 100644--- a/packages/openui-cli/src/lib/examples-catalog.ts+++ b/packages/openui-cli/src/commands/create/lib/examples-catalog.ts@@ -1,7 +1,7 @@import { styleText } from "node:util";-import { fetchSourceFile } from "./checkout";-import { CreateError } from "./telemetry";+import { fetchSourceFile } from "../../../lib/checkout";+import { CreateError } from "../../../lib/errors";export const EXAMPLES_CATALOG_PATH = "examples/examples.json";diff --git a/packages/openui-cli/src/commands/create/lib/help.ts b/packages/openui-cli/src/commands/create/lib/help.tsnew file mode 100644index 000000000..1450bbe17--- /dev/null+++ b/packages/openui-cli/src/commands/create/lib/help.ts@@ -0,0 +1,96 @@+import type { Command } from "commander";++import {+ loadTemplatesCatalog,+ type CatalogOverlay,+ type CatalogTemplate,+} from "./templates-catalog";++type HelpEntry = { key: string; description: string };++const FALLBACK_TEMPLATES: HelpEntry[] = [+ {+ key: "openui-cloud",+ description:+ "Recommended default for prototypes and evaluations. Hosted models, managed conversation history, built-in tools, and ready-to-use reports and presentations.",+ },+ {+ key: "openui-self-hosted",+ description:+ "Choose when owning the OpenAI-compatible provider, AI route, and persistence is a requirement. Available only via --template; interactive runs default to openui-cloud.",+ },+];++const FALLBACK_FRAMEWORKS: HelpEntry[] = [+ { key: "default", description: "Uses OpenAI SDK." },+ {+ key: "langgraph",+ description: "Bootstraps a LangGraph agent with the selected model backend.",+ },+ {+ key: "vercel-ai-sdk",+ description: "Scaffolds a Vercel AI SDK agent with the selected model backend.",+ },+ {+ key: "vercel-eve",+ description: "Scaffolds a Vercel Eve agent with the selected model backend.",+ },+];++function formatSection(title: string, entries: HelpEntry[]): string {+ const width = Math.max(...entries.map((entry) => entry.key.length), 0);+ const lines = entries.map((entry) => ` ${entry.key.padEnd(width)} ${entry.description}`);+ return `${title}\n${lines.join("\n")}`;+}++function uniqueOverlays(templates: CatalogTemplate[]): CatalogOverlay[] {+ const seen = new Map<string, CatalogOverlay>();+ for (const template of templates) {+ for (const overlay of template.overlays) {+ if (!seen.has(overlay.key)) seen.set(overlay.key, overlay);+ }+ }+ return [...seen.values()];+}++async function loadCreateHelpText(): Promise<string> {+ const sections: string[] = [];+ try {+ const templates = await loadTemplatesCatalog();+ sections.push(+ formatSection(+ "Templates:",+ templates.map((template) => ({+ key: template.key,+ description: template.description,+ })),+ ),+ );+ sections.push(+ formatSection(+ "Backend frameworks:",+ uniqueOverlays(templates).map((overlay) => ({+ key: overlay.key,+ description: overlay.description,+ })),+ ),+ );+ } catch {+ sections.push(formatSection("Templates:", FALLBACK_TEMPLATES));+ sections.push(formatSection("Backend frameworks:", FALLBACK_FRAMEWORKS));+ sections.push(" Live catalog could not be fetched.");+ }++ sections.push(`OpenUI examples:+ Loaded at runtime from examples/examples.json in the OpenUI repo.+ Pick "Scaffold from OpenUI Examples" in the interactive prompt, or pass+ --example <name> with any catalog folder name.`);++ return `\n${sections.join("\n\n")}\n`;+}++/** Built-in `--help` is sync; print flags now, then the fetched catalog. */+export async function printCreateHelp(command: Command): Promise<void> {+ process.stdout.write(command.helpInformation());+ process.stdout.write(await loadCreateHelpText());+}diff --git a/packages/openui-cli/src/commands/create/lib/install-skill.ts b/packages/openui-cli/src/commands/create/lib/install-skill.tsnew file mode 100644index 000000000..0c19f5ca1--- /dev/null+++ b/packages/openui-cli/src/commands/create/lib/install-skill.ts@@ -0,0 +1,113 @@+import { printLogTail, QUIET_COMMAND_CAPTURE_LIMIT } from "../../../lib/command-output";+import { CliCancelledError, processErrorProperties } from "../../../lib/errors";+import {+ runCommand,+ type CommandResult,+ type RunCommandOptions,+} from "../../../lib/process-runner";+import { withSpinner } from "../../../lib/spinner";+import type { CreateTelemetryClient } from "./telemetry";++const OPENUI_SKILL_SOURCE = "thesysdev/skills";++export async function shouldInstallSkill(+ option: boolean | undefined,+ interactive: boolean,+): Promise<boolean> {+ if (option !== undefined) return option;+ if (!interactive) return false;++ try {+ const { confirm } = await import("@inquirer/prompts");+ return await confirm({+ message: "Install the OpenUI agent skill for AI coding assistants?",+ default: true,+ });+ } catch (err) {+ const { ExitPromptError } = await import("@inquirer/core");+ if (err instanceof ExitPromptError) {+ throw new CliCancelledError("skill_prompt");+ }+ throw err;+ }+}++async function runSkillInstall(+ targetDir: string,+ options: RunCommandOptions = {},+): Promise<CommandResult> {+ return runCommand(+ "npx",+ ["-y", "skills", "add", OPENUI_SKILL_SOURCE, "--skill", "openui", "-y"],+ targetDir,+ options,+ );+}++export async function installRequestedSkill(params: {+ enabled: boolean;+ verbose?: boolean;+ targetDir: string;+ tel: CreateTelemetryClient;+ printFailureLog?: boolean;+}): Promise<boolean> {+ const { enabled, verbose, targetDir, tel, printFailureLog } = params;+ if (!enabled) return false;++ tel.trackSkillInstallStarted({ skill_installed: true });+ const runSkill = () =>+ verbose+ ? runSkillInstall(targetDir)+ : runSkillInstall(targetDir, {+ echo: false,+ stdin: "ignore",+ captureLimit: QUIET_COMMAND_CAPTURE_LIMIT,+ });+ if (verbose) {+ console.info("Installing OpenUI agent skill...\n");+ }+ const skillResult = verbose+ ? await runSkill()+ : await withSpinner("Installing OpenUI agent skill...", runSkill);+ const skillInstalled = !skillResult.error && skillResult.status === 0;+ if (skillInstalled) {+ if (!verbose) {+ console.info("✓ OpenUI agent skill installed");+ }+ tel.trackSkillInstallFinished({+ skill_installed: true,+ duration_ms: skillResult.durationMs,+ exit_code: skillResult.status,+ });+ return true;+ }++ const properties = processErrorProperties(skillResult, "skill_install", {+ error_class: "dependency",+ error_code: "SKILL_INSTALL_FAILED",+ });+ if (properties.error_class === "user_cancelled") {+ tel.trackSkillInstallCancelled({+ skill_installed: false,+ ...properties,+ });+ throw new CliCancelledError(+ "skill_install",+ properties.cancellation_exit_code ?? 0,+ properties,+ );+ }+ tel.trackSkillInstallFailed({+ skill_installed: false,+ ...properties,+ });+ if (printFailureLog && !verbose) {+ printLogTail(skillResult.diagnosticTail, "skill install log (tail)");+ }+ console.warn(+ "\nCould not install the OpenUI agent skill automatically.\n" ++ "You can install it manually later with:\n\n" ++ " npx skills add thesysdev/skills --skill openui\n",+ );+ return false;+}diff --git a/packages/openui-cli/src/commands/create/lib/install.ts b/packages/openui-cli/src/commands/create/lib/install.tsnew file mode 100644index 000000000..f11802157--- /dev/null+++ b/packages/openui-cli/src/commands/create/lib/install.ts@@ -0,0 +1,134 @@+import * as fs from "node:fs";+import * as path from "node:path";++import { printLogTail, QUIET_COMMAND_CAPTURE_LIMIT } from "../../../lib/command-output";+import type { PackageManager } from "../../../lib/detect-package-manager";+import { CliCancelledError, CreateError, processErrorProperties } from "../../../lib/errors";+import { mutedNpmEnv, runCommand } from "../../../lib/process-runner";+import { withSpinner } from "../../../lib/spinner";+import type { OverlayName, TemplateName } from "./create-types";+import type { CreateTelemetryClient } from "./telemetry";++export function resolveInstallInvocation(params: {+ backendFramework: OverlayName;+ packageManager: PackageManager;+ targetDir: string;+}): { installCmd: string; installArgs: string[] } {+ const { backendFramework, packageManager, targetDir } = params;+ // Framework scaffolds without an npm lock must resolve ranges against the+ // registry (`npm install`). When a backend overlay ships package-lock.json,+ // keep the normal `npm ci` path. --prefer-offline is only safe for `npm ci`,+ // where the lockfile pins exact versions and cache hits are content-addressed;+ // bare `npm install` can fail with ETARGET on a stale packument cache.+ const frameworkInstall = backendFramework !== "default";+ const hasNpmLock = fs.existsSync(path.join(targetDir, "package-lock.json"));+ const installCmd =+ frameworkInstall && packageManager.name === "npm" && !hasNpmLock+ ? "npm install --no-audit --no-fund --progress=false"+ : frameworkInstall && packageManager.name === "pnpm"+ ? "pnpm install --no-frozen-lockfile"+ : packageManager.installCmd;+ const installArgs =+ frameworkInstall && packageManager.name === "npm" && !hasNpmLock+ ? ["install", "--no-audit", "--no-fund", "--progress=false"]+ : frameworkInstall && packageManager.name === "pnpm"+ ? ["install", "--no-frozen-lockfile"]+ : packageManager.installArgs;+ return { installCmd, installArgs };+}++export async function installProjectDependencies(params: {+ tel: CreateTelemetryClient;+ verbose?: boolean;+ targetDir: string;+ template: TemplateName;+ aiSetup: string;+ packageManager: PackageManager;+ installCmd: string;+ installArgs: string[];+ installDependencies: boolean;+}): Promise<boolean> {+ const {+ tel,+ verbose,+ targetDir,+ template,+ aiSetup,+ packageManager,+ installCmd,+ installArgs,+ installDependencies,+ } = params;++ if (!installDependencies) {+ tel.trackDependencyInstallSkipped({+ skip_reason: "no_install_flag",+ });+ console.info(`Skipping dependency install (--no-install). Run \`${installCmd}\` later.`);+ return false;+ }++ tel.trackDependencyInstallStarted({ template, ai_setup: aiSetup });+ const runInstall = () =>+ verbose+ ? runCommand(packageManager.runCmd, installArgs, targetDir)+ : runCommand(packageManager.runCmd, installArgs, targetDir, {+ echo: false,+ stdin: "ignore",+ captureLimit: QUIET_COMMAND_CAPTURE_LIMIT,+ env: mutedNpmEnv(),+ });++ if (verbose) {+ console.info(`Installing dependencies with: ${installCmd}\n`);+ }+ const installResult = verbose+ ? await runInstall()+ : await withSpinner("Installing dependencies...", runInstall);+ if (!installResult.error && installResult.status === 0) {+ if (!verbose) {+ console.info("✓ Dependencies installed");+ }+ tel.trackDependencyInstallSucceeded({+ template,+ ai_setup: aiSetup,+ dependency_installed: true,+ });+ return true;+ }++ if (!verbose) {+ printLogTail(installResult.diagnosticTail, "install log (tail)");+ }+ const properties = processErrorProperties(installResult, "dependency_install", {+ error_class: "dependency",+ error_code: "NONZERO_EXIT",+ });+ if (properties.error_class === "user_cancelled") {+ tel.trackDependencyInstallCancelled({+ template,+ ai_setup: aiSetup,+ dependency_installed: false,+ ...properties,+ });+ throw new CliCancelledError(+ "dependency_install",+ properties.cancellation_exit_code ?? 0,+ properties,+ );+ }+ tel.trackDependencyInstallFailed({+ template,+ ai_setup: aiSetup,+ dependency_installed: false,+ ...properties,+ });+ const { failure_stage, error_class, error_code, ...metadata } = properties;+ throw new CreateError(+ failure_stage,+ "dependency install failed",+ error_class,+ error_code,+ metadata,+ );+}diff --git a/packages/openui-cli/src/commands/create/lib/messages.ts b/packages/openui-cli/src/commands/create/lib/messages.tsnew file mode 100644index 000000000..524b22582--- /dev/null+++ b/packages/openui-cli/src/commands/create/lib/messages.ts@@ -0,0 +1,43 @@+import { THESYS_KEYS_URL } from "../../../lib/auth/mint";+import type { TemplateName } from "./create-types";++export function getStartedMessage(o: {+ name: string;+ devCmd: string;+ template: TemplateName;+ backendGettingStarted?: string;+ skillInstalled: boolean;+ envWritten: boolean;+ startDev: boolean;+ installCmd: string;+ dependencyInstalled: boolean;+}): string {+ const skillMessage = o.skillInstalled+ ? "The OpenUI agent skill was installed.\nAI coding assistants will use it to help you build with OpenUI.\n"+ : "";++ const envNote =+ o.template === "openui-cloud"+ ? o.envWritten+ ? "✅ .env created with your OpenUI Cloud API key + base URL."+ : `[!] .env created without a key. Add THESYS_API_KEY=… (get one at ${THESYS_KEYS_URL}).`+ : o.envWritten+ ? "✅ .env created with your API key."+ : "Add your API key to .env:\nOPENAI_API_KEY=sk-your-key-here";++ const nextStep = o.startDev+ ? `Starting the development server in "${o.name}"...\n\n> ${o.devCmd} run dev`+ : [+ `> cd ${o.name}`,+ ...(o.dependencyInstalled ? [] : [`> ${o.installCmd}`]),+ `> ${o.devCmd} run dev`,+ ].join("\n");++ const deployHint = "Share a preview:\n> npx @openuidev/cli@latest deploy";++ const frameworkNote = o.backendGettingStarted?.replaceAll("{{packageManager}}", o.devCmd) ?? "";++ return `\n${[skillMessage.trim(), "Done!", envNote, frameworkNote, nextStep, deployHint]+ .filter(Boolean)+ .join("\n\n")}\n`;+}diff --git a/packages/openui-cli/src/lib/overlays.ts b/packages/openui-cli/src/commands/create/lib/overlays.tssimilarity index 98%rename from packages/openui-cli/src/lib/overlays.tsrename to packages/openui-cli/src/commands/create/lib/overlays.tsindex cbef9c80d..27eca4832 100644--- a/packages/openui-cli/src/lib/overlays.ts+++ b/packages/openui-cli/src/commands/create/lib/overlays.ts@@ -1,7 +1,7 @@import * as fs from "node:fs";import * as path from "node:path";-import { CreateError } from "./telemetry";+import { CreateError } from "../../../lib/errors";export const OVERLAYS_DIR = "overlays";export const OVERLAY_MANIFEST = "manifest.json";diff --git a/packages/openui-cli/src/commands/create/lib/resolve.ts b/packages/openui-cli/src/commands/create/lib/resolve.tsnew file mode 100644index 000000000..b1b44ff9a--- /dev/null+++ b/packages/openui-cli/src/commands/create/lib/resolve.ts@@ -0,0 +1,213 @@+import { CliCancelledError, CreateError } from "../../../lib/errors";+import { resolveArgs } from "../../../lib/resolve-args";+import type { OverlayName, TemplateName } from "./create-types";+import {+ findExample,+ groupedExampleChoices,+ loadExamplesCatalog,+ rejectConflictingScaffoldSelectors,+ type ExampleProject,+} from "./examples-catalog";+import { resolveAvailableTarget } from "./target-dir";+import type { CreateTelemetryClient } from "./telemetry";+import {+ DEFAULT_TEMPLATE_KEY,+ findCatalogOverlay,+ findCatalogTemplate,+ loadTemplatesCatalog,+ type CatalogOverlay,+ type CatalogTemplate,+} from "./templates-catalog";++export function rejectConflictingImmediateFlags(args: string[]): void {+ const separatorIndex = args.indexOf("--");+ const optionArgs = separatorIndex === -1 ? args : args.slice(0, separatorIndex);+ const hasImmediate = optionArgs.some((arg) => arg === "--immediate" || arg === "-i");+ const hasNoImmediate = optionArgs.includes("--no-immediate");+ if (hasImmediate && hasNoImmediate) {+ throw new CreateError("bad_args", "--immediate and --no-immediate cannot be used together.");+ }+}++export type CreateCatalog = {+ examples: ExampleProject[];+ template?: TemplateName;+ templateEntry?: CatalogTemplate;+};++export async function loadCreateCatalog(params: {+ example?: string;+ template?: TemplateName;+ backendFramework?: OverlayName;+ interactive: boolean;+}): Promise<CreateCatalog> {+ const { example, template: requestedTemplate, backendFramework, interactive } = params;++ rejectConflictingScaffoldSelectors({+ example,+ backendFramework,+ template: requestedTemplate,+ });++ // Interactive runs always scaffold the Cloud backend; openui-self-hosted stays+ // available, but only when requested explicitly with --template.+ if (!interactive && !example && !requestedTemplate) {+ throw new CreateError(+ "args_resolution",+ "Missing required argument --template",+ "invalid_input",+ "MISSING_REQUIRED_ARG",+ );+ }++ if (example) {+ const examples = await loadExamplesCatalog();+ findExample(example, examples);+ return { examples };+ }++ if (interactive) {+ const [catalog, examples] = await Promise.all([loadTemplatesCatalog(), loadExamplesCatalog()]);+ const template = requestedTemplate ?? DEFAULT_TEMPLATE_KEY;+ const templateEntry = findCatalogTemplate(catalog, template);+ if (backendFramework) {+ findCatalogOverlay(templateEntry, backendFramework);+ }+ return { examples, template, templateEntry };+ }++ const catalog = await loadTemplatesCatalog();+ const template = requestedTemplate ?? DEFAULT_TEMPLATE_KEY;+ const templateEntry = findCatalogTemplate(catalog, template);+ if (backendFramework) {+ findCatalogOverlay(templateEntry, backendFramework);+ }+ return { examples: [], template, templateEntry };+}++export async function resolveProjectIdentity(+ requestedName: string | undefined,+ interactive: boolean,+ tel: CreateTelemetryClient,+): Promise<{ name: string; targetDir: string }> {+ const nameArgs = await resolveArgs(+ {+ name: requestedName+ ? { value: requestedName }+ : {+ prompt: { type: "input", message: "Project name?", default: "openui-agent" },+ required: true,+ },+ },+ interactive,+ );+ return resolveAvailableTarget((nameArgs as { name: string }).name, interactive, tel);+}++const OPENUI_EXAMPLES_CHOICE = "openui-examples";+const GO_BACK_CHOICE = "__back__";++export async function resolveCreateSelection(params: {+ backendFramework?: OverlayName;+ example?: string;+ examples: ExampleProject[];+ overlays: CatalogOverlay[];+ interactive: boolean;+}): Promise<+ { kind: "overlay"; overlay: OverlayName } | { kind: "example"; example: ExampleProject }+> {+ const { backendFramework, example, examples, overlays, interactive } = params;+ if (example) return { kind: "example", example: findExample(example, examples) };+ if (backendFramework) return { kind: "overlay", overlay: backendFramework };+ if (!interactive) return { kind: "overlay", overlay: "default" };++ const { select, Separator } = await import("@inquirer/prompts");+ const prompt = async <T extends string>(+ message: string,+ choices: unknown[],+ pageSize: number,+ ) => {+ try {+ return (await select({+ message,+ choices: choices as never,+ pageSize,+ loop: false,+ })) as T;+ } catch (err) {+ const { ExitPromptError } = await import("@inquirer/core");+ if (err instanceof ExitPromptError) {+ throw new CliCancelledError("args_resolution");+ }+ throw err;+ }+ };++ for (;;) {+ const starterChoices: unknown[] = overlays.map((overlay) => ({+ value: overlay.key,+ name: overlay.name,+ description: overlay.description,+ }));+ if (examples.length > 0) {+ starterChoices.push(new Separator());+ starterChoices.push({+ value: OPENUI_EXAMPLES_CHOICE,+ name: "Scaffold from OpenUI Examples",+ description: "Browse examples from the OpenUI repo",+ });+ }++ const selected = await prompt<string>(+ "Choose your backend framework",+ starterChoices,+ starterChoices.length,+ );+ if (selected !== OPENUI_EXAMPLES_CHOICE) {+ return { kind: "overlay", overlay: selected as OverlayName };+ }++ const exampleSelected = await prompt<string>(+ "Select an OpenUI example",+ [+ { value: GO_BACK_CHOICE, name: "← Back" },+ new Separator(),+ ...groupedExampleChoices(examples, Separator),+ ],+ 10,+ );+ if (exampleSelected === GO_BACK_CHOICE) continue;+ return { kind: "example", example: findExample(exampleSelected, examples) };+ }+}++const isInteractiveTerminal = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);++export function resolveImmediate(+ immediate: boolean | undefined,+ noInstall: boolean | undefined,+ interactive: boolean,+): {+ immediate: boolean;+ installDependencies: boolean;+ source: "flag" | "interactive_default" | "no_install" | "noninteractive_default";+} {+ if (noInstall) {+ return { immediate: false, installDependencies: false, source: "no_install" };+ }+ if (immediate !== undefined) {+ return {+ immediate,+ installDependencies: true,+ source: "flag",+ };+ }+ if (!interactive || !isInteractiveTerminal()) {+ return {+ immediate: false,+ installDependencies: true,+ source: "noninteractive_default",+ };+ }+ return { immediate: true, installDependencies: true, source: "interactive_default" };+}diff --git a/packages/openui-cli/src/lib/scaffold-example.ts b/packages/openui-cli/src/commands/create/lib/scaffold-example.tssimilarity index 97%rename from packages/openui-cli/src/lib/scaffold-example.tsrename to packages/openui-cli/src/commands/create/lib/scaffold-example.tsindex 7532a75ee..b64c264be 100644--- a/packages/openui-cli/src/lib/scaffold-example.ts+++ b/packages/openui-cli/src/commands/create/lib/scaffold-example.ts@@ -2,10 +2,10 @@ import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";-import { checkoutSource } from "./checkout";-import type { PackageManagerName } from "./detect-package-manager";+import { checkoutSource } from "../../../lib/checkout";+import type { PackageManagerName } from "../../../lib/detect-package-manager";+import { CreateError } from "../../../lib/errors";import type { ExampleProject } from "./examples-catalog";-import { CreateError } from "./telemetry";const ARTIFACT_DIRS = new Set(["node_modules", ".next", ".turbo", "dist", ".nuxt", ".svelte-kit"]);diff --git a/packages/openui-cli/src/lib/target-dir.ts b/packages/openui-cli/src/commands/create/lib/target-dir.tssimilarity index 88%rename from packages/openui-cli/src/lib/target-dir.tsrename to packages/openui-cli/src/commands/create/lib/target-dir.tsindex 146facb20..03d7ccb75 100644--- a/packages/openui-cli/src/lib/target-dir.ts+++ b/packages/openui-cli/src/commands/create/lib/target-dir.ts@@ -1,8 +1,9 @@import * as fs from "node:fs";import * as path from "node:path";-import { resolveArgs } from "./resolve-args";-import { CreateError, telemetry } from "./telemetry";+import { CreateError } from "../../../lib/errors";+import { resolveArgs } from "../../../lib/resolve-args";+import type { CreateTelemetryClient } from "./telemetry";/** How many times an interactive run may re-prompt before aborting. */const MAX_NAME_RETRIES = 5;@@ -22,6 +23,7 @@ function suggestAvailableName(name: string): string {export async function resolveAvailableTarget(requestedName: string,interactive: boolean,+ tel: CreateTelemetryClient,): Promise<{ name: string; targetDir: string }> {let name = requestedName;let retries = 0;@@ -29,7 +31,7 @@ export async function resolveAvailableTarget(for (;;) {const targetDir = path.resolve(process.cwd(), name);if (!fs.existsSync(targetDir)) {- if (retries > 0) telemetry.capture("cli_target_name_retried", { retries });+ if (retries > 0) tel.trackTargetNameRetried({ retries });return { name, targetDir };}@@ -38,7 +40,7 @@ export async function resolveAvailableTarget(// Fired on every collision, in both modes. Interactive runs now recover// instead of throwing, so without this the TARGET_EXISTS signal that used// to reach analytics via cli_create_failed would disappear for them.- telemetry.capture("cli_target_exists", {+ tel.trackTargetExists({interactive,attempt: retries + 1,exhausted,diff --git a/packages/openui-cli/src/commands/create/lib/telemetry.ts b/packages/openui-cli/src/commands/create/lib/telemetry.tsnew file mode 100644index 000000000..b023c802b--- /dev/null+++ b/packages/openui-cli/src/commands/create/lib/telemetry.ts@@ -0,0 +1,268 @@+import { AuthTelemetryClient } from "../../../lib/auth/telemetry";+import { Telemetry } from "../../../lib/telemetry";+import type { AiSetup, TemplateName } from "./create-types";++const createFunnel = {+ funnel: "cli_create",+ funnel_version: "frontloaded_cloud_setup_v1",+} as const;++const createFunnelSteps = {+ create_started: "0100",+ ai_setup_selected: "0200",+ backend_framework_selected: "0250",+ example_selected: "0260",+ scaffold_started: "0300",+ scaffold_succeeded: "0310",+ scaffold_failed: "0320",+ env_resolution_started: "0400",+ cloud_auth_started: "0410",+ cloud_auth_resolved: "0420",+ cloud_auth_failed: "0425",+ cloud_auth_cancelled: "0426",+ env_written: "0430",+ skill_prompt_resolved: "0500",+ skill_install_started: "0510",+ skill_install_finished: "0520",+ skill_install_failed: "0525",+ skill_install_cancelled: "0526",+ dependency_install_started: "0600",+ dependency_install_succeeded: "0610",+ dependency_install_failed: "0620",+ dependency_install_cancelled: "0625",+ create_succeeded: "0700",+ create_failed: "9000",+ create_cancelled: "9010",+} as const;++type CreateFunnelStep = keyof typeof createFunnelSteps;++function createFunnelProps(stepKey: CreateFunnelStep): Record<string, string> {+ return {+ ...createFunnel,+ step_rank: createFunnelSteps[stepKey],+ step_key: stepKey,+ };+}++export function aiSetupFromTemplate(template: TemplateName): AiSetup {+ return template === "openui-cloud" ? "openui_cloud" : "openai_compatible_provider";+}++export class CreateTelemetryClient extends Telemetry {+ static failedProperties(cancelled: boolean): Record<string, string> {+ return createFunnelProps(cancelled ? "create_cancelled" : "create_failed");+ }++ authClient(): AuthTelemetryClient {+ return new AuthTelemetryClient(this);+ }++ registerContext(props: Record<string, unknown>) {+ this.register(props);+ }++ trackStarted(props: {+ interactive: boolean;+ has_name_arg: boolean;+ has_template_arg: boolean;+ has_backend_framework_arg: boolean;+ has_example_arg: boolean;+ has_api_key_arg: boolean;+ has_auth_arg: boolean;+ no_install: boolean;+ immediate_arg: boolean | undefined;+ }) {+ this.capture("cli_create_started", { ...createFunnelProps("create_started"), ...props });+ }++ trackAiSetupSelected(props: { template: string; ai_setup: string }) {+ this.capture("cli_ai_setup_selected", { ...createFunnelProps("ai_setup_selected"), ...props });+ }++ trackBackendFrameworkSelected(props: {+ backend_framework: string;+ backend_framework_source: string;+ }) {+ this.capture("cli_backend_framework_selected", {+ ...createFunnelProps("backend_framework_selected"),+ ...props,+ });+ }++ trackExampleSelected(props: { example: string; example_source: string }) {+ this.capture("cli_example_selected", { ...createFunnelProps("example_selected"), ...props });+ }++ trackEnvResolutionStarted(props: { template?: string; ai_setup?: string; example?: string }) {+ this.capture("cli_env_resolution_started", {+ ...createFunnelProps("env_resolution_started"),+ ...props,+ });+ }++ trackSkillInstalled(props: { skill_installed: boolean }) {+ this.capture("cli_skill_installed", {+ ...createFunnelProps("skill_prompt_resolved"),+ ...props,+ });+ }++ trackImmediateSelected(props: {+ immediate: boolean;+ dependency_install_requested: boolean;+ selection_source: string;+ }) {+ this.capture("cli_immediate_selected", props);+ }++ trackScaffoldStarted(props: { template?: string; ai_setup?: string; example?: string }) {+ this.capture("cli_scaffold_started", { ...createFunnelProps("scaffold_started"), ...props });+ }++ trackScaffoldFailed(props: Record<string, unknown>) {+ this.capture("cli_scaffold_failed", { ...createFunnelProps("scaffold_failed"), ...props });+ }++ trackScaffoldSucceeded(props: { template?: string; ai_setup?: string; example?: string }) {+ this.capture("cli_scaffold_succeeded", {+ ...createFunnelProps("scaffold_succeeded"),+ ...props,+ });+ }++ trackEnvResolved(props: Record<string, unknown>) {+ this.capture("cli_env_resolved", { ...createFunnelProps("env_written"), ...props });+ }++ trackCreateSucceeded(props: Record<string, unknown>) {+ this.capture("cli_create_succeeded", { ...createFunnelProps("create_succeeded"), ...props });+ }++ trackDevCommandSkipped(props: { skip_reason: string; required_env?: string }) {+ this.capture("cli_dev_command_skipped", props);+ }++ trackDevCommandStarted(props: { package_manager: string }) {+ this.capture("cli_dev_command_started", props);+ }++ trackDevCommandStopped(props: {+ package_manager: string;+ duration_ms: number;+ exit_code: number | null;+ failure_signal: NodeJS.Signals | null;+ }) {+ this.capture("cli_dev_command_stopped", props);+ }++ trackDevCommandFailed(props: Record<string, unknown>) {+ this.capture("cli_dev_command_failed", props);+ }++ trackCloudAuthStarted(props: { auth_method?: string }) {+ this.capture("cli_cloud_auth_started", {+ ...createFunnelProps("cloud_auth_started"),+ ...props,+ });+ }++ trackCloudAuthMethod(props: { auth_method: string; auth_succeeded: boolean }) {+ this.capture("cli_cloud_auth_method", {+ ...createFunnelProps("cloud_auth_resolved"),+ ...props,+ });+ }++ trackCloudAuthCancelled(props: Record<string, unknown>) {+ this.capture("cli_cloud_auth_cancelled", {+ ...createFunnelProps("cloud_auth_cancelled"),+ ...props,+ });+ }++ trackCloudAuthFailed(props: Record<string, unknown>) {+ this.capture("cli_cloud_auth_failed", { ...createFunnelProps("cloud_auth_failed"), ...props });+ }++ trackDependencyInstallSkipped(props: { skip_reason: string }) {+ this.capture("cli_dependency_install_skipped", props);+ }++ trackDependencyInstallStarted(props: { template: string; ai_setup: string }) {+ this.capture("cli_dependency_install_started", {+ ...createFunnelProps("dependency_install_started"),+ ...props,+ });+ }++ trackDependencyInstallSucceeded(props: {+ template: string;+ ai_setup: string;+ dependency_installed: boolean;+ }) {+ this.capture("cli_dependency_install_succeeded", {+ ...createFunnelProps("dependency_install_succeeded"),+ ...props,+ });+ }++ trackDependencyInstallCancelled(props: Record<string, unknown>) {+ this.capture("cli_dependency_install_cancelled", {+ ...createFunnelProps("dependency_install_cancelled"),+ ...props,+ });+ }++ trackDependencyInstallFailed(props: Record<string, unknown>) {+ this.capture("cli_dependency_install_failed", {+ ...createFunnelProps("dependency_install_failed"),+ ...props,+ });+ }++ trackSkillInstallStarted(props: { skill_installed: boolean }) {+ this.capture("cli_skill_install_started", {+ ...createFunnelProps("skill_install_started"),+ ...props,+ });+ }++ trackSkillInstallFinished(props: {+ skill_installed: boolean;+ duration_ms: number;+ exit_code: number | null;+ }) {+ this.capture("cli_skill_install_finished", {+ ...createFunnelProps("skill_install_finished"),+ ...props,+ });+ }++ trackSkillInstallCancelled(props: Record<string, unknown>) {+ this.capture("cli_skill_install_cancelled", {+ ...createFunnelProps("skill_install_cancelled"),+ ...props,+ });+ }++ trackSkillInstallFailed(props: Record<string, unknown>) {+ this.capture("cli_skill_install_failed", {+ ...createFunnelProps("skill_install_failed"),+ ...props,+ });+ }++ trackTargetNameRetried(props: { retries: number }) {+ this.capture("cli_target_name_retried", props);+ }++ trackTargetExists(props: {+ interactive: boolean;+ attempt: number;+ exhausted: boolean;+ error_code: string;+ }) {+ this.capture("cli_target_exists", props);+ }+}diff --git a/packages/openui-cli/src/lib/templates-catalog.ts b/packages/openui-cli/src/commands/create/lib/templates-catalog.tssimilarity index 96%rename from packages/openui-cli/src/lib/templates-catalog.tsrename to packages/openui-cli/src/commands/create/lib/templates-catalog.tsindex feb36da32..88999b7e1 100644--- a/packages/openui-cli/src/lib/templates-catalog.ts+++ b/packages/openui-cli/src/commands/create/lib/templates-catalog.ts@@ -1,5 +1,5 @@-import { fetchSourceFile } from "./checkout";-import { CreateError } from "./telemetry";+import { fetchSourceFile } from "../../../lib/checkout";+import { CreateError } from "../../../lib/errors";export const TEMPLATES_CATALOG_PATH = "templates/templates.json";diff --git a/packages/openui-cli/src/commands/create/run.ts b/packages/openui-cli/src/commands/create/run.tsnew file mode 100644index 000000000..cfdeef8f9--- /dev/null+++ b/packages/openui-cli/src/commands/create/run.ts@@ -0,0 +1,275 @@+import * as fs from "node:fs";++import type { CliContext } from "../../lib/context";+import { resolveInstallPackageManager } from "../../lib/detect-package-manager";+import { cliErrorProperties, CreateError, processErrorProperties } from "../../lib/errors";+import { applyScaffoldFiles, resolveTemplateSource } from "../../lib/scaffold";+import { withSpinner } from "../../lib/spinner";+import { runCreateExample } from "./lib/create-example";+import type { CreateAppOptions } from "./lib/create-types";+import { runDevCommand } from "./lib/dev-server";+import {+ buildAppId,+ requiredApiKeyEnv,+ resolveChatEnv,+ resolveCloudEnv,+ writeEnv,+} from "./lib/env";+import { installProjectDependencies, resolveInstallInvocation } from "./lib/install";+import { installRequestedSkill, shouldInstallSkill } from "./lib/install-skill";+import { getStartedMessage } from "./lib/messages";+import type { TemplateOverlay } from "./lib/overlays";+import {+ loadCreateCatalog,+ resolveCreateSelection,+ resolveImmediate,+ resolveProjectIdentity,+} from "./lib/resolve";+import { aiSetupFromTemplate, CreateTelemetryClient } from "./lib/telemetry";+import { findCatalogOverlay } from "./lib/templates-catalog";++export async function runCreateApp(options: CreateAppOptions, ctx: CliContext): Promise<void> {+ const tel = new CreateTelemetryClient(ctx.telemetry);+ const interactive = !options.noInteractive;+ const packageManager = resolveInstallPackageManager();+ const t0 = Date.now();+ tel.registerContext({ interactive, package_manager: packageManager.name });+ tel.trackStarted({+ interactive,+ has_name_arg: Boolean(options.name),+ has_template_arg: Boolean(options.template),+ has_backend_framework_arg: Boolean(options.backendFramework),+ has_example_arg: Boolean(options.example),+ has_api_key_arg: Boolean(options.apiKey),+ has_auth_arg: Boolean(options.auth),+ no_install: Boolean(options.noInstall),+ immediate_arg: options.immediate,+ });++ const catalog = await loadCreateCatalog({+ example: options.example,+ template: options.template,+ backendFramework: options.backendFramework,+ interactive,+ });+ const { name, targetDir } = await resolveProjectIdentity(options.name, interactive, tel);++ const selected = await resolveCreateSelection({+ backendFramework: options.backendFramework,+ example: options.example,+ examples: catalog.examples,+ overlays: catalog.templateEntry?.overlays ?? [],+ interactive,+ });+ if (selected.kind === "example") {+ await runCreateExample({+ options,+ interactive,+ packageManager,+ t0,+ name,+ targetDir,+ example: selected.example,+ tel,+ verbose: ctx.verbose,+ });+ return;+ }++ const template = catalog.template;+ const templateEntry = catalog.templateEntry;+ if (!template || !templateEntry) {+ throw new CreateError(+ "args_resolution",+ "Missing required argument --template",+ "invalid_input",+ "MISSING_REQUIRED_ARG",+ );+ }++ const backendFramework = selected.overlay;+ findCatalogOverlay(templateEntry, backendFramework);++ const aiSetup = aiSetupFromTemplate(template);+ tel.registerContext({ template, ai_setup: aiSetup, backend_framework: backendFramework });+ tel.trackAiSetupSelected({ template, ai_setup: aiSetup });+ tel.trackBackendFrameworkSelected({+ backend_framework: backendFramework,+ backend_framework_source: options.backendFramework+ ? "flag"+ : interactive+ ? "prompt"+ : "default",+ });++ tel.trackEnvResolutionStarted({ template, ai_setup: aiSetup });+ const envResult =+ template === "openui-self-hosted"+ ? await resolveChatEnv(interactive)+ : await resolveCloudEnv(name, options, interactive, tel);++ const installSkill = await shouldInstallSkill(options.skill, interactive);+ tel.trackSkillInstalled({ skill_installed: installSkill });++ const immediateResolution = resolveImmediate(options.immediate, options.noInstall, interactive);+ const apiKeyEnv = requiredApiKeyEnv(template);+ const apiKeyAvailable = envResult.envWritten || Boolean(process.env[apiKeyEnv]?.trim());+ const devStartBlockedByMissingApiKey = immediateResolution.immediate && !apiKeyAvailable;+ tel.trackImmediateSelected({+ immediate: immediateResolution.immediate,+ dependency_install_requested: immediateResolution.installDependencies,+ selection_source: immediateResolution.source,+ });++ let overlay: TemplateOverlay | undefined;+ const runScaffold = async () => {+ const { dir: templateDir } = await resolveTemplateSource(template);+ tel.trackScaffoldStarted({ template, ai_setup: aiSetup });+ try {+ overlay = applyScaffoldFiles({+ templateDir,+ targetDir,+ name,+ packageManager: packageManager.name,+ backendFramework,+ });+ await writeEnv(+ targetDir,+ envResult,+ template === "openui-cloud" ? buildAppId(name) : undefined,+ );+ } catch (err) {+ const properties = cliErrorProperties(err, {+ failure_stage: "scaffold",+ error_class: "filesystem",+ error_code: "SCAFFOLD_FAILED",+ });+ tel.trackScaffoldFailed({ template, ai_setup: aiSetup, ...properties });+ throw new CreateError(+ properties.failure_stage,+ err instanceof Error ? err.message : String(err),+ properties.error_class,+ properties.error_code,+ );+ } finally {+ fs.rmSync(templateDir, { recursive: true, force: true });+ }+ };++ console.info();+ if (ctx.verbose) {+ console.info(`Scaffolding ${template} into "${name}"...\n`);+ await runScaffold();+ } else {+ await withSpinner("Scaffolding...", runScaffold);+ console.info("✓ Scaffolded");+ }+ tel.trackScaffoldSucceeded({ template, ai_setup: aiSetup });+ tel.trackEnvResolved({+ template,+ ai_setup: aiSetup,+ env_written: envResult.envWritten,+ auth_method: envResult.authMethod,+ auth_succeeded: envResult.authSucceeded,+ });++ const { installCmd, installArgs } = resolveInstallInvocation({+ backendFramework,+ packageManager,+ targetDir,+ });+ const dependencyInstalled = await installProjectDependencies({+ tel,+ verbose: ctx.verbose,+ targetDir,+ template,+ aiSetup,+ packageManager,+ installCmd,+ installArgs,+ installDependencies: immediateResolution.installDependencies,+ });++ const skillInstalled = await installRequestedSkill({+ enabled: installSkill,+ verbose: ctx.verbose,+ targetDir,+ tel,+ });++ const devCmd = packageManager.runCmd;+ const startDev =+ immediateResolution.immediate && dependencyInstalled && !devStartBlockedByMissingApiKey;++ tel.trackCreateSucceeded({+ template,+ ai_setup: aiSetup,+ duration_ms: Date.now() - t0,+ skill_installed: skillInstalled,+ env_written: envResult.envWritten,+ dependency_installed: dependencyInstalled,+ });+ console.info(+ getStartedMessage({+ name,+ devCmd,+ template,+ backendGettingStarted: overlay?.manifest.gettingStarted,+ skillInstalled,+ envWritten: envResult.envWritten,+ startDev,+ installCmd,+ dependencyInstalled,+ }),+ );++ if (devStartBlockedByMissingApiKey) {+ tel.trackDevCommandSkipped({+ skip_reason: "missing_api_key",+ required_env: apiKeyEnv,+ });+ return;+ }++ if (!startDev) {+ tel.trackDevCommandSkipped({+ skip_reason: options.noInstall ? "dependencies_not_installed" : "not_immediate",+ });+ return;+ }++ tel.trackDevCommandStarted({+ package_manager: packageManager.name,+ });+ const devResult = await runDevCommand(devCmd, targetDir);+ const stoppedNormally =+ devResult.status === 0 ||+ devResult.status === 130 ||+ devResult.status === 143 ||+ devResult.signal === "SIGINT" ||+ devResult.signal === "SIGTERM";++ if (stoppedNormally) {+ tel.trackDevCommandStopped({+ package_manager: packageManager.name,+ duration_ms: devResult.durationMs,+ exit_code: devResult.status,+ failure_signal: devResult.signal,+ });+ } else {+ const exitCode = devResult.status ?? 1;+ const properties = processErrorProperties(devResult, "dev_server", {+ error_class: "process",+ error_code: "NONZERO_EXIT",+ });+ tel.trackDevCommandFailed({+ package_manager: packageManager.name,+ failure_reason: devResult.error ? "spawn_error" : "nonzero_exit",+ ...properties,+ });+ console.error(+ `\nDevelopment server exited. Retry with:\n\n> cd ${name}\n> ${devCmd} run dev\n`,+ );+ process.exitCode = exitCode;+ }+}diff --git a/packages/openui-cli/src/commands/deploy/command.ts b/packages/openui-cli/src/commands/deploy/command.tsnew file mode 100644index 000000000..2ca06071b--- /dev/null+++ b/packages/openui-cli/src/commands/deploy/command.ts@@ -0,0 +1,52 @@+import { Command } from "commander";++import { context } from "../../lib/context";++import { runDeploy } from "./run";++export const deployCommand = new Command("deploy")+ .description("Deploy an OpenUI project")+ .usage("[dir] [options]")+ .argument("[dir]", "Project directory (default: current directory)")+ .option("-y, --yes", "Skip confirmation prompts")+ .option("--skip-env", "Do not pass or save local .env values")+ .option("--no-interactive", "Skip prompts (implies --yes)")+ .allowUnknownOption()+ .allowExcessArguments()+ .addHelpText(+ "after",+ `+Default supported platform is Vercel. If you are not logged in to the platform,+opens vercel login first. Links the project when needed, then offers to save+missing allowlisted keys from .env / .env.local to the project on the platform+(auto-accepted with --yes). Build logs are hidden by default; pass --verbose+to stream them. On failure the log tail is printed. Extra flags after deploy+are forwarded as-is to the target platform, which validates them.++Examples:+ openui deploy+ openui deploy --verbose+`,+ )+ .action(+ async (+ dir: string | undefined,+ options: {+ yes?: boolean;+ skipEnv?: boolean;+ interactive: boolean;+ },+ command: Command,+ ) => {+ await runDeploy(+ {+ dir,+ yes: options.yes,+ skipEnv: options.skipEnv,+ noInteractive: !options.interactive,+ extraArgs: command.args,+ },+ context,+ );+ },+ );diff --git a/packages/openui-cli/src/lib/cli-bin.ts b/packages/openui-cli/src/commands/deploy/lib/cli-bin.tssimilarity index 96%rename from packages/openui-cli/src/lib/cli-bin.tsrename to packages/openui-cli/src/commands/deploy/lib/cli-bin.tsindex 678fb97d4..03ed02db8 100644--- a/packages/openui-cli/src/lib/cli-bin.ts+++ b/packages/openui-cli/src/commands/deploy/lib/cli-bin.ts@@ -1,7 +1,7 @@import * as fs from "node:fs";import * as path from "node:path";-import { resolveDlxInvocation } from "./detect-package-manager";+import { resolveDlxInvocation } from "../../../lib/detect-package-manager";/** How a third-party CLI binary was resolved for spawn. */export type CliInvocation = {diff --git a/packages/openui-cli/src/lib/deploy/index.ts b/packages/openui-cli/src/commands/deploy/lib/index.tssimilarity index 100%rename from packages/openui-cli/src/lib/deploy/index.tsrename to packages/openui-cli/src/commands/deploy/lib/index.tsdiff --git a/packages/openui-cli/src/lib/deploy/project-env.ts b/packages/openui-cli/src/commands/deploy/lib/project-env.tssimilarity index 94%rename from packages/openui-cli/src/lib/deploy/project-env.tsrename to packages/openui-cli/src/commands/deploy/lib/project-env.tsindex 446d75127..3c502fd8f 100644--- a/packages/openui-cli/src/lib/deploy/project-env.ts+++ b/packages/openui-cli/src/commands/deploy/lib/project-env.ts@@ -1,4 +1,4 @@-import { loadAllowlistedProjectEnv } from "../env";+import { loadAllowlistedProjectEnv } from "../../../lib/env";/** Known OpenUI template env keys. Values must never be logged or sent to telemetry. */export const DEPLOY_ENV_ALLOWLIST = [diff --git a/packages/openui-cli/src/lib/deploy/project.ts b/packages/openui-cli/src/commands/deploy/lib/project.tssimilarity index 72%rename from packages/openui-cli/src/lib/deploy/project.tsrename to packages/openui-cli/src/commands/deploy/lib/project.tsindex 8c88486b8..a2362b93b 100644--- a/packages/openui-cli/src/lib/deploy/project.ts+++ b/packages/openui-cli/src/commands/deploy/lib/project.ts@@ -1,7 +1,7 @@import * as fs from "node:fs";import * as path from "node:path";-import { CreateError } from "../telemetry";+import { CreateError } from "../../../lib/errors";type ProjectPackageJson = {name?: string;@@ -34,14 +34,3 @@ export function readProjectDependencies(projectDir: string): Record<string, striexport function hasOpenUiPackages(deps: Record<string, string>): boolean {return Object.keys(deps).some((name) => name.startsWith("@openuidev/"));}--/** Require an OpenUI app (any `@openuidev/*` dependency). */-export function assertOpenUiProject(projectDir: string): void {- if (hasOpenUiPackages(readProjectDependencies(projectDir))) return;- throw new CreateError(- "args_resolution",- "Not an OpenUI project. Run this from an OpenUI app, or pass its directory.",- "invalid_input",- "NOT_OPENUI_PROJECT",- );-}diff --git a/packages/openui-cli/src/lib/deploy/prompt.ts b/packages/openui-cli/src/commands/deploy/lib/prompt.tssimilarity index 94%rename from packages/openui-cli/src/lib/deploy/prompt.tsrename to packages/openui-cli/src/commands/deploy/lib/prompt.tsindex 7a72d3486..36047ebdc 100644--- a/packages/openui-cli/src/lib/deploy/prompt.ts+++ b/packages/openui-cli/src/commands/deploy/lib/prompt.ts@@ -1,4 +1,4 @@-import { CliCancelledError } from "../telemetry";+import { CliCancelledError } from "../../../lib/errors";/** True when stdin/stdout are TTYs and `--no-interactive` was not passed. */export function canPromptInteractive(noInteractive = false): boolean {diff --git a/packages/openui-cli/src/lib/deploy/quiet.ts b/packages/openui-cli/src/commands/deploy/lib/quiet.tssimilarity index 100%rename from packages/openui-cli/src/lib/deploy/quiet.tsrename to packages/openui-cli/src/commands/deploy/lib/quiet.tsdiff --git a/packages/openui-cli/src/lib/deploy-targets/index.ts b/packages/openui-cli/src/commands/deploy/lib/targets/index.tssimilarity index 82%rename from packages/openui-cli/src/lib/deploy-targets/index.tsrename to packages/openui-cli/src/commands/deploy/lib/targets/index.tsindex d34fb2f15..0bea5a4db 100644--- a/packages/openui-cli/src/lib/deploy-targets/index.ts+++ b/packages/openui-cli/src/commands/deploy/lib/targets/index.ts@@ -1,5 +1,5 @@-import type { DeployTarget, DeployTargetOptions } from "../deploy";-import { CreateError } from "../telemetry";+import type { DeployTarget, DeployTargetOptions } from "..";+import { CreateError } from "../../../../lib/errors";import { deployToVercel } from "./vercel";/** Dispatch to a platform adapter (Vercel today). */diff --git a/packages/openui-cli/src/lib/deploy-targets/vercel/args.ts b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/args.tssimilarity index 100%rename from packages/openui-cli/src/lib/deploy-targets/vercel/args.tsrename to packages/openui-cli/src/commands/deploy/lib/targets/vercel/args.tsdiff --git a/packages/openui-cli/src/lib/deploy-targets/vercel/connect.ts b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/connect.tssimilarity index 92%rename from packages/openui-cli/src/lib/deploy-targets/vercel/connect.tsrename to packages/openui-cli/src/commands/deploy/lib/targets/vercel/connect.tsindex c868c9302..a6a903a22 100644--- a/packages/openui-cli/src/lib/deploy-targets/vercel/connect.ts+++ b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/connect.ts@@ -1,15 +1,15 @@import * as fs from "node:fs";import * as path from "node:path";+import { loadAllowlistedProjectEnv } from "../../../../../lib/env";+import { CreateError, throwCommandFailure } from "../../../../../lib/errors";+import { mutedNpmEnv, runCommand } from "../../../../../lib/process-runner";+import { withSpinner } from "../../../../../lib/spinner";import type { CliInvocation } from "../../cli-bin";-import { readProjectPackageJson } from "../../deploy/project";-import { canPromptInteractive } from "../../deploy/prompt";-import type { DeployTargetOptions } from "../../deploy/types";-import { adoptVercelEnvVars, loadAllowlistedProjectEnv } from "../../env";-import { mutedNpmEnv, runCommand } from "../../process-runner";-import { withSpinner } from "../../spinner";-import { CreateError } from "../../telemetry";-import { throwCommandFailure } from "../../utils";+import { readProjectPackageJson } from "../../project";+import { canPromptInteractive } from "../../prompt";+import type { DeployTargetOptions } from "../../types";+import { adoptVercelEnvVars } from "../../vercel-env";import { vercelLinkScopeArgs, vercelSpawnArgs } from "./args";/** Auth vars Vercel CLI reads. OpenUI apps keep these in `.env`; Vercel often writes `.env.local`. */diff --git a/packages/openui-cli/src/lib/deploy-targets/vercel/index.ts b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/index.tssimilarity index 92%rename from packages/openui-cli/src/lib/deploy-targets/vercel/index.tsrename to packages/openui-cli/src/commands/deploy/lib/targets/vercel/index.tsindex 7666dd16f..b06db0e17 100644--- a/packages/openui-cli/src/lib/deploy-targets/vercel/index.ts+++ b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/index.ts@@ -1,15 +1,14 @@-import { formatCliCommand, resolveCliInvocation } from "../../cli-bin";-import { printLogTail } from "../../command-output";import {loadProjectDeployEnv,loadProjectDeployFileEnv,printQuietDeploySuccess,type DeployTargetOptions,-} from "../../deploy";-import { adoptVercelEnvVars } from "../../env";-import { runCommand, runQuietCommand } from "../../process-runner";-import { telemetry } from "../../telemetry";-import { throwCommandFailure } from "../../utils";+} from "../..";+import { printLogTail } from "../../../../../lib/command-output";+import { throwCommandFailure } from "../../../../../lib/errors";+import { runCommand, runQuietCommand } from "../../../../../lib/process-runner";+import { formatCliCommand, resolveCliInvocation } from "../../cli-bin";+import { adoptVercelEnvVars } from "../../vercel-env";import { buildVercelDeployArgs, publicVercelArgs, vercelSpawnArgs } from "./args";import {isVercelLinked,@@ -107,7 +106,7 @@ export async function deployToVercel(opts: DeployTargetOptions): Promise<void> {noWait,);}- telemetry.capture("cli_deploy_succeeded", {+ opts.tel.trackSucceeded({target: "vercel",prod: opts.prod,yes: opts.yes,diff --git a/packages/openui-cli/src/lib/deploy-targets/vercel/project-env.ts b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/project-env.tssimilarity index 96%rename from packages/openui-cli/src/lib/deploy-targets/vercel/project-env.tsrename to packages/openui-cli/src/commands/deploy/lib/targets/vercel/project-env.tsindex 7b3b517e5..d9b670bfa 100644--- a/packages/openui-cli/src/lib/deploy-targets/vercel/project-env.ts+++ b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/project-env.ts@@ -1,7 +1,7 @@+import { runCommand } from "../../../../../lib/process-runner";import type { CliInvocation } from "../../cli-bin";-import { SENSITIVE_DEPLOY_ENV_KEYS } from "../../deploy/project-env";-import { canPromptInteractive, confirmOrDefault } from "../../deploy/prompt";-import { runCommand } from "../../process-runner";+import { SENSITIVE_DEPLOY_ENV_KEYS } from "../../project-env";+import { canPromptInteractive, confirmOrDefault } from "../../prompt";import { vercelSpawnArgs } from "./args";import { isVercelLinked, vercelCliEnv } from "./connect";diff --git a/packages/openui-cli/src/lib/deploy-targets/vercel/summary.ts b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/summary.tssimilarity index 95%rename from packages/openui-cli/src/lib/deploy-targets/vercel/summary.tsrename to packages/openui-cli/src/commands/deploy/lib/targets/vercel/summary.tsindex cde41aa93..280adbf9e 100644--- a/packages/openui-cli/src/lib/deploy-targets/vercel/summary.ts+++ b/packages/openui-cli/src/commands/deploy/lib/targets/vercel/summary.ts@@ -1,4 +1,4 @@-import type { DeploySuccessSummary } from "../../deploy/quiet";+import type { DeploySuccessSummary } from "../../quiet";/** Parse the stable alias, unique deployment URL, and inspect link from `vercel` output. */export function extractVercelDeploymentSummary(log: string): DeploySuccessSummary {diff --git a/packages/openui-cli/src/commands/deploy/lib/telemetry.ts b/packages/openui-cli/src/commands/deploy/lib/telemetry.tsnew file mode 100644index 000000000..f08fd9b1e--- /dev/null+++ b/packages/openui-cli/src/commands/deploy/lib/telemetry.ts@@ -0,0 +1,28 @@+import { Telemetry } from "../../../lib/telemetry";++export class DeployTelemetryClient extends Telemetry {+ registerContext(props: Record<string, unknown>) {+ this.register(props);+ }++ trackStarted(props: {+ target: string;+ prod: boolean;+ yes: boolean;+ skip_env: boolean;+ verbose: boolean;+ interactive: boolean;+ is_openui_project: boolean;+ has_dir_arg: boolean;+ }) {+ this.capture("cli_deploy_started", props);+ }++ trackNonOpenUiProject() {+ this.capture("cli_deploy_non_openui_project");+ }++ trackSucceeded(props: Record<string, unknown>) {+ this.capture("cli_deploy_succeeded", props);+ }+}diff --git a/packages/openui-cli/src/lib/deploy/types.ts b/packages/openui-cli/src/commands/deploy/lib/types.tssimilarity index 82%rename from packages/openui-cli/src/lib/deploy/types.tsrename to packages/openui-cli/src/commands/deploy/lib/types.tsindex 8342eb4f4..e6d685eb6 100644--- a/packages/openui-cli/src/lib/deploy/types.ts+++ b/packages/openui-cli/src/commands/deploy/lib/types.ts@@ -1,3 +1,5 @@+import type { DeployTelemetryClient } from "./telemetry";+/** Shared options every deploy target receives from `openui deploy`. */export type DeployTargetOptions = {projectDir: string;@@ -7,6 +9,7 @@ export type DeployTargetOptions = {skipEnv: boolean;noInteractive: boolean;verbose: boolean;+ tel: DeployTelemetryClient;};export const DEPLOY_TARGETS = ["vercel"] as const;diff --git a/packages/openui-cli/src/commands/deploy/lib/vercel-env.ts b/packages/openui-cli/src/commands/deploy/lib/vercel-env.tsnew file mode 100644index 000000000..fcafc67e2--- /dev/null+++ b/packages/openui-cli/src/commands/deploy/lib/vercel-env.ts@@ -0,0 +1,39 @@+import * as fs from "node:fs";+import * as path from "node:path";++import { DEFAULT_ENV_FILE, parseEnvFile, removeEnvVar, upsertEnvVar } from "../../../lib/env";++const VERCEL_WRITTEN_ENV_KEYS = [+ "VERCEL_TOKEN",+ "VERCEL_OIDC_TOKEN",+ "VERCEL_ORG_ID",+ "VERCEL_PROJECT_ID",+] as const;++/** `.env` when it already exists (OpenUI default); otherwise `.env.local`. */+function resolveProjectEnvFileName(projectDir: string): string {+ return fs.existsSync(path.join(projectDir, DEFAULT_ENV_FILE)) ? DEFAULT_ENV_FILE : ".env.local";+}++/**+ * Vercel always writes `.env.local`. If the project already has `.env`, move+ * those Vercel keys there and drop an emptied `.env.local`.+ */+export function adoptVercelEnvVars(projectDir: string): void {+ const targetName = resolveProjectEnvFileName(projectDir);+ if (targetName === ".env.local") return;+ const localPath = path.join(projectDir, ".env.local");+ if (!fs.existsSync(localPath)) return;++ const fromLocal = parseEnvFile(localPath);+ const targetPath = path.join(projectDir, targetName);+ for (const key of VERCEL_WRITTEN_ENV_KEYS) {+ const value = fromLocal[key]?.trim();+ if (!value || /[\r\n]/.test(value)) continue;+ upsertEnvVar(targetPath, key, value);+ removeEnvVar(localPath, key);+ }+ if (fs.existsSync(localPath) && fs.readFileSync(localPath, "utf8").trim() === "") {+ fs.unlinkSync(localPath);+ }+}diff --git a/packages/openui-cli/src/commands/deploy.ts b/packages/openui-cli/src/commands/deploy/run.tssimilarity index 70%rename from packages/openui-cli/src/commands/deploy.tsrename to packages/openui-cli/src/commands/deploy/run.tsindex 3d618bd5e..9bceff0ad 100644--- a/packages/openui-cli/src/commands/deploy.ts+++ b/packages/openui-cli/src/commands/deploy/run.ts@@ -1,14 +1,17 @@import * as fs from "node:fs";import * as path from "node:path";+import type { CliContext } from "../../lib/context";+import { resolveInstallPackageManager } from "../../lib/detect-package-manager";+import { CreateError } from "../../lib/errors";import {- assertOpenUiProject,DEFAULT_DEPLOY_TARGET,+ hasOpenUiPackages,+ readProjectDependencies,type DeployTargetOptions,-} from "../lib/deploy";-import { deployToTarget } from "../lib/deploy-targets";-import { resolveInstallPackageManager } from "../lib/detect-package-manager";-import { CreateError, telemetry } from "../lib/telemetry";+} from "./lib";+import { deployToTarget } from "./lib/targets";+import { DeployTelemetryClient } from "./lib/telemetry";/** OpenUI-only flags. Everything else is forwarded for the target CLI to validate. */const OWN_FLAGS = new Set(["--skip-env", "--no-interactive", "--verbose"]);@@ -18,7 +21,6 @@ export type DeployOptions = {yes?: boolean;skipEnv?: boolean;noInteractive?: boolean;- verbose?: boolean;extraArgs?: string[];};@@ -28,9 +30,10 @@ type ResolvedDeploy = {};/** Resolve flags, validate the project dir, then hand off to the deploy target. */-export async function runDeploy(options: DeployOptions): Promise<void> {+export async function runDeploy(options: DeployOptions, ctx: CliContext): Promise<void> {+ const tel = new DeployTelemetryClient(ctx.telemetry);const resolved = resolveDeployInvocation(options);- const projectDir = resolveProjectDir(resolved.projectDir);+ const projectDir = resolveProjectDir(resolved.projectDir, ctx.cwd);const extraArgs = resolved.extraArgs.filter((arg) => arg !== "--verbose");const prod = extraArgs.includes("--prod");const yes =@@ -39,7 +42,9 @@ export async function runDeploy(options: DeployOptions): Promise<void> {extraArgs.includes("--yes") ||extraArgs.includes("-y");const skipEnv = Boolean(options.skipEnv);- const verbose = Boolean(options.verbose) || (options.extraArgs ?? []).includes("--verbose");+ const verbose = ctx.verbose || (options.extraArgs ?? []).includes("--verbose");+ const interactive = !options.noInteractive;+ const isOpenUiProject = hasOpenUiPackages(readProjectDependencies(projectDir));const targetOpts: DeployTargetOptions = {projectDir,@@ -49,15 +54,23 @@ export async function runDeploy(options: DeployOptions): Promise<void> {skipEnv,noInteractive: Boolean(options.noInteractive),verbose,+ tel,};- telemetry.register({ package_manager: resolveInstallPackageManager().name });- telemetry.capture("cli_deploy_started", {+ tel.registerContext({+ interactive,+ is_openui_project: isOpenUiProject,+ package_manager: resolveInstallPackageManager().name,+ });+ if (!isOpenUiProject) tel.trackNonOpenUiProject();+ tel.trackStarted({target: DEFAULT_DEPLOY_TARGET,prod,yes,skip_env: skipEnv,verbose,+ interactive,+ is_openui_project: isOpenUiProject,has_dir_arg: Boolean(resolved.projectDir),});@@ -93,8 +106,8 @@ function unsetIfFlag(value?: string): string | undefined {}/** Resolve and require a directory that contains package.json. */-function resolveProjectDir(dir?: string): string {- const projectDir = path.resolve(process.cwd(), dir ?? ".");+function resolveProjectDir(dir: string | undefined, cwd: string): string {+ const projectDir = path.resolve(cwd, dir ?? ".");if (!fs.existsSync(projectDir)) {throw new CreateError("args_resolution",@@ -114,11 +127,10 @@ function resolveProjectDir(dir?: string): string {if (!fs.existsSync(path.join(projectDir, "package.json"))) {throw new CreateError("args_resolution",- `No package.json in ${projectDir}. Run this from an OpenUI project, or pass its directory.`,+ `No package.json in ${projectDir}. Run this from a project, or pass its directory.`,"invalid_input","PROJECT_NOT_FOUND",);}- assertOpenUiProject(projectDir);return projectDir;}diff --git a/packages/openui-cli/src/commands/generate-api-key/command.ts b/packages/openui-cli/src/commands/generate-api-key/command.tsnew file mode 100644index 000000000..be743aa21--- /dev/null+++ b/packages/openui-cli/src/commands/generate-api-key/command.ts@@ -0,0 +1,31 @@+import { Command } from "commander";++import { context } from "../../lib/context";+import { DEFAULT_ENV_FILE } from "../../lib/env";++import { runGenerateApiKey } from "./run";++export const generateApiKeyCommand = new Command("generate-api-key")+ .description("Mint an OpenUI Gateway API key and write it to a project env file")+ .option("-f, --file <path>", "Env file to write", DEFAULT_ENV_FILE)+ .option(+ "-k, --key <name>",+ "Environment variable name (letters, digits, underscores)",+ "THESYS_API_KEY",+ )+ .option("-n, --name <string>", "Name of the minted key in the Thesys console")+ .addHelpText(+ "after",+ `+Run this inside an existing project. It uses the same browser sign-in as+openui create, mints an OpenUI Gateway API key, and writes it to the env file.++Examples:+ openui generate-api-key+ openui generate-api-key --file .env.local+ openui generate-api-key --file .env.local --key THESYS_API_KEY+`,+ )+ .action(async (options: { file?: string; key?: string; name?: string }) => {+ await runGenerateApiKey(options, context);+ });diff --git a/packages/openui-cli/src/commands/generate-api-key/lib/telemetry.ts b/packages/openui-cli/src/commands/generate-api-key/lib/telemetry.tsnew file mode 100644index 000000000..dae78db9f--- /dev/null+++ b/packages/openui-cli/src/commands/generate-api-key/lib/telemetry.ts@@ -0,0 +1,16 @@+import { Telemetry } from "../../../lib/telemetry";++export class GenerateApiKeyTelemetryClient extends Telemetry {+ trackStarted(props: { env_file: string; env_key: string }) {+ this.capture("cli_generate_api_key_started", props);+ }++ trackSucceeded(props: {+ auth_method: string;+ env_file: string;+ env_key: string;+ duration_ms: number;+ }) {+ this.capture("cli_generate_api_key_succeeded", props);+ }+}diff --git a/packages/openui-cli/src/commands/generate-api-key.ts b/packages/openui-cli/src/commands/generate-api-key/run.tssimilarity index 50%rename from packages/openui-cli/src/commands/generate-api-key.tsrename to packages/openui-cli/src/commands/generate-api-key/run.tsindex 07c2b0aec..e790cfb7b 100644--- a/packages/openui-cli/src/commands/generate-api-key.ts+++ b/packages/openui-cli/src/commands/generate-api-key/run.ts@@ -1,9 +1,11 @@import * as fs from "node:fs";import * as path from "node:path";-import { assertValidApiKeyName, mintCloudApiKey } from "../auth/mint";-import { assertValidEnvVarName, DEFAULT_ENV_FILE, upsertEnvVar } from "../lib/env";-import { telemetry } from "../lib/telemetry";+import { assertValidApiKeyName, mintCloudApiKey } from "../../lib/auth/mint";+import { AuthTelemetryClient } from "../../lib/auth/telemetry";+import type { CliContext } from "../../lib/context";+import { assertValidEnvVarName, DEFAULT_ENV_FILE, upsertEnvVar } from "../../lib/env";+import { GenerateApiKeyTelemetryClient } from "./lib/telemetry";export interface GenerateApiKeyOptions {file?: string;@@ -13,42 +15,47 @@ export interface GenerateApiKeyOptions {const DEFAULT_ENV_KEY = "THESYS_API_KEY";-function resolveProjectName(explicit?: string): string {+function resolveProjectName(explicit: string | undefined, cwd: string): string {const trimmed = explicit?.trim();if (trimmed) return trimmed;try {- const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8")) as {+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8")) as {name?: unknown;};if (typeof pkg.name === "string" && pkg.name.trim()) return pkg.name.trim();} catch {/* no package.json, or it isn't valid JSON */}- return path.basename(process.cwd()) || "OpenUI Cloud App";+ return path.basename(cwd) || "OpenUI Cloud App";}-export async function runGenerateApiKey(options: GenerateApiKeyOptions): Promise<void> {+export async function runGenerateApiKey(+ options: GenerateApiKeyOptions,+ ctx: CliContext,+): Promise<void> {+ const tel = new GenerateApiKeyTelemetryClient(ctx.telemetry);+ const authTel = new AuthTelemetryClient(ctx.telemetry);const t0 = Date.now();const file = options.file?.trim() || DEFAULT_ENV_FILE;const envKey = options.key?.trim() || DEFAULT_ENV_KEY;- const projectName = resolveProjectName(options.name);+ const projectName = resolveProjectName(options.name, ctx.cwd);assertValidEnvVarName(envKey, "--key");if (options.name?.trim()) assertValidApiKeyName(projectName);- telemetry.capture("cli_generate_api_key_started", {+ tel.trackStarted({env_file: path.basename(file),env_key: envKey,});- const apiKey = await mintCloudApiKey(projectName);+ const apiKey = await mintCloudApiKey(projectName, authTel);- const filePath = path.resolve(process.cwd(), file);+ const filePath = path.resolve(ctx.cwd, file);upsertEnvVar(filePath, envKey, apiKey);- const displayPath = path.relative(process.cwd(), filePath) || file;+ const displayPath = path.relative(ctx.cwd, filePath) || file;console.info(`✅ ${envKey} written to ${displayPath}`);- telemetry.capture("cli_generate_api_key_succeeded", {+ tel.trackSucceeded({auth_method: "oauth",env_file: path.basename(file),env_key: envKey,diff --git a/packages/openui-cli/src/commands/generate/command.ts b/packages/openui-cli/src/commands/generate/command.tsnew file mode 100644index 000000000..4a6ab91da--- /dev/null+++ b/packages/openui-cli/src/commands/generate/command.ts@@ -0,0 +1,40 @@+import { Command } from "commander";++import { context } from "../../lib/context";+import { resolveArgs } from "../../lib/resolve-args";++import { type GenerateOptions, runGenerate } from "./run";++export const generateCommand = new Command("generate")+ .description("Generate the system prompt + serialized spec from a library definition")+ .argument("[entry]", "Path to a file that exports a createLibrary() result")+ .option(+ "-o, --out <file>",+ "Write the prompt to a file; the spec JSON lands alongside with .spec.json extension",+ )+ .option(+ "--json-schema",+ "Output JSON schema with component signatures for standalone prompt generation",+ )+ .option("--spec", "Generate a serialized library spec JSON (signatures, groups, JSON schema)")+ .option("--export <name>", "Name of the export to use (auto-detected by default)")+ .option(+ "--prompt-options <name>",+ "Name of the PromptOptions export to use (auto-detected by default)",+ )+ .option("--no-interactive", "Fail with error if required args are missing")+ .action(async (entry: string | undefined, options: GenerateOptions) => {+ const args = await resolveArgs(+ {+ entry: entry+ ? { value: entry }+ : {+ prompt: { type: "input", message: "Entry file path?" },+ required: true,+ },+ },+ options.interactive,+ );++ await runGenerate((args as { entry: string }).entry, options, context);+ });diff --git a/packages/openui-cli/src/commands/generate/lib/delimiter.ts b/packages/openui-cli/src/commands/generate/lib/delimiter.tsnew file mode 100644index 000000000..be1dd0396--- /dev/null+++ b/packages/openui-cli/src/commands/generate/lib/delimiter.ts@@ -0,0 +1,3 @@+/** ASCII Record Separator — Untypeable in prompt text and always+ * escaped by JSON.stringify, so it can never collide with either artifact. */+export const SEPARATION_DELIMITER = "\u001E";diff --git a/packages/openui-cli/src/commands/generate/lib/telemetry.ts b/packages/openui-cli/src/commands/generate/lib/telemetry.tsnew file mode 100644index 000000000..7cad1bba1--- /dev/null+++ b/packages/openui-cli/src/commands/generate/lib/telemetry.ts@@ -0,0 +1,16 @@+import { Telemetry } from "../../../lib/telemetry";++export class GenerateTelemetryClient extends Telemetry {+ trackStarted(props: { json_schema: boolean; spec: boolean; out_to_file: boolean }) {+ this.capture("cli_generate_started", props);+ }++ trackSucceeded(props: {+ json_schema: boolean;+ spec: boolean;+ out_to_file: boolean;+ duration_ms: number;+ }) {+ this.capture("cli_generate_succeeded", props);+ }+}diff --git a/packages/openui-cli/src/commands/generate-worker.ts b/packages/openui-cli/src/commands/generate/lib/worker.tssimilarity index 98%rename from packages/openui-cli/src/commands/generate-worker.tsrename to packages/openui-cli/src/commands/generate/lib/worker.tsindex 58a677512..1a1a8bbd6 100644--- a/packages/openui-cli/src/commands/generate-worker.ts+++ b/packages/openui-cli/src/commands/generate/lib/worker.ts@@ -6,7 +6,7 @@** argv: [entryPath, exportName?, "--json-schema"?, "--spec"?, "--prompt-options", name?]* stdout: one artifact for the mode flags; default emits BOTH the prompt and- * the spec JSON, joined by SEPARATION_DELIMITER (generate.ts splits them).+ * the spec JSON, joined by SEPARATION_DELIMITER (run.ts splits them).*/import * as fs from "fs";@@ -14,7 +14,7 @@ import * as os from "os";import * as path from "path";import * as esbuild from "esbuild";-import { SEPARATION_DELIMITER } from "../lib/utils";+import { SEPARATION_DELIMITER } from "./delimiter";// ── Main ──diff --git a/packages/openui-cli/src/commands/generate.ts b/packages/openui-cli/src/commands/generate/run.tssimilarity index 81%rename from packages/openui-cli/src/commands/generate.tsrename to packages/openui-cli/src/commands/generate/run.tsindex 7a0fb358b..568cf4855 100644--- a/packages/openui-cli/src/commands/generate.ts+++ b/packages/openui-cli/src/commands/generate/run.ts@@ -1,9 +1,11 @@import { execFileSync } from "child_process";import * as fs from "fs";import * as path from "path";-import { SEPARATION_DELIMITER } from "../lib/utils";-import { CreateError, telemetry } from "../lib/telemetry";+import type { CliContext } from "../../lib/context";+import { CreateError } from "../../lib/errors";+import { SEPARATION_DELIMITER } from "./lib/delimiter";+import { GenerateTelemetryClient } from "./lib/telemetry";export interface GenerateOptions {out?: string;@@ -17,20 +19,22 @@ export interface GenerateOptions {export async function runGenerate(entry: string,options: Omit<GenerateOptions, "interactive">,+ ctx: CliContext,): Promise<void> {+ const tel = new GenerateTelemetryClient(ctx.telemetry);const t0 = Date.now();- telemetry.capture("cli_generate_started", {+ tel.trackStarted({json_schema: !!options.jsonSchema,spec: !!options.spec,out_to_file: !!options.out,});- const entryPath = path.resolve(process.cwd(), entry);+ const entryPath = path.resolve(ctx.cwd, entry);if (!fs.existsSync(entryPath)) {throw new CreateError("generate_entry_missing", `File not found: ${entryPath}`);}- const workerPath = path.join(__dirname, "generate-worker.js");+ const workerPath = path.join(__dirname, "lib", "worker.js");const workerArgs = [workerPath, entryPath];if (options.export) workerArgs.push(options.export);@@ -42,7 +46,7 @@ export async function runGenerate(try {output = execFileSync(process.execPath, workerArgs, {encoding: "utf-8",- cwd: process.cwd(),+ cwd: ctx.cwd,stdio: ["inherit", "pipe", "inherit"],});} catch (err) {@@ -51,7 +55,7 @@ export async function runGenerate(if (options.jsonSchema || options.spec) {if (options.out) {- const outPath = path.resolve(process.cwd(), options.out);+ const outPath = path.resolve(ctx.cwd, options.out);fs.mkdirSync(path.dirname(outPath), { recursive: true });fs.writeFileSync(outPath, output + "\n");console.info(`Written to ${outPath}`);@@ -65,7 +69,7 @@ export async function runGenerate(// Without `--out` both go to stdout.const [prompt = "", specJson = ""] = output.split(SEPARATION_DELIMITER);if (options.out) {- const promptPath = path.resolve(process.cwd(), options.out);+ const promptPath = path.resolve(ctx.cwd, options.out);fs.mkdirSync(path.dirname(promptPath), { recursive: true });const base = promptPath.slice(0, promptPath.length - path.extname(promptPath).length);const specPath = `${base}.spec.json`;@@ -78,7 +82,7 @@ export async function runGenerate(}}- telemetry.capture("cli_generate_succeeded", {+ tel.trackSucceeded({json_schema: !!options.jsonSchema,spec: !!options.spec,out_to_file: !!options.out,diff --git a/packages/openui-cli/src/commands/index.ts b/packages/openui-cli/src/commands/index.tsnew file mode 100644index 000000000..e4c9686ab--- /dev/null+++ b/packages/openui-cli/src/commands/index.ts@@ -0,0 +1,6 @@+import { createCommand } from "./create/command";+import { deployCommand } from "./deploy/command";+import { generateApiKeyCommand } from "./generate-api-key/command";+import { generateCommand } from "./generate/command";++export const commands = [createCommand, deployCommand, generateApiKeyCommand, generateCommand];diff --git a/packages/openui-cli/src/index.ts b/packages/openui-cli/src/index.tsindex 9a27e3485..6f81d5c7b 100644--- a/packages/openui-cli/src/index.ts+++ b/packages/openui-cli/src/index.ts@@ -1,280 +1,5 @@#!/usr/bin/env node-import { randomUUID } from "node:crypto";-import * as fs from "node:fs";-import * as path from "node:path";+import { runProgram } from "./program";-import { Command } from "commander";--import { runCreateApp } from "./commands/create-app";-import { runDeploy } from "./commands/deploy";-import { GenerateOptions, runGenerate } from "./commands/generate";-import { runGenerateApiKey } from "./commands/generate-api-key";-import { detectAgent, UNKNOWN_AGENT_NAME } from "./lib/detect-agent";-import { DEFAULT_ENV_FILE } from "./lib/env";-import { rejectConflictingScaffoldSelectors } from "./lib/examples-catalog";-import { rejectConflictingImmediateFlags, resolveArgs } from "./lib/resolve-args";-import { telemetry } from "./lib/telemetry";-import {- handleCliError,- normalizeAuth,- normalizeBackendFramework,- normalizeTemplate,-} from "./lib/utils"; // Ensure utils.ts is included for type declarations--const program = new Command();--const cliVersion = (- JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8")) as {- version: string;- }-).version;--program.name("openui").description("CLI for OpenUI").version(cliVersion);-program.option("--no-telemetry", "Disable anonymous usage analytics");--program.option(- "--agent-name <name>",- "AI agents: declare your stable lowercase kebab-case product slug for telemetry (e.g. codex or claude-code); humans can omit",- UNKNOWN_AGENT_NAME,-);-program.configureHelp({ showGlobalOptions: true });--// Init telemetry once, just before any command runs (honors --no-telemetry / DO_NOT_TRACK).-program.hook("preAction", (_thisCommand, actionCommand) => {- const globalOptions = program.opts<{ agentName: string; telemetry?: boolean }>();- const command = actionCommand.name();- telemetry.init({ cliVersion, flagEnabled: globalOptions.telemetry !== false });- telemetry.register({- agent_name: globalOptions.agentName,- detected_agent_name: detectAgent(),- cli_run_id: randomUUID(),- command,- });- telemetry.capture("cli_invoked");-});--program- .command("create")- .description(- "Scaffold a Next.js agent app with the recommended OpenUI Cloud backend or your own provider",- )- .option("-n, --name <string>", "Project name (interactive default: openui-agent)")- .option(- "-t, --template <template>",- "AI backend: openui-cloud (recommended default) | openui-self-hosted (infrastructure control)",- )- .option(- "--backend-framework <framework>",- "Backend framework: default | langgraph | vercel-ai-sdk | vercel-eve",- )- .option("-e, --example <example>", "Create from an example in examples/examples.json")- .option("--api-key <key>", "OpenUI Cloud API key (cloud template; skips sign-in)")- .option("--auth <method>", "Cloud auth method: oauth | skip (manual is deprecated)")- .option("--skill", "Install the OpenUI agent skill for AI coding assistants")- .option("--no-skill", "Skip installing the OpenUI agent skill")- .option("--no-interactive", "Fail with error if required args are missing")- .option("--no-install", "Scaffold without running the package install")- .option("-i, --immediate", "Start the development server after installing dependencies")- .option("--no-immediate", "Install dependencies without starting the development server")- .option("--verbose", "Stream full dependency install logs")- .addHelpText(- "after",- `-Templates:- openui-cloud Recommended default for prototypes and evaluations.- Hosted models, managed conversation history, built-in tools,- and ready-to-use reports and presentations. No model, storage,- or artifact infrastructure to operate. Bring your own- OpenAI/Anthropic/Google key (BYOK) on any plan,- including the free tier.- openui-self-hosted Choose when owning the OpenAI-compatible provider, AI route,- and persistence is a requirement. Available only via- --template; interactive runs default to openui-cloud.--Backend frameworks:- default Uses OpenAI SDK.- langgraph Bootstraps a LangGraph agent with the selected model backend.- vercel-ai-sdk Scaffolds a Vercel AI SDK agent with the selected model backend.- vercel-eve Scaffolds a Vercel Eve agent with the selected model backend.--OpenUI examples:- Loaded at runtime from examples/examples.json in the OpenUI repo.- Pick "Scaffold from OpenUI Examples" in the interactive prompt, or pass- --example <name> with any catalog folder name.-`,- )- .action(- async (options: {- name?: string;- template?: string;- backendFramework?: string;- example?: string;- apiKey?: string;- auth?: string;- skill?: boolean;- interactive: boolean;- install: boolean;- immediate?: boolean;- verbose?: boolean;- }) => {- try {- rejectConflictingImmediateFlags(process.argv.slice(2));- rejectConflictingScaffoldSelectors({- example: options.example,- backendFramework: normalizeBackendFramework(options.backendFramework),- template: options.template,- });- await runCreateApp({- name: options.name,- template: normalizeTemplate(options.template),- backendFramework: normalizeBackendFramework(options.backendFramework),- example: options.example,- apiKey: options.apiKey,- auth: normalizeAuth(options.auth),- skill: options.skill,- noInteractive: !options.interactive,- noInstall: !options.install,- immediate: options.immediate,- verbose: options.verbose,- });- } catch (e) {- handleCliError(e, "cli_create_failed");- } finally {- await telemetry.shutdown();- }- },- );--program- .command("deploy")- .description("Deploy an OpenUI project")- .usage("[dir] [options]")- .argument("[dir]", "Project directory (default: current directory)")- .option("-y, --yes", "Skip confirmation prompts")- .option("--skip-env", "Do not pass or save local .env values")- .option("--no-interactive", "Skip prompts (implies --yes)")- .option("--verbose", "Stream full deployment build logs")- .allowUnknownOption()- .allowExcessArguments()- .addHelpText(- "after",- `-Default supported platform is Vercel. If you are not logged in to the platform,-opens vercel login first. Links the project when needed, then offers to save-missing allowlisted keys from .env / .env.local to the project on the platform-(auto-accepted with --yes). Build logs are hidden by default; pass --verbose-to stream them. On failure the log tail is printed. Extra flags after deploy-are forwarded as-is to the target platform, which validates them.--Examples:- openui deploy- openui deploy --verbose-`,- )- .action(- async (- dir: string | undefined,- options: {- yes?: boolean;- skipEnv?: boolean;- interactive: boolean;- verbose?: boolean;- },- command: Command,- ) => {- try {- await runDeploy({- dir,- yes: options.yes,- skipEnv: options.skipEnv,- noInteractive: !options.interactive,- verbose: options.verbose,- extraArgs: command.args,- });- } catch (e) {- handleCliError(e, "cli_deploy_failed");- } finally {- await telemetry.shutdown();- }- },- );--program- .command("generate-api-key")- .description("Mint an OpenUI Gateway API key and write it to a project env file")- .option("-f, --file <path>", "Env file to write", DEFAULT_ENV_FILE)- .option(- "-k, --key <name>",- "Environment variable name (letters, digits, underscores)",- "THESYS_API_KEY",- )- .option("-n, --name <string>", "Name of the minted key in the Thesys console")- .addHelpText(- "after",- `-Run this inside an existing project. It uses the same browser sign-in as-openui create, mints an OpenUI Gateway API key, and writes it to the env file.--Examples:- openui generate-api-key- openui generate-api-key --file .env.local- openui generate-api-key --file .env.local --key THESYS_API_KEY-`,- )- .action(async (options: { file?: string; key?: string; name?: string }) => {- try {- await runGenerateApiKey({- file: options.file,- key: options.key,- name: options.name,- });- } catch (e) {- handleCliError(e, "cli_generate_api_key_failed");- } finally {- await telemetry.shutdown();- }- });--program- .command("generate")- .description("Generate the system prompt + serialized spec from a library definition")- .argument("[entry]", "Path to a file that exports a createLibrary() result")- .option(- "-o, --out <file>",- "Write the prompt to a file; the spec JSON lands alongside with .spec.json extension",- )- .option(- "--json-schema",- "Output JSON schema with component signatures for standalone prompt generation",- )- .option("--spec", "Generate a serialized library spec JSON (signatures, groups, JSON schema)")- .option("--export <name>", "Name of the export to use (auto-detected by default)")- .option(- "--prompt-options <name>",- "Name of the PromptOptions export to use (auto-detected by default)",- )- .option("--no-interactive", "Fail with error if required args are missing")- .action(async (entry: string | undefined, options: GenerateOptions) => {- try {- const args = await resolveArgs(- {- entry: entry- ? { value: entry }- : {- prompt: { type: "input", message: "Entry file path?" },- required: true,- },- },- options.interactive,- );-- await runGenerate((args as { entry: string }).entry, options);- } catch (e) {- handleCliError(e, "cli_generate_failed");- } finally {- await telemetry.shutdown();- }- });--program.parse();+void runProgram();diff --git a/packages/openui-cli/src/auth/authenticator.ts b/packages/openui-cli/src/lib/auth/authenticator.tssimilarity index 100%rename from packages/openui-cli/src/auth/authenticator.tsrename to packages/openui-cli/src/lib/auth/authenticator.tsdiff --git a/packages/openui-cli/src/auth/mint.ts b/packages/openui-cli/src/lib/auth/mint.tssimilarity index 89%rename from packages/openui-cli/src/auth/mint.tsrename to packages/openui-cli/src/lib/auth/mint.tsindex 4b346f9d2..9ea89ee8b 100644--- a/packages/openui-cli/src/auth/mint.ts+++ b/packages/openui-cli/src/lib/auth/mint.ts@@ -1,6 +1,6 @@-import { createFunnelProps } from "../lib/create-telemetry";-import { CliCancelledError, CreateError, telemetry } from "../lib/telemetry";+import { CliCancelledError, CreateError } from "../errors";import { Authenticator } from "./authenticator";+import type { AuthTelemetryClient } from "./telemetry";// Thesys console OAuth + key mint (same flow as create-c1-app). The OpenUI Cloud// master key is the same C1-flavored org API key (usageType "C1").@@ -24,6 +24,18 @@ export function assertValidApiKeyName(name: string): void {}export type CloudAuthMethod = "oauth" | "manual" | "skip";++export function normalizeAuth(a?: string): CloudAuthMethod | undefined {+ if (!a) return undefined;+ const v = a.toLowerCase();+ if (v === "oauth" || v === "manual" || v === "skip") return v;+ throw new CreateError(+ "args_resolution",+ `unknown --auth "${a}". Use: oauth | skip (manual is deprecated).`,+ "invalid_input",+ "INVALID_AUTH",+ );+}/** How the cloud key was obtained (for telemetry) — auth method + the `--api-key` flag case. */export type ResolvedAuthMethod = CloudAuthMethod | "apikey-flag";@@ -88,12 +100,12 @@ async function cloudAuthPrompt<T>(}/** Sign in via the browser and mint an OpenUI Cloud API key for the user's org. */-export async function mintCloudApiKey(projectName: string): Promise<string> {+export async function mintCloudApiKey(+ projectName: string,+ tel: AuthTelemetryClient,+): Promise<string> {const auth = new Authenticator({ issuerUrl: THESYS_ISSUER_URL, clientId: THESYS_CLIENT_ID });- telemetry.capture("cli_cloud_oidc_started", {- ...createFunnelProps("cloud_auth_started"),- auth_method: "oauth",- });+ tel.trackOidcStarted();await cloudAuthStep("oidc_discovery", "OIDC_DISCOVERY_FAILED", () => auth.initialize());const { accessToken, userInfo } = await cloudAuthStep("browser_auth", "OIDC_FAILED", () =>auth.authenticate(),@@ -151,7 +163,7 @@ export async function mintCloudApiKey(projectName: string): Promise<string> {const oidcSub =(profile["sub"] as string | undefined) ?? (userInfo?.["sub"] as string | undefined);- if (oidcSub) telemetry.aliasOidcSubject(oidcSub);+ if (oidcSub) tel.aliasOidcSubject(oidcSub);return data.apiKey;}@@ -166,6 +178,7 @@ export async function resolveCloudApiKey(opts: {auth?: CloudAuthMethod;projectName: string;interactive: boolean;+ tel: AuthTelemetryClient;}): Promise<{ key: string | null; method: ResolvedAuthMethod }> {const provided = opts.apiKey?.trim();if (provided) return { key: provided, method: "apikey-flag" };@@ -208,5 +221,5 @@ export async function resolveCloudApiKey(opts: {return { key: key.trim() || null, method: "manual" };}- return { key: await mintCloudApiKey(opts.projectName), method: "oauth" };+ return { key: await mintCloudApiKey(opts.projectName, opts.tel), method: "oauth" };}diff --git a/packages/openui-cli/src/lib/auth/telemetry.ts b/packages/openui-cli/src/lib/auth/telemetry.tsnew file mode 100644index 000000000..b222a1c84--- /dev/null+++ b/packages/openui-cli/src/lib/auth/telemetry.ts@@ -0,0 +1,13 @@+import { Telemetry } from "../telemetry";++export class AuthTelemetryClient extends Telemetry {+ trackOidcStarted() {+ this.capture("cli_cloud_oidc_started", {+ funnel: "cli_create",+ funnel_version: "frontloaded_cloud_setup_v1",+ step_rank: "0410",+ step_key: "cloud_auth_started",+ auth_method: "oauth",+ });+ }+}diff --git a/packages/openui-cli/src/lib/checkout.ts b/packages/openui-cli/src/lib/checkout.tsindex a48c239a3..21e22993b 100644--- a/packages/openui-cli/src/lib/checkout.ts+++ b/packages/openui-cli/src/lib/checkout.ts@@ -4,7 +4,7 @@ import * as os from "node:os";import * as path from "node:path";import { isTruthyEnv } from "./env";-import { CreateError } from "./telemetry";+import { CreateError } from "./errors";const GIT_TIMEOUT_MS = 60_000;const FETCH_TIMEOUT_MS = 30_000;diff --git a/packages/openui-cli/src/lib/context.ts b/packages/openui-cli/src/lib/context.tsnew file mode 100644index 000000000..19c522f88--- /dev/null+++ b/packages/openui-cli/src/lib/context.ts@@ -0,0 +1,19 @@+import { telemetry, type Telemetry } from "./telemetry";++export type CliContext = {+ cwd: string;+ argv: string[];+ telemetry: Telemetry;+ verbose: boolean;+};++export const context: CliContext = {+ get cwd() {+ return process.cwd();+ },+ get argv() {+ return process.argv;+ },+ telemetry,+ verbose: false,+};diff --git a/packages/openui-cli/src/lib/create-telemetry.ts b/packages/openui-cli/src/lib/create-telemetry.tsdeleted file mode 100644index a1e9fb24d..000000000--- a/packages/openui-cli/src/lib/create-telemetry.ts+++ /dev/null@@ -1,48 +0,0 @@-import type { AiSetup, TemplateName } from "./create-types";--const createFunnel = {- funnel: "cli_create",- funnel_version: "frontloaded_cloud_setup_v1",-} as const;--const createFunnelSteps = {- create_started: "0100",- ai_setup_selected: "0200",- backend_framework_selected: "0250",- example_selected: "0260",- scaffold_started: "0300",- scaffold_succeeded: "0310",- scaffold_failed: "0320",- env_resolution_started: "0400",- cloud_auth_started: "0410",- cloud_auth_resolved: "0420",- cloud_auth_failed: "0425",- cloud_auth_cancelled: "0426",- env_written: "0430",- skill_prompt_resolved: "0500",- skill_install_started: "0510",- skill_install_finished: "0520",- skill_install_failed: "0525",- skill_install_cancelled: "0526",- dependency_install_started: "0600",- dependency_install_succeeded: "0610",- dependency_install_failed: "0620",- dependency_install_cancelled: "0625",- create_succeeded: "0700",- create_failed: "9000",- create_cancelled: "9010",-} as const;--type CreateFunnelStep = keyof typeof createFunnelSteps;--export function createFunnelProps(stepKey: CreateFunnelStep): Record<string, string> {- return {- ...createFunnel,- step_rank: createFunnelSteps[stepKey],- step_key: stepKey,- };-}--export function aiSetupFromTemplate(template: TemplateName): AiSetup {- return template === "openui-cloud" ? "openui_cloud" : "openai_compatible_provider";-}diff --git a/packages/openui-cli/src/lib/env.ts b/packages/openui-cli/src/lib/env.tsindex f297ad2a9..ab8814166 100644--- a/packages/openui-cli/src/lib/env.ts+++ b/packages/openui-cli/src/lib/env.ts@@ -3,7 +3,7 @@ import * as path from "node:path";import { parse as parseDotenv } from "dotenv";-import { CreateError } from "./telemetry";+import { CreateError } from "./errors";/** True for `"1"` or `"true"` (any case). */export const isTruthyEnv = (value?: string) => value === "1" || value?.toLowerCase() === "true";@@ -11,41 +11,6 @@ export const isTruthyEnv = (value?: string) => value === "1" || value?.toLowerCaexport const DEFAULT_ENV_FILE = ".env";export const PROJECT_ENV_FILES = [".env", ".env.local"] as const;-/** `.env` when it already exists (OpenUI default); otherwise `.env.local`. */-export function resolveProjectEnvFileName(projectDir: string): string {- return fs.existsSync(path.join(projectDir, DEFAULT_ENV_FILE)) ? DEFAULT_ENV_FILE : ".env.local";-}--const VERCEL_WRITTEN_ENV_KEYS = [- "VERCEL_TOKEN",- "VERCEL_OIDC_TOKEN",- "VERCEL_ORG_ID",- "VERCEL_PROJECT_ID",-] as const;--/**- * Vercel always writes `.env.local`. If the project already has `.env`, move- * those Vercel keys there and drop an emptied `.env.local`.- */-export function adoptVercelEnvVars(projectDir: string): void {- const targetName = resolveProjectEnvFileName(projectDir);- if (targetName === ".env.local") return;- const localPath = path.join(projectDir, ".env.local");- if (!fs.existsSync(localPath)) return;-- const fromLocal = parseEnvFile(localPath);- const targetPath = path.join(projectDir, targetName);- for (const key of VERCEL_WRITTEN_ENV_KEYS) {- const value = fromLocal[key]?.trim();- if (!value || /[\r\n]/.test(value)) continue;- upsertEnvVar(targetPath, key, value);- removeEnvVar(localPath, key);- }- if (fs.existsSync(localPath) && fs.readFileSync(localPath, "utf8").trim() === "") {- fs.unlinkSync(localPath);- }-}-/** Parse a dotenv-style file into key/value pairs (no `$VAR` expansion). */export function parseEnvFile(filePath: string): Record<string, string> {if (!fs.existsSync(filePath)) return {};diff --git a/packages/openui-cli/src/lib/utils.ts b/packages/openui-cli/src/lib/errors.tssimilarity index 71%rename from packages/openui-cli/src/lib/utils.tsrename to packages/openui-cli/src/lib/errors.tsindex 0d07e62e4..1cd49f74f 100644--- a/packages/openui-cli/src/lib/utils.ts+++ b/packages/openui-cli/src/lib/errors.ts@@ -1,20 +1,60 @@-import type { CloudAuthMethod } from "../auth/mint";-import { createFunnelProps } from "./create-telemetry";-import type { TemplateName } from "./create-types";-import { OverlayName } from "./create-types";import type { CommandResult } from "./process-runner";-import {- CliCancelledError,- CreateError,- telemetry as defaultTelemetry,- type CliErrorClass,- type CliErrorMetadata,- type Telemetry,-} from "./telemetry";-/** ASCII Record Separator — Untypeable in prompt text and always- * escaped by JSON.stringify, so it can never collide with either artifact. */-export const SEPARATION_DELIMITER = "\u001E";+/** Thrown by command funnels so the index wrapper can attribute the failure stage + drain once. */+export type CliErrorClass =+ | "invalid_input"+ | "filesystem"+ | "authentication"+ | "dependency"+ | "peer_dependency"+ | "registry_auth"+ | "network"+ | "package_compatibility"+ | "workspace_config"+ | "install_script"+ | "process"+ | "user_cancelled"+ | "generation"+ | "unknown";++export type CliErrorMetadata = {+ duration_ms?: number;+ exit_code?: number;+ failure_signal?: NodeJS.Signals;+ http_status?: number;+ cancellation_exit_code?: number;+ auth_failure_stage?: string;+};++export class CreateError extends Error {+ constructor(+ public stage: string,+ message: string,+ public errorClass: CliErrorClass = "unknown",+ public errorCode = "UNKNOWN",+ public errorMetadata: CliErrorMetadata = {},+ ) {+ super(message);+ this.name = "CreateError";+ }+}++export class CliCancelledError extends CreateError {+ constructor(+ stage: string,+ public exitCode = 0,+ metadata: CliErrorMetadata = {},+ ) {+ super(+ stage,+ "Operation cancelled.",+ "user_cancelled",+ exitCode === 0 ? "USER_CANCELLED" : exitCode === 143 ? "TERMINATED" : "INTERRUPTED",+ { ...metadata, cancellation_exit_code: exitCode },+ );+ this.name = "CliCancelledError";+ }+}export type CliErrorProperties = CliErrorMetadata & {failure_stage: string;@@ -217,70 +257,3 @@ export function throwCommandFailure(const { failure_stage, error_class, error_code, ...metadata } = properties;throw new CreateError(failure_stage, message, error_class, error_code, metadata);}--export function handleCliError(- e: unknown,- event: string,- telemetry: Telemetry = defaultTelemetry,-): void {- const cancelled = e instanceof CliCancelledError;- const message = e instanceof Error ? e.message : String(e);- if (cancelled) console.info("Cancelled.");- else console.error(e instanceof CreateError ? `Error: ${message}` : message);-- const errorProperties = cliErrorProperties(e);- const capturedEvent = cancelled ? event.replace(/_failed$/, "_cancelled") : event;-- if (event === "cli_create_failed") {- telemetry.capture(capturedEvent, {- ...createFunnelProps(cancelled ? "create_cancelled" : "create_failed"),- ...errorProperties,- });- } else {- telemetry.capture(capturedEvent, errorProperties);- }-- process.exitCode = cancelled ? e.exitCode : 1;-}--export function normalizeTemplate(t?: string): TemplateName | undefined {- if (!t) return undefined;- const v = t.toLowerCase();- if (v === "self-hosted" || v === "openui-self-hosted") return "openui-self-hosted";- if (v === "cloud" || v === "openui-cloud") return "openui-cloud";- return v;-}--export function normalizeAuth(a?: string): CloudAuthMethod | undefined {- if (!a) return undefined;- const v = a.toLowerCase();- if (v === "oauth" || v === "manual" || v === "skip") return v;- throw new CreateError(- "args_resolution",- `unknown --auth "${a}". Use: oauth | skip (manual is deprecated).`,- "invalid_input",- "INVALID_AUTH",- );-}--export function normalizeBackendFramework(framework?: string): OverlayName | undefined {- if (!framework) return undefined;- switch (framework.toLowerCase()) {- case "default":- case "none":- case "no-framework":- return "default";- case "langgraph":- case "lang-graph":- return "langgraph";- case "vercel":- case "vercel-ai-sdk":- case "ai-sdk":- return "vercel-ai-sdk";- case "eve":- case "vercel-eve":- return "vercel-eve";- default:- return framework.toLowerCase();- }-}diff --git a/packages/openui-cli/src/lib/install-skill.ts b/packages/openui-cli/src/lib/install-skill.tsdeleted file mode 100644index 28cf8c2ca..000000000--- a/packages/openui-cli/src/lib/install-skill.ts+++ /dev/null@@ -1,38 +0,0 @@-import { runCommand, type CommandResult, type RunCommandOptions } from "./process-runner";-import { CliCancelledError } from "./telemetry";--const OPENUI_SKILL_SOURCE = "thesysdev/skills";--export async function shouldInstallSkill(- option: boolean | undefined,- interactive: boolean,-): Promise<boolean> {- if (option !== undefined) return option;- if (!interactive) return false;-- try {- const { confirm } = await import("@inquirer/prompts");- return await confirm({- message: "Install the OpenUI agent skill for AI coding assistants?",- default: true,- });- } catch (err) {- const { ExitPromptError } = await import("@inquirer/core");- if (err instanceof ExitPromptError) {- throw new CliCancelledError("skill_prompt");- }- throw err;- }-}--export async function runSkillInstall(- targetDir: string,- options: RunCommandOptions = {},-): Promise<CommandResult> {- return runCommand(- "npx",- ["-y", "skills", "add", OPENUI_SKILL_SOURCE, "--skill", "openui", "-y"],- targetDir,- options,- );-}diff --git a/packages/openui-cli/src/lib/resolve-args.ts b/packages/openui-cli/src/lib/resolve-args.tsindex 53bd78035..9884427db 100644--- a/packages/openui-cli/src/lib/resolve-args.ts+++ b/packages/openui-cli/src/lib/resolve-args.ts@@ -1,4 +1,4 @@-import { CliCancelledError, CreateError } from "./telemetry";+import { CliCancelledError, CreateError } from "./errors";type InputPromptConfig = {type: "input";@@ -20,16 +20,6 @@ type ResolvedArgs<T extends Record<string, ArgDef<unknown>>> = {[K in keyof T]: T[K] extends { value: infer V } ? V : string;};-export function rejectConflictingImmediateFlags(args: string[]): void {- const separatorIndex = args.indexOf("--");- const optionArgs = separatorIndex === -1 ? args : args.slice(0, separatorIndex);- const hasImmediate = optionArgs.some((arg) => arg === "--immediate" || arg === "-i");- const hasNoImmediate = optionArgs.includes("--no-immediate");- if (hasImmediate && hasNoImmediate) {- throw new CreateError("bad_args", "--immediate and --no-immediate cannot be used together.");- }-}-async function resolveOne(prompt: PromptConfig): Promise<string> {const { input, select } = await import("@inquirer/prompts");if (prompt.type === "select") {diff --git a/packages/openui-cli/src/lib/scaffold/copy.ts b/packages/openui-cli/src/lib/scaffold/copy.tsnew file mode 100644index 000000000..461f3bece--- /dev/null+++ b/packages/openui-cli/src/lib/scaffold/copy.ts@@ -0,0 +1,32 @@+import * as fs from "node:fs";+import * as path from "node:path";++import { OVERLAYS_DIR } from "../../commands/create/lib/overlays";++export function shouldCopyTemplatePath(templateDir: string, src: string): boolean {+ const rel = path.relative(templateDir, src);+ if (!rel) return true;+ const top = rel.split(path.sep)[0] ?? "";+ // Copy the base template only; selected backend overlays are applied later.+ // Also exclude install/build artifacts that may sit in a template directory.+ return ![OVERLAYS_DIR, "node_modules", ".next", ".turbo", "dist"].includes(top);+}++export function restoreDotfiles(projectDir: string) {+ // Templates ship `gitignore` un-dotted: npm silently strips `.gitignore`+ // files (at any depth) from published packages, so a dotted copy never+ // reaches the scaffold — and freshly created apps would commit `.env`.+ // Restore the real name here instead.+ const plain = path.join(projectDir, "gitignore");+ if (fs.existsSync(plain)) {+ fs.renameSync(plain, path.join(projectDir, ".gitignore"));+ }+}++export function copyTemplate(templateDir: string, targetDir: string): void {+ fs.cpSync(templateDir, targetDir, {+ recursive: true,+ filter: (src) => shouldCopyTemplatePath(templateDir, src),+ });+ restoreDotfiles(targetDir);+}diff --git a/packages/openui-cli/src/lib/scaffold/index.ts b/packages/openui-cli/src/lib/scaffold/index.tsnew file mode 100644index 000000000..d4d18d86e--- /dev/null+++ b/packages/openui-cli/src/lib/scaffold/index.ts@@ -0,0 +1,36 @@+import {+ applyOverlay,+ resolveOverlay,+ type TemplateOverlay,+} from "../../commands/create/lib/overlays";+import type { PackageManagerName } from "../detect-package-manager";+import { copyTemplate } from "./copy";+import { applyLockfileHygiene } from "./lockfiles";+import { rewritePackageJson } from "./package-json";++export { resolveTemplateSource, type ResolvedTemplate } from "./source";++export function applyScaffoldFiles(params: {+ templateDir: string;+ targetDir: string;+ name: string;+ packageManager: PackageManagerName;+ backendFramework: string;+}): TemplateOverlay | undefined {+ const overlay = resolveOverlay(params.templateDir, params.backendFramework);+ copyTemplate(params.templateDir, params.targetDir);+ applyOverlay(params.targetDir, overlay);+ rewritePackageJson(+ params.targetDir,+ params.name,+ params.packageManager,+ overlay?.manifest.packageJson,+ );+ applyLockfileHygiene({+ targetDir: params.targetDir,+ overlay,+ packageManager: params.packageManager,+ backendFramework: params.backendFramework,+ });+ return overlay;+}diff --git a/packages/openui-cli/src/lib/scaffold/lockfiles.ts b/packages/openui-cli/src/lib/scaffold/lockfiles.tsnew file mode 100644index 000000000..fba5b3401--- /dev/null+++ b/packages/openui-cli/src/lib/scaffold/lockfiles.ts@@ -0,0 +1,30 @@+import * as fs from "node:fs";+import * as path from "node:path";++import type { TemplateOverlay } from "../../commands/create/lib/overlays";+import type { PackageManagerName } from "../detect-package-manager";++export function applyLockfileHygiene(params: {+ targetDir: string;+ overlay: TemplateOverlay | undefined;+ packageManager: PackageManagerName;+ backendFramework: string;+}): void {+ const { targetDir, overlay, packageManager, backendFramework } = params;+ // An overlay that changes dependencies without a lock must not keep the base lock+ const overlayShipsNpmLock = Boolean(+ overlay && fs.existsSync(path.join(overlay.dir, "package-lock.json")),+ );+ if (packageManager !== "npm" || (overlay && !overlayShipsNpmLock)) {+ fs.rmSync(path.join(targetDir, "package-lock.json"), { force: true });+ }+ // The Cloud template ships pnpm's lock/workspace files for reproducible pnpm+ // installs and native-build policy. A framework changes dependencies, so+ // regenerate its lock; non-pnpm scaffolds do not need either pnpm file.+ if (packageManager !== "pnpm" || backendFramework !== "default") {+ fs.rmSync(path.join(targetDir, "pnpm-lock.yaml"), { force: true });+ }+ if (packageManager !== "pnpm") {+ fs.rmSync(path.join(targetDir, "pnpm-workspace.yaml"), { force: true });+ }+}diff --git a/packages/openui-cli/src/lib/scaffold/package-json.ts b/packages/openui-cli/src/lib/scaffold/package-json.tsnew file mode 100644index 000000000..8f36d3f9d--- /dev/null+++ b/packages/openui-cli/src/lib/scaffold/package-json.ts@@ -0,0 +1,94 @@+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";++import type { OverlayManifest } from "../../commands/create/lib/overlays";+import type { PackageManagerName } from "../detect-package-manager";++/** Match npm/pnpm install: keep dependency keys alphabetically sorted. */+function sortPackageRecord<T>(record: Record<string, T>): Record<string, T> {+ return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));+}++export function rewritePackageJson(+ projectDir: string,+ name: string,+ packageManager: PackageManagerName,+ overlayPackageJson?: OverlayManifest["packageJson"],+) {+ // package.json: set the project name and de-vendor monorepo-local deps+ // (workspace:* / file: / catalog:) to the published "latest". link: deps are+ // rewritten to an absolute file: path so locally-linked packages (e.g.+ // @openuidev/thesys) keep resolving against the developer's checkout under any+ // package manager — npm rejects link:, and ~ isn't expanded. Temporary, until+ // these packages are published.+ const pkgPath = path.join(projectDir, "package.json");+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8")) as {+ name: string;+ scripts?: Record<string, string>;+ dependencies?: Record<string, string>;+ devDependencies?: Record<string, string>;+ pnpm?: unknown;+ };+ pkg.name = name;+ if (packageManager !== "pnpm") delete pkg.pnpm;++ if (overlayPackageJson) {+ pkg.dependencies ??= {};+ for (const dependency of overlayPackageJson.removeDependencies ?? []) {+ delete pkg.dependencies[dependency];+ }+ Object.assign(pkg.dependencies, overlayPackageJson.dependencies ?? {});+ Object.assign((pkg.devDependencies ??= {}), overlayPackageJson.devDependencies ?? {});+ Object.assign((pkg.scripts ??= {}), overlayPackageJson.scripts ?? {});+ }++ for (const section of ["dependencies", "devDependencies"] as const) {+ const deps = pkg[section];+ if (!deps) continue;+ for (const key of Object.keys(deps)) {+ const v = deps[key];+ if (!v) continue;+ if (v.startsWith("link:")) {+ const target = v.slice("link:".length);+ const abs = target.startsWith("~")+ ? path.join(os.homedir(), target.slice(1))+ : path.resolve(target);+ deps[key] = `file:${abs}`;+ continue;+ }+ // workspace:/file:/catalog: are monorepo-only protocols npm/yarn/bun+ // can't resolve standalone — pin them to the published "latest".+ if (/^(workspace:|file:|catalog:)/.test(v)) deps[key] = "latest";+ }+ // Object.assign appends overlay packages at the end; re-sort so the+ // scaffolded package.json matches what `npm install` / `pnpm add` write.+ pkg[section] = sortPackageRecord(deps);+ }+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");++ // Keep the copied npm lockfile's root package metadata aligned so npm ci can+ // consume the template without having to rewrite or re-resolve it.+ const lockPath = path.join(projectDir, "package-lock.json");+ if (fs.existsSync(lockPath)) {+ const lock = JSON.parse(fs.readFileSync(lockPath, "utf8")) as {+ name?: string;+ packages?: Record<+ string,+ {+ name?: string;+ dependencies?: Record<string, string>;+ devDependencies?: Record<string, string>;+ }+ >;+ };+ lock.name = name;+ const lockRoot = lock.packages?.[""];+ if (lockRoot) {+ lockRoot.name = name;+ lockRoot.dependencies = pkg.dependencies;+ lockRoot.devDependencies = pkg.devDependencies;+ }+ fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + "\n");+ }+}diff --git a/packages/openui-cli/src/lib/scaffold-template.ts b/packages/openui-cli/src/lib/scaffold/source.tssimilarity index 89%rename from packages/openui-cli/src/lib/scaffold-template.tsrename to packages/openui-cli/src/lib/scaffold/source.tsindex 3638d5423..51893bd12 100644--- a/packages/openui-cli/src/lib/scaffold-template.ts+++ b/packages/openui-cli/src/lib/scaffold/source.ts@@ -2,8 +2,8 @@ import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";-import { checkoutSource } from "./checkout";-import { CreateError } from "./telemetry";+import { checkoutSource } from "../checkout";+import { CreateError } from "../errors";export const TEMPLATES_DIR = "templates";diff --git a/packages/openui-cli/src/lib/telemetry.ts b/packages/openui-cli/src/lib/telemetry.tsindex 7e8380885..68c6eb6bb 100644--- a/packages/openui-cli/src/lib/telemetry.ts+++ b/packages/openui-cli/src/lib/telemetry.ts@@ -5,7 +5,7 @@ import { PostHog } from "posthog-node";import { isTruthyEnv } from "./env";-// Public ingestion key (same project as docs/coda-prod). Overridable for testing.+// Public ingestion keyconst POSTHOG_KEY =process.env["OPENUI_POSTHOG_KEY"] ?? "phc_3OLW53x09ZTVZSV6BEpj5uycj3ooqR6KOemOjx04e3D";const POSTHOG_HOST = process.env["OPENUI_POSTHOG_HOST"] ?? "https://us.i.posthog.com";@@ -46,6 +46,7 @@ function loadOrCreateState() {persist: () => writeState(file, { ...fresh, firstRunNoticeShown: true }),};}+function writeState(file: string, s: Stored) {try {fs.mkdirSync(path.dirname(file), { recursive: true });@@ -55,67 +56,23 @@ function writeState(file: string, s: Stored) {}}-/** Thrown by command funnels so the index wrapper can attribute the failure stage + drain once. */-export type CliErrorClass =- | "invalid_input"- | "filesystem"- | "authentication"- | "dependency"- | "peer_dependency"- | "registry_auth"- | "network"- | "package_compatibility"- | "workspace_config"- | "install_script"- | "process"- | "user_cancelled"- | "generation"- | "unknown";--export type CliErrorMetadata = {- duration_ms?: number;- exit_code?: number;- failure_signal?: NodeJS.Signals;- http_status?: number;- cancellation_exit_code?: number;- auth_failure_stage?: string;+type Session = {+ client?: PostHog;+ distinctId: string;+ superProps: Record<string, unknown>;+ enabled: boolean;};-export class CreateError extends Error {- constructor(- public stage: string,- message: string,- public errorClass: CliErrorClass = "unknown",- public errorCode = "UNKNOWN",- public errorMetadata: CliErrorMetadata = {},- ) {- super(message);- this.name = "CreateError";- }-}+export class Telemetry {+ private readonly session: Session;-export class CliCancelledError extends CreateError {- constructor(- stage: string,- public exitCode = 0,- metadata: CliErrorMetadata = {},- ) {- super(- stage,- "Operation cancelled.",- "user_cancelled",- exitCode === 0 ? "USER_CANCELLED" : exitCode === 143 ? "TERMINATED" : "INTERRUPTED",- { ...metadata, cancellation_exit_code: exitCode },- );- this.name = "CliCancelledError";+ constructor(source?: Telemetry) {+ this.session = source?.session ?? {+ distinctId: "anonymous",+ superProps: {},+ enabled: false,+ };}-}--export class Telemetry {- private client?: PostHog;- private distinctId = "anonymous";- private superProps: Record<string, unknown> = {};- private enabled = false;init(opts: { cliVersion: string; flagEnabled: boolean }) {const optedOut =@@ -124,9 +81,9 @@ export class Telemetry {opts.flagEnabled === false;if (optedOut) return; // enabled stays false → all capture() are no-opsconst state = loadOrCreateState();- this.distinctId = state.distinctId;+ this.session.distinctId = state.distinctId;const interactiveTerminal = isInteractiveTerminal();- this.superProps = {+ this.session.superProps = {cli_version: opts.cliVersion,os: process.platform,os_release: os.release(),@@ -138,19 +95,19 @@ export class Telemetry {is_interactive_terminal: interactiveTerminal,};try {- this.client = new PostHog(POSTHOG_KEY, {+ this.session.client = new PostHog(POSTHOG_KEY, {host: POSTHOG_HOST,flushAt: 1,flushInterval: 0,});// Telemetry is best-effort: swallow network/flush errors so an offline CLI// run never spams the user's console with PostHog stack traces.- this.client.on("error", (error) => debugLogPostHogFailure("request", error));+ this.session.client.on("error", (error) => debugLogPostHogFailure("request", error));} catch (error) {debugLogPostHogFailure("init", error);return;}- this.enabled = true;+ this.session.enabled = true;// posthog-core logs flush failures via a hardcoded console.error (not gated on// any logger/option). Filter ONLY those lines so an offline run stays quiet —// the CLI's own console.error output passes through untouched.@@ -159,7 +116,7 @@ export class Telemetry {if (typeof args[0] === "string" && args[0].includes("flushing PostHog")) return;origError(...args);};- if (isTelemetryDebug()) this.client.debug();+ if (isTelemetryDebug()) this.session.client.debug();if (state.isFirstRun) {process.stderr.write("\n◆ OpenUI CLI collects usage analytics; OAuth sign-ins may link usage to your OIDC account ID.\n" +@@ -170,16 +127,30 @@ export class Telemetry {}register(props: Record<string, unknown>) {- if (this.enabled) Object.assign(this.superProps, props);+ if (this.session.enabled) Object.assign(this.session.superProps, props);+ }++ registerRun(props: {+ agent_name: string;+ detected_agent_name: string;+ cli_run_id: string;+ command: string;+ }) {+ this.register(props);+ }++ trackInvoked() {+ this.capture("cli_invoked");}capture(event: string, properties: Record<string, unknown> = {}) {- if (!this.enabled || !this.client) return;+ const { enabled, client, distinctId, superProps } = this.session;+ if (!enabled || !client) return;try {- this.client.capture({- distinctId: this.distinctId,+ client.capture({+ distinctId,event,- properties: { ...this.superProps, ...properties },+ properties: { ...superProps, ...properties },});} catch (error) {debugLogPostHogFailure("capture", error);@@ -187,11 +158,12 @@ export class Telemetry {}alias(distinctId: string, alias: string) {- if (!this.enabled || !this.client) return;+ const { enabled, client } = this.session;+ if (!enabled || !client) return;if (!distinctId || !alias || distinctId === alias) return;try {- this.client.alias({ distinctId, alias });- this.client.setPersonProperties({+ client.alias({ distinctId, alias });+ client.setPersonProperties({distinctId,propertiesOnce: {first_cli_auth_ts: new Date().toISOString(),@@ -203,18 +175,20 @@ export class Telemetry {}aliasOidcSubject(oidcSub: string) {- if (!this.enabled || !this.client || !oidcSub || oidcSub === this.distinctId) {+ const { enabled, client, distinctId } = this.session;+ if (!enabled || !client || !oidcSub || oidcSub === distinctId) {return;}- this.alias(oidcSub, this.distinctId);+ this.alias(oidcSub, distinctId);}async shutdown() {- if (!this.enabled || !this.client) return;+ const { enabled, client } = this.session;+ if (!enabled || !client) return;try {await Promise.race([- this.client.shutdown(),+ client.shutdown(),new Promise<void>((r) => setTimeout(r, SHUTDOWN_TIMEOUT_MS)),]);} catch (error) {diff --git a/packages/openui-cli/src/program.ts b/packages/openui-cli/src/program.tsnew file mode 100644index 000000000..4e31a1d8f--- /dev/null+++ b/packages/openui-cli/src/program.ts@@ -0,0 +1,86 @@+import { randomUUID } from "node:crypto";+import * as fs from "node:fs";+import * as path from "node:path";++import { Command } from "commander";++import { commands } from "./commands";+import { CreateTelemetryClient } from "./commands/create/lib/telemetry";+import { context as ctx } from "./lib/context";+import { detectAgent, UNKNOWN_AGENT_NAME } from "./lib/detect-agent";+import { CliCancelledError, cliErrorProperties, CreateError } from "./lib/errors";++let activeCommand = "unknown";++function buildProgram(): Command {+ const program = new Command();++ const cliVersion = (+ JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8")) as {+ version: string;+ }+ ).version;++ program.name("openui").description("CLI for OpenUI").version(cliVersion);+ program.option("--no-telemetry", "Disable anonymous usage analytics");+ program.option("--verbose", "Stream full command logs");+ program.option(+ "--agent-name <name>",+ "AI agents: declare your stable lowercase kebab-case product slug for telemetry (e.g. codex or claude-code); humans can omit",+ UNKNOWN_AGENT_NAME,+ );+ program.configureHelp({ showGlobalOptions: true });++ program.hook("preAction", (_thisCommand, actionCommand) => {+ activeCommand = actionCommand.name();+ const globalOptions = program.opts<{+ agentName: string;+ telemetry?: boolean;+ verbose?: boolean;+ }>();+ ctx.verbose = Boolean(globalOptions.verbose || actionCommand.optsWithGlobals()["verbose"]);+ ctx.telemetry.init({ cliVersion, flagEnabled: globalOptions.telemetry !== false });+ ctx.telemetry.registerRun({+ agent_name: globalOptions.agentName,+ detected_agent_name: detectAgent(),+ cli_run_id: randomUUID(),+ command: actionCommand.name(),+ });+ ctx.telemetry.trackInvoked();+ });++ for (const command of commands) {+ command.configureHelp({ showGlobalOptions: true });+ program.addCommand(command);+ }++ return program;+}++function handleCliError(e: unknown, event: string, extra?: Record<string, unknown>): void {+ const cancelled = e instanceof CliCancelledError;+ const message = e instanceof Error ? e.message : String(e);+ if (cancelled) console.info("Cancelled.");+ else console.error(e instanceof CreateError ? `Error: ${message}` : message);++ const errorProperties = cliErrorProperties(e);+ const capturedEvent = cancelled ? event.replace(/_failed$/, "_cancelled") : event;+ ctx.telemetry.capture(capturedEvent, { ...extra, ...errorProperties });++ process.exitCode = cancelled ? e.exitCode : 1;+}++export async function runProgram(): Promise<void> {+ const program = buildProgram();+ try {+ await program.parseAsync(process.argv);+ } catch (e) {+ const cancelled = e instanceof CliCancelledError;+ const event = `cli_${activeCommand.replace(/-/g, "_")}_failed`;+ const extra =+ activeCommand === "create" ? CreateTelemetryClient.failedProperties(cancelled) : undefined;+ handleCliError(e, event, extra);+ } finally {+ await ctx.telemetry.shutdown();+ }+}