Skip to content

The Open Standard for Generative UI

fix: add generate-api-key command (#1121)

AB83c9ddb78913
diff --git a/docs/content/docs/api-reference/cli.mdx b/docs/content/docs/api-reference/cli.mdx
index f385957af..be4f8216d 100644
--- a/docs/content/docs/api-reference/cli.mdx
+++ b/docs/content/docs/api-reference/cli.mdx
@@ -1,9 +1,9 @@
---
title: "@openuidev/cli"
-description: API reference for the OpenUI CLI to scaffold apps and generate system prompts or library specs.
+description: API reference for the OpenUI CLI to scaffold apps, mint Cloud API keys, and generate system prompts or library specs.
---
-A command-line tool for scaffolding OpenUI chat apps and generating system prompts, JSON schemas, or serialized library specs from library definitions.
+A command-line tool for scaffolding OpenUI chat apps, minting OpenUI Cloud API key, and generating system prompts, JSON schemas, or serialized library specs from library definitions.
## Installation
@@ -210,6 +210,48 @@ npx @openuidev/cli@latest create --name my-app --skill
npx @openuidev/cli@latest create --name my-app --no-skill
```
+## `openui generate-api-key`
+
+Signs in with Thesys in the browser, mints an OpenUI Cloud API key, and writes it to a project env file.
+
+```
+openui generate-api-key [options]
+```
+
+**Options**
+
+| Flag | Description |
+| --------------------- | -------------------------------------------------------------------------------------------------- |
+| `-f, --file <path>` | Env file to write (default: `.env`) |
+| `-k, --key <name>` | Environment variable name (default: `THESYS_API_KEY`) |
+| `-n, --name <string>` | Name of the minted key in the Thesys console (default: `package.json` name, or the directory name) |
+
+**Examples**
+
+```bash tab="pnpm" tab-group="pkg"
+pnpx @openuidev/cli@latest generate-api-key
+pnpx @openuidev/cli@latest generate-api-key --file .env.local
+pnpx @openuidev/cli@latest generate-api-key --file .env.local --key THESYS_API_KEY
+```
+
+```bash tab="bun" tab-group="pkg"
+bunx @openuidev/cli@latest generate-api-key
+bunx @openuidev/cli@latest generate-api-key --file .env.local
+bunx @openuidev/cli@latest generate-api-key --file .env.local --key THESYS_API_KEY
+```
+
+```bash tab="yarn" tab-group="pkg"
+yarn dlx @openuidev/cli@latest generate-api-key
+yarn dlx @openuidev/cli@latest generate-api-key --file .env.local
+yarn dlx @openuidev/cli@latest generate-api-key --file .env.local --key THESYS_API_KEY
+```
+
+```bash tab="npm" tab-group="pkg"
+npx @openuidev/cli@latest generate-api-key
+npx @openuidev/cli@latest generate-api-key --file .env.local
+npx @openuidev/cli@latest generate-api-key --file .env.local --key THESYS_API_KEY
+```
+
## `openui generate`
Generates the system prompt **and** the serialized library spec from a file that exports a `createLibrary()` result. A single run emits both artifacts — they derive from the same `Library` instance, so they can never drift apart. Use the spec with `generateSystemPrompt` in backend routes; the prompt file supports static or legacy integrations.
diff --git a/docs/content/docs/api-reference/index.mdx b/docs/content/docs/api-reference/index.mdx
index 9096c6513..afc517163 100644
--- a/docs/content/docs/api-reference/index.mdx
+++ b/docs/content/docs/api-reference/index.mdx
@@ -100,7 +100,7 @@ The OpenUI SDK is split into packages that build on each other:
Development-only floating widget surfacing captured events with error messages and stack traces.
</Card>
<Card title="@openuidev/cli" href="/docs/api-reference/cli">
- openui create (scaffold a Next.js app) and openui generate (system prompt + library spec from a
- library definition).
+ openui create (scaffold a Next.js app), openui generate-api-key (mint a Cloud key), and openui generate (system prompt + library spec from a library
+ definition).
</Card>
</Cards>
diff --git a/packages/openui-cli/README.md b/packages/openui-cli/README.md
index 2868338d8..2d9808cb8 100644
--- a/packages/openui-cli/README.md
+++ b/packages/openui-cli/README.md
@@ -1,18 +1,19 @@
# @openuidev/cli
-Command-line tools for starting OpenUI projects and generating model instructions from component libraries.
+Command-line tools for starting OpenUI projects, minting OpenUI Cloud API keys, and generating model instructions from component libraries.
[![npm](https://img.shields.io/npm/v/@openuidev/cli)](https://www.npmjs.com/package/@openuidev/cli)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/thesysdev/openui/blob/main/LICENSE)
**Links:** [CLI docs](https://openui.com/docs/api-reference/cli) | [GitHub repo](https://github.com/thesysdev/openui)
-It currently supports two workflows:
+It currently supports:
- scaffolding a new OpenUI app from one of two templates:
- **OpenUI Cloud (recommended)** — hosted models with managed conversations, streaming, built-in tools, and ready-to-use report and presentation artifacts
- **Self-hosted** — bring an OpenAI-compatible model key and own the AI route and persistence
- keeping the default minimal SDK route or adding a LangGraph, Vercel AI SDK, or Vercel Eve backend to either template
+- minting an OpenUI Cloud API key into an existing project's env file
- generating a system prompt or JSON Schema from a `createLibrary()` export
## Install
@@ -51,6 +52,13 @@ npx @openuidev/cli@latest create --template openui-self-hosted --backend-framewo
npx @openuidev/cli@latest create --template openui-self-hosted --backend-framework vercel-eve
```
+Mint an OpenUI Cloud API key into the current project's `.env`:
+
+```bash
+npx @openuidev/cli@latest generate-api-key
+npx @openuidev/cli@latest generate-api-key --file .env.local --key THESYS_API_KEY
+```
+
Generate a prompt from a library file:
```bash
@@ -164,6 +172,28 @@ openui create --name my-app --no-skill --no-install
openui create --no-interactive --name my-app --template openui-cloud --api-key tk_your_key
```
+### `openui generate-api-key`
+
+Signs in with Thesys in the browser, mints an OpenUI Cloud API key, and writes it to a project env file.
+
+```bash
+openui generate-api-key [options]
+```
+
+Options:
+
+- `-f, --file <path>`: Env file to write (default: `.env`)
+- `-k, --key <name>`: Environment variable name (default: `THESYS_API_KEY`)
+- `-n, --name <string>`: Name of the minted key in the Thesys console (default: `package.json` name, or the current directory name)
+
+Examples:
+
+```bash
+openui generate-api-key
+openui generate-api-key --file .env.local
+openui generate-api-key --file .env.local --key THESYS_API_KEY
+```
+
### `openui generate`
Generates a system prompt and serialized library spec from a file that exports a `createLibrary()` result. Use the spec with `generateSystemPrompt` in backend routes; the prompt file remains available for static or legacy integrations.
@@ -240,6 +270,7 @@ Run the built CLI:
```bash
node dist/index.js --help
node dist/index.js create --help
+node dist/index.js generate-api-key --help
node dist/index.js generate --help
```
diff --git a/packages/openui-cli/package.json b/packages/openui-cli/package.json
index c9c03ede1..c3cf0e6b0 100644
--- a/packages/openui-cli/package.json
+++ b/packages/openui-cli/package.json
@@ -1,7 +1,7 @@
{
"name": "@openuidev/cli",
"version": "0.2.12",
- "description": "CLI for OpenUI — scaffold generative UI chat apps and generate LLM system prompts from component libraries",
+ "description": "CLI for OpenUI — scaffold generative UI chat apps, mint Cloud API keys, and generate LLM system prompts from component libraries",
"bin": {
"openui": "dist/index.js"
},
diff --git a/packages/openui-cli/src/commands/generate-api-key.ts b/packages/openui-cli/src/commands/generate-api-key.ts
new file mode 100644
index 000000000..ffc85bbc9
--- /dev/null
+++ b/packages/openui-cli/src/commands/generate-api-key.ts
@@ -0,0 +1,56 @@
+import * as fs from "node:fs";
+import * as path from "node:path";
+
+import { mintCloudApiKey } from "../auth/mint";
+import { upsertEnvVar } from "../lib/env";
+import { telemetry } from "../lib/telemetry";
+
+export interface GenerateApiKeyOptions {
+ file?: string;
+ key?: string;
+ name?: string;
+}
+
+const DEFAULT_ENV_FILE = ".env";
+const DEFAULT_ENV_KEY = "THESYS_API_KEY";
+
+function resolveProjectName(explicit?: 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 {
+ 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";
+}
+
+export async function runGenerateApiKey(options: GenerateApiKeyOptions): Promise<void> {
+ 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);
+
+ telemetry.capture("cli_generate_api_key_started", {
+ env_file: path.basename(file),
+ env_key: envKey,
+ });
+
+ const apiKey = await mintCloudApiKey(projectName);
+
+ const filePath = path.resolve(process.cwd(), file);
+ upsertEnvVar(filePath, envKey, apiKey);
+
+ const displayPath = path.relative(process.cwd(), filePath) || file;
+ console.info(`✅ ${envKey} written to ${displayPath}`);
+
+ telemetry.capture("cli_generate_api_key_succeeded", {
+ auth_method: "oauth",
+ env_file: path.basename(file),
+ env_key: envKey,
+ duration_ms: Date.now() - t0,
+ });
+}
diff --git a/packages/openui-cli/src/index.ts b/packages/openui-cli/src/index.ts
index 12901a225..1ebb0b8f3 100644
--- a/packages/openui-cli/src/index.ts
+++ b/packages/openui-cli/src/index.ts
@@ -8,6 +8,7 @@ import { Command } from "commander";
import { runCreateApp } from "./commands/create-app";
import { GenerateOptions, runGenerate } from "./commands/generate";
+import { runGenerateApiKey } from "./commands/generate-api-key";
import { detectAgent, UNKNOWN_AGENT_NAME } from "./lib/detect-agent";
import { rejectConflictingImmediateFlags, resolveArgs } from "./lib/resolve-args";
import { telemetry } from "./lib/telemetry";
@@ -129,6 +130,38 @@ Backend frameworks:
},
);
+program
+ .command("generate-api-key")
+ .description("Mint an OpenUI Cloud API key and write it to a project env file")
+ .option("-f, --file <path>", "Env file to write", ".env")
+ .option("-k, --key <name>", "Environment variable name", "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 Cloud 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")
diff --git a/packages/openui-cli/src/lib/env.ts b/packages/openui-cli/src/lib/env.ts
index 8abbc649b..95c6b3979 100644
--- a/packages/openui-cli/src/lib/env.ts
+++ b/packages/openui-cli/src/lib/env.ts
@@ -1,2 +1,48 @@
+import * as fs from "node:fs";
+import * as path from "node:path";
+
+import { CreateError } from "./telemetry";
+
/** True for `"1"` or `"true"` (any case). */
export const isTruthyEnv = (value?: string) => value === "1" || value?.toLowerCase() === "true";
+
+const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=[^\r\n]*$/;
+
+function isKeyLine(line: string, name: string): boolean {
+ return new RegExp(`^\\s*#?\\s*${name}\\s*=`).test(line);
+}
+
+/**
+ * Create or update `name=value` in an env file. Replaces the first matching
+ * assignment (including a commented one) and otherwise appends.
+ */
+export function upsertEnvVar(filePath: string, name: string, value: string): void {
+ const assignment = `${name}=${value}`;
+ if (!ENV_ASSIGNMENT.test(assignment)) {
+ throw new CreateError(
+ "args_resolution",
+ "Invalid env assignment. Name must use letters, digits, and underscores; value cannot contain newlines.",
+ "invalid_input",
+ "INVALID_ENV_ASSIGNMENT",
+ );
+ }
+
+ const resolved = path.resolve(filePath);
+ let content = "";
+ try {
+ content = fs.readFileSync(resolved, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+
+ const newline = content.includes("\r\n") ? "\r\n" : "\n";
+ const lines = content.length === 0 ? [] : content.split(/\r?\n/);
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
+
+ const replaceAt = lines.findIndex((line) => isKeyLine(line, name));
+ if (replaceAt >= 0) lines[replaceAt] = assignment;
+ else lines.push(assignment);
+
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
+ fs.writeFileSync(resolved, lines.join(newline) + newline);
+}