🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(cli): publish a local HTML file as an artifact (#19360)
Inneib1a9979c5f21
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex a273e8af049..a64afa3f83a 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -38,6 +38,7 @@ the next free number of that prefix.- **L-E17** Direct-mention routing is verified with a real tool call and the full persisted tree; no owner assistant, `callAgent`, or synthetic target-user row.- **L-E19** Markdown evidence: one paragraph per physical line; newline only where it is content.- **L-E20** Build fixtures through the same composition the product uses; compare an entity page against a canary-created sibling before publishing it as evidence.+- **L-E21** Evidence for "A is unaffected by B" must be able to tell A from B: distinct content and the target echoed in the request line.- **L-E21** Publish against production even when the subject exists only locally; a local ingest may supplement, never replace.**Product and interaction contracts**@@ -62,6 +63,7 @@ the next free number of that prefix.- **L-S19** `plan[]` holds only what the user accepts or rejects, each id fulfilled by a case; a clean ingest prints `plan: N item(s)` with nothing after it.- **L-S20** Read the managed containers' host ports from `docker ps` and pass `DB_PORT`/`REDIS_PORT` to every `init-dev-env.sh` subcommand; `auth_failed` on migrate is a port mismatch.- **L-S21** In a worktree, invoke scripts by absolute path and prove the SPA's identity (Vite pid cwd, changed module from the Vite origin) before trusting any gate or evidence.+- **L-S22** A per-account cap that a round consumes (artifact deployments) is cleared for the account the surface actually authenticates as, and re-cleared between rounds.## Entries@@ -535,3 +537,35 @@ once and require its server call in the log. Before trusting any gate,`pwd`/`cd <worktree> &&` and confirm the NAME of the test you added appears inthe runner output. Distinct from L-S7: that is a stale bundle from the righttree; this is a healthy bundle from the wrong tree.++### L-E21 — Evidence that cannot distinguish the two things the case compares++`since 2026-09-10` · `holds-while: a case asserts one artifact is unaffected by an operation on another`++**Trap:** proving `--new` forks a separate site, the round published two sites+whose pages were byte-identical (`contentHash` equal) and a request line that+printed only the response, not the URL asked for. The artifact showed the+expected string, so the case read as a pass — but curling the _new_ site would+have printed exactly the same bytes. The claim rested on a hand-typed section+header, not on anything in the output.++**Rule:** when a case asserts "X still serves its own content" or any other+independence between two objects, make the two distinguishable _before_+capturing: different content per object, and each request echoing the URL or id+it targeted. Ask of the artifact: if the wrong target had been requested, would+this file look different? If not, the case proves nothing.++### L-S22 — A per-account quota the round itself consumes, cleared for the wrong account++`since 2026-09-10` · `holds-while: artifact deployments are capped per plan (Free = 3 active) and the CLI authenticates as a seeded runtime user`++**Trap:** each publish leaves an active deployment, so the third run of a round+fails with `ARTIFACT_DEPLOYMENT_CAPACITY_LIMIT_REACHED` — which reads as a+regression in the code under test. The purge then ran against the smoke's+default `user_artifact_e2e` and reported "active before: 0" while the CLI, which+authenticates as the seeded runtime user, still held three.++**Rule:** identify the account the surface actually authenticates as (for the CLI,+the `user_id` on the seeded API key row) and clear the cap for _that_ id before+and between rounds. A quota error mid-round is an environment fact until the+account has been checked; do not debug it as product behaviour.diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 1773385f100..7732c8a4ce6 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -101,6 +101,8 @@ drive / probe / capture / publish. Skip a row only when its surface AND runtime| P77 | web, cli | gateway | probe | Read `llm_generation_tracing.prompt_version` after one call; restart the server if stale || P78 | web, cli | gateway | env | `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1` so the server can read local s3rver URLs || P79 | web, cli | client, gateway | env | Local SearXNG with `SEARCH_PROVIDERS=searxng`; the on-disk search1api keys are dead |+| P84 | cli | any | auth | Drive `lh` against the local lobehub-cloud runtime by seeding an API key row into its main database |+| P85 | cli | any | fixture | Simulate a publish whose response was lost by restoring `pendingCreateKey` in `.lobehub/artifacts.json` || P82 | web | any | drive | Acceptance flow canvas through the production debug proxy: anonymous shared link, one uninterrupted script, canvas controls for clipped groups |## Choose the least invasive mechanism@@ -2487,3 +2489,66 @@ ScreenshotTiles, and Highlighter's `styles.content` styles a container whose`pre` has separate padding. An outer wrapper or `img` override alone does notprove the visible edge or total inset changed. Measure the settled DOM, theninspect a screenshot before declaring the styling verified.++#### P84 · Driving `lh` against the local lobehub-cloud runtime++**applies-to:** surface=cli · runtime=any · phase=auth++**Situation:** a CLI command that only exists on cloud (`market.deployments.*`,+which the OSS lambda router stubs out as an empty object) has to be exercised+against `lobehub-cloud`'s own dev runtime, not this repo's `:3010` server. The+adapter's seeded CLI profile (§4 CLI) points at the wrong backend, and cloud's+`bun run dev:runtime:auth` only writes **browser** cookies.++**Doesn't work:** `dev:runtime:auth` for the CLI (cookies, not a token); an+interactive device-code login (hijacks the user's browser and is forbidden).++**Works:** insert an api\_keys row into the runtime's main database and use it as+`LOBEHUB_CLI_API_KEY`. `key_hash` is `HMAC-SHA256(key, KEY_VAULTS_SECRET)`;+`key` is the same plaintext AES-GCM encrypted with that secret as+`iv:authTag:ciphertext` hex — the shapes `init-dev-env.sh seed-user` uses. Read+`keyVaultsSecret` and `seedEmail` from+`~/.lobehub/runtime-dev/secrets/<checkout>.json`, resolve the user id by that+email, then:++```bash+LOBEHUB_CLI_API_KEY=sk-lh-<16 lowercase alnum> \+LOBEHUB_SERVER=http://localhost:<runtime app port> \+LOBEHUB_CLI_HOME=<scratch dir> \+ node apps/cli/dist/index.js <command>+```++The key must match `^sk-lh-[\da-z]{16}$` or the server rejects it before any+lookup. Give the run its own `LOBEHUB_CLI_HOME` so it cannot disturb the user's+real login, and remember the publishing identity is now that seeded user — see+`common-mistakes.md` L-S22 before blaming a quota error on the code.++Cloud's runtime commands each re-read the container ports, so pass the same+`LOBEHUB_RUNTIME_POSTGRES_PORT` / `LOBEHUB_RUNTIME_REDIS_PORT` overrides to+_every_ `bun run dev …` invocation. Omitting them on a later call silently+targets the default 5433, which on a developer machine is usually a different+project's Postgres and fails as `password authentication failed for user+"postgres"`.++#### P85 · Simulating a publish whose response never arrived++**applies-to:** surface=cli · runtime=any · phase=fixture++**Situation:** proving that retrying an interrupted `lh artifact publish` does not+create a second site. The real failure — a dropped reply — cannot be produced by+killing the process, because the manifest is what carries the recovery state.++**Works:** the CLI writes `pendingCreateKey` into `.lobehub/artifacts.json`+_before_ sending a create, and replaces it with `deploymentId` on success. So+write the manifest by hand with only a known `pendingCreateKey`, publish (the+CLI adopts that key), then restore the same one-key manifest and publish again.+A correct implementation returns the first deployment id and does not advance+the revision; a broken one mints a second site with its own URL.++```bash+printf '{"artifacts":{"dist/index.html":{"pendingCreateKey":"%s"}},"version":1}' "$KEY" \+ > .lobehub/artifacts.json+```++Capture both publishes' `--json` output in one artifact with the restored+manifest shown between them, so a reviewer can see the key was genuinely reused.diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 532f7b3437f..4ce8a946ff0 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -39,6 +39,7 @@"@lobechat/device-identity": "workspace:*","@lobechat/eval-rubric": "workspace:*","@lobechat/heterogeneous-agents": "workspace:*",+ "@lobechat/html-artifact": "workspace:*","@lobechat/local-file-shell": "workspace:*","@lobechat/tool-runtime": "workspace:*","@lobechat/types": "workspace:*",diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yamlindex 3a61929f042..fcc6ed93919 100644--- a/apps/cli/pnpm-workspace.yaml+++ b/apps/cli/pnpm-workspace.yaml@@ -16,6 +16,7 @@ packages:- '../../packages/ssrf-safe-fetch'- '../../packages/business/const'- '../../packages/file-loaders'+ - '../../packages/html-artifact'- '../../packages/utils'- '.'diff --git a/apps/cli/src/commands/artifact.test.ts b/apps/cli/src/commands/artifact.test.tsnew file mode 100644index 00000000000..95374ab910b--- /dev/null+++ b/apps/cli/src/commands/artifact.test.ts@@ -0,0 +1,224 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerArtifactCommand } from './artifact';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ market: {+ deployments: {+ commitWorkspaceHtmlUpload: { mutate: vi.fn() },+ prepareWorkspaceHtmlUpload: { mutate: vi.fn() },+ },+ },+ },+}));++const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({+ getTrpcClient: vi.fn(),+}));++vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));++describe('artifact publish', () => {+ let workingDirectory: string;+ let exitSpy: ReturnType<typeof vi.spyOn>;+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let fetchSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ workingDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'lh-artifact-'));+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue({ ok: true, status: 200, statusText: 'OK' } as Response);++ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mockReset();+ mockTrpcClient.market.deployments.commitWorkspaceHtmlUpload.mutate+ .mockReset()+ .mockResolvedValue({ data: { id: 'dep-1', publicUrl: 'https://example.com/p' } });+ });++ afterEach(() => {+ exitSpy.mockRestore();+ consoleSpy.mockRestore();+ fetchSpy.mockRestore();+ fs.rmSync(workingDirectory, { force: true, recursive: true });+ });++ const run = async (args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerArtifactCommand(program);+ await program.parseAsync(['node', 'lh', 'artifact', 'publish', ...args]);+ };++ const prepareReturns = (files: { path: string }[]) => {+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mockResolvedValue({+ data: {+ files: files.map((file) => ({+ headers: { 'Content-Type': 'application/octet-stream' },+ path: file.path,+ uploadUrl: `https://upload.example.com${file.path}`,+ })),+ uploadId: 'upload-1',+ },+ });+ };++ it('bundles a sibling stylesheet and uploads every prepared file', async () => {+ const site = path.join(workingDirectory, 'site');+ fs.mkdirSync(site);+ fs.writeFileSync(+ path.join(site, 'index.html'),+ '<title>Demo</title><link rel="stylesheet" href="./app.css">',+ );+ fs.writeFileSync(path.join(site, 'app.css'), `body{content:"${'x'.repeat(40_000)}"}`);++ prepareReturns([{ path: '/index.html' }, { path: '/app.css' }]);++ await run([path.join(site, 'index.html'), '--root', site]);++ const prepared =+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mock.calls[0][0];+ expect(prepared.title).toBe('Demo');+ expect(prepared.files.map((file: { path: string }) => file.path)).toEqual([+ '/index.html',+ '/app.css',+ ]);+ expect(fetchSpy).toHaveBeenCalledTimes(2);+ expect(mockTrpcClient.market.deployments.commitWorkspaceHtmlUpload.mutate).toHaveBeenCalledWith(+ {+ uploadId: 'upload-1',+ },+ );+ });++ it('reaches assets above the entry directory when --root allows it', async () => {+ fs.mkdirSync(path.join(workingDirectory, 'pages'));+ fs.mkdirSync(path.join(workingDirectory, 'images'));+ fs.writeFileSync(+ path.join(workingDirectory, 'pages', 'index.html'),+ '<title>Up</title><img src="../images/logo.png">',+ );+ fs.writeFileSync(path.join(workingDirectory, 'images', 'logo.png'), 'png-bytes');++ prepareReturns([{ path: '/index.html' }]);++ await run([path.join(workingDirectory, 'pages', 'index.html'), '--root', workingDirectory]);++ expect(mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate).toHaveBeenCalled();+ expect(exitSpy).not.toHaveBeenCalled();+ });++ it('refuses an entry outside the root instead of publishing it', async () => {+ const outside = path.join(workingDirectory, 'outside.html');+ fs.writeFileSync(outside, '<title>Nope</title>');+ fs.mkdirSync(path.join(workingDirectory, 'root'));++ await run([outside, '--root', path.join(workingDirectory, 'root')]);++ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate,+ ).not.toHaveBeenCalled();+ });++ const manifestPath = () => path.join(workingDirectory, '.lobehub', 'artifacts.json');++ const readManifest = () => JSON.parse(fs.readFileSync(manifestPath(), 'utf8'));++ const writeManifest = (artifacts: Record<string, unknown>) => {+ fs.mkdirSync(path.dirname(manifestPath()), { recursive: true });+ fs.writeFileSync(manifestPath(), JSON.stringify({ artifacts, version: 1 }));+ };++ describe('deployment binding', () => {+ beforeEach(() => {+ fs.writeFileSync(path.join(workingDirectory, 'index.html'), '<title>Bound</title>');+ prepareReturns([{ path: '/index.html' }]);+ });++ const publish = (...extra: string[]) =>+ run([path.join(workingDirectory, 'index.html'), '--root', workingDirectory, ...extra]);++ it('creates a deployment and records the binding when none exists', async () => {+ await publish();++ const call =+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mock.calls[0][0];+ expect(call.target).toEqual({ kind: 'create' });+ expect(call.idempotencyKey).toEqual(expect.any(String));+ expect(readManifest().artifacts['index.html']).toEqual({ deploymentId: 'dep-1' });+ });++ it('republishes to the bound deployment instead of creating another', async () => {+ writeManifest({ 'index.html': { deploymentId: 'dep-existing' } });++ await publish();++ const call =+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mock.calls[0][0];+ expect(call.target).toEqual({ deploymentId: 'dep-existing', kind: 'deployment' });+ // An update needs no key: a retry costs a revision, never a second site.+ expect(call.idempotencyKey).toBeUndefined();+ });++ it('--new creates a separate deployment and rebinds to it', async () => {+ writeManifest({ 'index.html': { deploymentId: 'dep-old' } });++ await publish('--new');++ const call =+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mock.calls[0][0];+ expect(call.target).toEqual({ kind: 'create' });+ expect(readManifest().artifacts['index.html']).toEqual({ deploymentId: 'dep-1' });+ });++ it('--deployment targets an id for this run without touching the manifest', async () => {+ writeManifest({ 'index.html': { deploymentId: 'dep-bound' } });++ await publish('--deployment', 'dep-oneoff');++ const call =+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mock.calls[0][0];+ expect(call.target).toEqual({ deploymentId: 'dep-oneoff', kind: 'deployment' });+ expect(readManifest().artifacts['index.html']).toEqual({ deploymentId: 'dep-bound' });+ });++ it('rejects --new together with --deployment', async () => {+ await publish('--new', '--deployment', 'dep-x');++ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate,+ ).not.toHaveBeenCalled();+ });++ it('reuses a pending create key so a lost response cannot mint a second site', async () => {+ writeManifest({ 'index.html': { pendingCreateKey: 'key-from-a-lost-response' } });++ await publish();++ const call =+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mock.calls[0][0];+ expect(call.idempotencyKey).toBe('key-from-a-lost-response');+ });++ it('records the pending key before sending, so a crash mid-publish is recoverable', async () => {+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mockRejectedValueOnce(+ new Error('network died'),+ );++ await expect(publish()).rejects.toThrow('network died');++ expect(readManifest().artifacts['index.html'].pendingCreateKey).toEqual(expect.any(String));+ });+ });+});diff --git a/apps/cli/src/commands/artifact.ts b/apps/cli/src/commands/artifact.tsnew file mode 100644index 00000000000..1559ccd5742--- /dev/null+++ b/apps/cli/src/commands/artifact.ts@@ -0,0 +1,254 @@+import path from 'node:path';++import {+ gatherWorkspaceHtmlArtifact,+ hostedPath,+ packWorkspaceHtmlDocument,+} from '@lobechat/html-artifact';+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient, type TrpcClient } from '../api/client';+import {+ createIdempotencyKey,+ readBinding,+ resolveManifest,+ writeBinding,+} from '../utils/artifactManifest';+import { outputJson } from '../utils/format';+import { log } from '../utils/logger';+import { readLocalHtmlAsset } from '../utils/readLocalHtmlAsset';++interface PreparedUploadTarget {+ headers: Record<string, string>;+ path: string;+ uploadUrl: string;+}++interface DeploymentRecord {+ id?: string;+ latestRevisionNumber?: number;+ publicUrl?: string;+ slug?: string;+ status?: string;+}++/**+ * `market.deployments.*` only exists on the LobeHub Cloud server; the OSS+ * `LambdaRouter` this CLI is typed against ships an empty stub, so the calls+ * are described here and reached through a cast.+ */+type PublishTarget = { deploymentId: string; kind: 'deployment' } | { kind: 'create' };++interface MarketDeploymentClient {+ market: {+ deployments: {+ commitWorkspaceHtmlUpload: {+ mutate: (input: { uploadId: string }) => Promise<{ data: DeploymentRecord }>;+ };+ prepareWorkspaceHtmlUpload: {+ mutate: (input: {+ artifactIdentifier: string;+ files: { contentType: string; path: string; sizeBytes: number }[];+ idempotencyKey?: string;+ requestedSlug?: string;+ target: PublishTarget;+ title?: string;+ }) => Promise<{ data: { files: PreparedUploadTarget[]; uploadId: string } }>;+ };+ };+ };+}++const deploymentClient = (client: TrpcClient) => client as unknown as MarketDeploymentClient;++interface UploadEntry {+ body: Buffer;+ contentType: string;+ path: string;+}++const fail = (message: string) => {+ log.error(message);+ process.exit(1);+};++const warnList = (label: string, items: string[]) => {+ if (items.length === 0) return;+ console.log(`${pc.yellow('!')} ${label}: ${items.join(', ')}`);+};++export function registerArtifactCommand(program: Command) {+ const artifact = program.command('artifact').description('Publish local pages as artifacts');++ artifact+ .command('publish <file>')+ .description('Publish a local HTML file, bundling the assets it references')+ .option(+ '--root <dir>',+ 'Directory the page may reference assets from (defaults to the working directory)',+ )+ .option('--deployment <id>', 'Publish to this deployment for this run only')+ .option('--new', 'Create a separate deployment instead of updating the bound one')+ .option('--title <title>', 'Override the page title')+ .option('--slug <slug>', 'Requested public slug')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(+ async (+ file: string,+ options: {+ json?: string | boolean;+ root?: string;+ slug?: string;+ title?: string;+ deployment?: string;+ new?: boolean;+ },+ ) => {+ const entryPath = path.resolve(file);+ const rootDirectory = path.resolve(options.root ?? process.cwd());++ if (!entryPath.startsWith(`${rootDirectory}${path.sep}`) && entryPath !== rootDirectory) {+ fail(+ `${file} is outside ${rootDirectory}. Pass --root to widen the published directory.`,+ );+ return;+ }++ const entry = await readLocalHtmlAsset(entryPath);+ if (!entry.ok || entry.text === undefined) {+ fail(`Cannot read ${file}`);+ return;+ }++ const gathered = await gatherWorkspaceHtmlArtifact({+ htmlContent: entry.text,+ htmlFilePath: entryPath,+ readAsset: readLocalHtmlAsset,+ workingDirectory: rootDirectory,+ });++ if (gathered.blocked === 'too-many') {+ fail('This page references too many local files to publish (limit is 64).');+ return;+ }+ if (gathered.blocked === 'too-large') {+ fail(`This page is too large to publish (${gathered.totalBytes} bytes, limit is 50MB).`);+ return;+ }++ const packed = packWorkspaceHtmlDocument({+ entryPath: gathered.entryPath,+ files: gathered.files,+ });++ if (packed.unresolvedHrefs.length > 0) {+ fail(`Could not resolve local references: ${packed.unresolvedHrefs.join(', ')}`);+ return;+ }++ warnList('Referenced files not found (widen with --root?)', gathered.missing);+ warnList('Too large to include', gathered.oversized);+ warnList('Unsupported file types, skipped', gathered.unsupported);++ const entries: UploadEntry[] = [+ {+ body: Buffer.from(packed.html, 'utf8'),+ contentType: 'text/html; charset=utf-8',+ path: '/index.html',+ },+ ...packed.sidecars.map((sidecar) => ({+ body: Buffer.from(sidecar.content, sidecar.encoding === 'base64' ? 'base64' : 'utf8'),+ contentType: sidecar.contentType,+ path: hostedPath(sidecar.path),+ })),+ ];++ const client = await getTrpcClient();+ const title = options.title || gathered.title;++ const manifest = resolveManifest(entryPath, rootDirectory);+ const binding = readBinding(manifest);++ if (options.new && options.deployment) {+ fail('--new and --deployment cannot be combined.');+ return;+ }++ const boundDeploymentId = options.new+ ? undefined+ : (options.deployment ?? binding.deploymentId);+ const target: PublishTarget = boundDeploymentId+ ? { deploymentId: boundDeploymentId, kind: 'deployment' }+ : { kind: 'create' };++ // Reuse a key left behind by a create whose response never arrived, so+ // the retry resolves to the deployment the server already made.+ const idempotencyKey =+ target.kind === 'create'+ ? (binding.pendingCreateKey ?? createIdempotencyKey())+ : undefined;++ // Recorded before the request, not after: a create that succeeds and+ // then loses its response must still be recoverable on the next run.+ const persistsBinding = target.kind === 'create' && !options.deployment;+ if (persistsBinding && idempotencyKey !== binding.pendingCreateKey) {+ writeBinding(manifest, { ...binding, pendingCreateKey: idempotencyKey });+ }++ const deployments = deploymentClient(client).market.deployments;++ const prepared = await deployments.prepareWorkspaceHtmlUpload.mutate({+ artifactIdentifier: gathered.identifier,+ files: entries.map((item) => ({+ contentType: item.contentType,+ path: item.path,+ sizeBytes: item.body.byteLength,+ })),+ idempotencyKey,+ requestedSlug: options.slug || title,+ target,+ title,+ });++ for (const uploadTarget of prepared.data.files) {+ const source = entries.find((item) => item.path === uploadTarget.path);+ if (!source) {+ fail(`Server asked for an unknown file: ${uploadTarget.path}`);+ return;+ }++ const response = await fetch(uploadTarget.uploadUrl, {+ body: source.body,+ headers: uploadTarget.headers,+ method: 'PUT',+ });++ if (!response.ok) {+ fail(+ `Upload failed for ${uploadTarget.path}: ${response.status} ${response.statusText}`,+ );+ return;+ }+ }++ const result = await deployments.commitWorkspaceHtmlUpload.mutate({+ uploadId: prepared.data.uploadId,+ });++ if (persistsBinding && result.data.id) {+ writeBinding(manifest, { deploymentId: result.data.id });+ }++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(result.data, fields);+ return;+ }++ console.log(`${pc.green('✓')} Published ${pc.bold(title)} (${entries.length} file(s))`);+ if (result.data.publicUrl) console.log(` URL: ${pc.dim(result.data.publicUrl)}`);+ console.log(` Deployment: ${pc.dim(result.data.id ?? '')}`);+ },+ );+}diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex b372209241c..c1d8db7ef13 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -3,6 +3,7 @@ import { Command } from 'commander';import { registerAgentCommand } from './commands/agent';import { registerAgentGroupCommand } from './commands/agent-group';import { registerAgentSignalCommand } from './commands/agent-signal';+import { registerArtifactCommand } from './commands/artifact';import { registerBotCommand } from './commands/bot';import { registerCompletionCommand } from './commands/completion';import { registerConfigCommand } from './commands/config';@@ -90,6 +91,7 @@ export function createProgram() {registerGenerateCommand(program);registerGoalCommand(program);registerFileCommand(program);+ registerArtifactCommand(program);registerHeteroCommand(program);registerSkillCommand(program);registerSessionGroupCommand(program);diff --git a/apps/cli/src/utils/artifactManifest.ts b/apps/cli/src/utils/artifactManifest.tsnew file mode 100644index 00000000000..0b61bf82a2b--- /dev/null+++ b/apps/cli/src/utils/artifactManifest.ts@@ -0,0 +1,97 @@+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';++const MANIFEST_DIR = '.lobehub';+const MANIFEST_FILE = 'artifacts.json';++export interface ArtifactBinding {+ deploymentId?: string;+ /**+ * Set before a create is sent and cleared once its deployment is recorded, so+ * a retry after a lost response reuses the key and the server returns the+ * deployment it already made instead of minting a second site.+ */+ pendingCreateKey?: string;+}++interface ArtifactManifest {+ artifacts: Record<string, ArtifactBinding>;+ version: 1;+}++export interface ResolvedManifest {+ entryKey: string;+ path: string;+ root: string;+}++const emptyManifest = (): ArtifactManifest => ({ artifacts: {}, version: 1 });++const findUp = (from: string, relative: string): string | undefined => {+ let dir = from;++ for (;;) {+ if (fs.existsSync(path.join(dir, relative))) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) return undefined;+ dir = parent;+ }+};++/**+ * The manifest is committed with the project so a publish from CI targets the+ * same deployment a developer created locally. Its directory is therefore the+ * project root: an existing manifest wins, then the enclosing repository, and+ * failing both the directory the publish was already scoped to. Never the+ * process cwd — that can be unrelated to the file being published, and would+ * drop a manifest into whichever directory the command happened to run from.+ */+export const resolveManifest = (entryPath: string, fallbackRoot: string): ResolvedManifest => {+ const from = path.dirname(path.resolve(entryPath));+ const root =+ findUp(from, path.join(MANIFEST_DIR, MANIFEST_FILE)) ??+ findUp(from, '.git') ??+ path.resolve(fallbackRoot);++ return {+ entryKey: path.relative(root, path.resolve(entryPath)).split(path.sep).join('/'),+ path: path.join(root, MANIFEST_DIR, MANIFEST_FILE),+ root,+ };+};++const readManifest = (manifestPath: string): ArtifactManifest => {+ try {+ const parsed: unknown = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ if (!parsed || typeof parsed !== 'object') return emptyManifest();++ const artifacts = (parsed as ArtifactManifest).artifacts;+ if (!artifacts || typeof artifacts !== 'object') return emptyManifest();++ return { artifacts, version: 1 };+ } catch {+ // absent or unreadable — the caller creates a fresh deployment+ return emptyManifest();+ }+};++export const readBinding = (manifest: ResolvedManifest): ArtifactBinding =>+ readManifest(manifest.path)['artifacts'][manifest.entryKey] ?? {};++export const writeBinding = (manifest: ResolvedManifest, binding: ArtifactBinding): void => {+ const current = readManifest(manifest.path);+ const next: ArtifactManifest = {+ ...current,+ artifacts: { ...current.artifacts, [manifest.entryKey]: binding },+ };++ fs.mkdirSync(path.dirname(manifest.path), { recursive: true });+ // Write-then-rename: a crash must not leave a truncated manifest, which would+ // read as "no binding" and publish a duplicate site on the next run.+ const temporary = `${manifest.path}.${process.pid}.tmp`;+ fs.writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`);+ fs.renameSync(temporary, manifest.path);+};++export const createIdempotencyKey = (): string => randomUUID();diff --git a/apps/cli/src/utils/readLocalHtmlAsset.ts b/apps/cli/src/utils/readLocalHtmlAsset.tsnew file mode 100644index 00000000000..9e1b231edd4--- /dev/null+++ b/apps/cli/src/utils/readLocalHtmlAsset.ts@@ -0,0 +1,41 @@+import fs from 'node:fs/promises';++import {+ isTextContentType,+ type ReadWorkspaceAssetResult,+ resolveWorkspaceAssetContentType,+ WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES,+} from '@lobechat/html-artifact';++export const readLocalHtmlAsset = async (+ absolutePath: string,+): Promise<ReadWorkspaceAssetResult> => {+ let size: number;+ try {+ const stats = await fs.stat(absolutePath);+ if (!stats.isFile()) return { ok: false, reason: 'missing' };+ size = stats.size;+ } catch {+ return { ok: false, reason: 'missing' };+ }++ if (size > WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES) {+ return { ok: false, reason: 'oversized', sizeBytes: size };+ }++ let buffer: Buffer;+ try {+ buffer = await fs.readFile(absolutePath);+ } catch {+ return { ok: false, reason: 'unreadable' };+ }++ const contentType = resolveWorkspaceAssetContentType(absolutePath);++ return {+ bytes: new Uint8Array(buffer),+ contentType,+ ok: true,+ text: isTextContentType(contentType) ? buffer.toString('utf8') : undefined,+ };+};diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex 480356eed92..85f9724569d 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -506,6 +506,24 @@ importers:specifier: 4.5.4version: 4.5.4+ ../../packages/html-artifact:+ dependencies:+ '@lobechat/const':+ specifier: workspace:*+ version: link:../const+ '@lobechat/prompts':+ specifier: workspace:*+ version: link:../prompts+ '@lobechat/utils':+ specifier: workspace:*+ version: link:../utils+ es-toolkit:+ specifier: ^1.50.0+ version: 1.52.0+ js-sha256:+ specifier: ^0.11.1+ version: 0.11.1+../../packages/local-file-shell:dependencies:'@lobechat/device-sandbox':@@ -739,6 +757,9 @@ importers:'@lobechat/heterogeneous-agents':specifier: workspace:*version: link:../../packages/heterogeneous-agents+ '@lobechat/html-artifact':+ specifier: workspace:*+ version: link:../../packages/html-artifact'@lobechat/local-file-shell':specifier: workspace:*version: link:../../packages/local-file-shell@@ -6013,6 +6034,9 @@ packages:resolution: {integrity: sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==}+ resolution: {integrity: sha512-o6WSo/LUvY2uC4j7mO50a2ms7E/EAdbP0swigLV+nzHKTTaYnaLIWJ02VdXrsJX0vGedDESQnLsOekr94ryfjg==}+resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}@@ -14405,6 +14429,8 @@ snapshots:+ [email protected]: {}+diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex cd69f5ae5be..cac3d11578b 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -11,6 +11,7 @@ packages:- '../../packages/electron-mac-notifications'- '../../packages/napi-loader'- '../../packages/file-loaders'+ - '../../packages/html-artifact'- '../../packages/desktop-bridge'- '../../packages/device-control'- '../../packages/device-sandbox'