Skip to content
Back to search

lavish-axi

HTML is the new markdown. Lavish is the new editor for your HTML artifacts.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 14 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/kunchenguid/lavish-axi with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/kunchenguid/lavish-axi'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/kunchenguid--lavish-axi/badge.svg)](/listings/kunchenguid--lavish-axi)

HTML

<a href="/listings/kunchenguid--lavish-axi"><img src="/api/listings/kunchenguid--lavish-axi/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Install the Lavish skill in the [Agent Skills](https://agentskills.io) format with [`npx skills`](https://github.com/vercel-labs/skills):

npx skills add kunchenguid/lavish-axi --skill lavish

That is the entire setup - no npm install needed. The skill teaches your agent to run Lavish through `npx -y lavish-axi`, so the CLI comes along on demand. It stays a short stub and sends the agent to `npx -y lavish-axi --help`, `reply --help`, `design`, and `playbook` for current instructions, so an installed copy cannot go stale against a newer CLI. Its frontmatter also includes Hermes Agent metadata, so Hermes-compatible harnesses can categorize and surface it as a first-class productivity skill. This installs the public `lavish` skill. The repository also contains an internal `lavish-design` brand skill for maintainers; default `npx skills add ... --list` and skills.sh discovery hide it unless `INSTALL_INTERNAL_SKILLS=1` is set.

Then, in agents that expose skills as slash commands (Claude Code, for example), invoke it directly:

/lavish let's discuss our plan here

Or just ask for anything that is easier to grasp visually - a plan, comparison, diagram, table, code view, or report - and the agent loads the skill on its own when it recognizes the task.

By default the skill lands in the current project's skills directory (`.claude/skills/`, for example); add `-g` to install it for all projects (`~/.claude/skills/`).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

plugin.json · Manifest · 21 lines
  1. {
  2. "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
  3. "name": "lavish-axi",
  4. "version": "0.1.97",
  5. "description": "HTML is the new markdown. Lavish is the new editor for your HTML artifacts.",
  6. "author": {
  7. "name": "Kun Chen",
  8. "url": "https://github.com/kunchenguid"
  9. },
  10. "homepage": "https://github.com/kunchenguid/lavish-axi#readme",
  11. "repository": "https://github.com/kunchenguid/lavish-axi",
  12. "license": "MIT",
  13. "keywords": [
  14. "axi",
  15. "agent",
  16. "cli",
  17. "html",
  18. "review",
  19. "collaboration"
  20. ]
  21. }
README.md · README · 342 lines
  1. <h1 align="center">lavish-axi</h1>
  2. <p align="center">
  3. <a href="https://github.com/kunchenguid/lavish-axi/actions/workflows/ci.yml"
  4. ><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/kunchenguid/lavish-axi/ci.yml?style=flat-square&label=ci"
  5. /></a>
  6. <a href="https://github.com/kunchenguid/lavish-axi/actions/workflows/release-please.yml"
  7. ><img alt="Release" src="https://img.shields.io/github/actions/workflow/status/kunchenguid/lavish-axi/release-please.yml?style=flat-square&label=release"
  8. /></a>
  9. <a href="https://www.npmjs.com/package/lavish-axi"
  10. ><img alt="npm" src="https://img.shields.io/npm/v/lavish-axi?style=flat-square"
  11. /></a>
  12. <a href="https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-blue?style=flat-square"
  13. ><img alt="Platform" src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-blue?style=flat-square"
  14. /></a>
  15. <a href="https://x.com/kunchenguid"
  16. ><img alt="X" src="https://img.shields.io/badge/X-@kunchenguid-black?style=flat-square"
  17. /></a>
  18. <a href="https://discord.gg/Wsy2NpnZDu"
  19. ><img alt="Discord" src="https://img.shields.io/discord/1439901831038763092?style=flat-square&label=discord"
  20. /></a>
  21. </p>
  22. <h3 align="center">For when a rich editor is not rich enough.</h3>
  23. <p align="center">
  24. <img alt="Lavish Editor demo" src="lavish-editor-marketing/renders/lavish-editor-marketing.gif" width="960" />
  25. </p>
  26. HTML is the new markdown. Lavish is the new editor for your HTML artifacts.
  27. Agents are good at producing rich HTML artifacts, but the human-agent collaboration loop on such artifacts is lacking and falls back into screenshots and long responses for “tell me what to change.”
  28. That loses the thing HTML is best at: interactivity.
  29. Lavish Editor opens agent-generated HTML files in a local browser, lets you pinpoint elements and selected text, edit diagrams your agent authored as Mermaid whiteboards, and send feedback to the agent to address.
  30. - **Local-first** - Review local HTML artifacts with a local CLI and no cloud dependency in the core feedback loop; hosted sharing through third-party ht-ml.app is explicit and opt-in.
  31. - **Human-AI collaboration** - Annotate elements and selected text ranges, edit Mermaid whiteboard diagrams, and send messages to the agent without leaving Lavish Editor.
  32. - **Battery included** - Lavish Editor teaches your agent good visualization for common use cases such as product or technical plans, design explorations and more out of the box.
  33. Lavish Editor is an [AXI](https://axi.md), which means -
  34. - It's just a CLI any capable agent can run without setup.
  35. - It's optimized for agent ergonomics. TOON output, long polling, and contextual disclosure making it highly token efficient.
  36. - The skill and hooks below only handle discovery; agents learn to use the AXI by using it.
  37. ## Quick Start
  38. Install the Lavish skill in the [Agent Skills](https://agentskills.io) format with [`npx skills`](https://github.com/vercel-labs/skills):
  39. ```sh
  40. npx skills add kunchenguid/lavish-axi --skill lavish
  41. ```
  42. That is the entire setup - no npm install needed.
  43. The skill teaches your agent to run Lavish through `npx -y lavish-axi`, so the CLI comes along on demand.
  44. It stays a short stub and sends the agent to `npx -y lavish-axi --help`, `reply --help`, `design`, and `playbook` for current instructions, so an installed copy cannot go stale against a newer CLI.
  45. Its frontmatter also includes Hermes Agent metadata, so Hermes-compatible harnesses can categorize and surface it as a first-class productivity skill.
  46. This installs the public `lavish` skill.
  47. The repository also contains an internal `lavish-design` brand skill for maintainers; default `npx skills add ... --list` and skills.sh discovery hide it unless `INSTALL_INTERNAL_SKILLS=1` is set.
  48. Then, in agents that expose skills as slash commands (Claude Code, for example), invoke it directly:
  49. ```
  50. /lavish let's discuss our plan here
  51. ```
  52. Or just ask for anything that is easier to grasp visually - a plan, comparison, diagram, table, code view, or report - and the agent loads the skill on its own when it recognizes the task.
  53. By default the skill lands in the current project's skills directory (`.claude/skills/`, for example); add `-g` to install it for all projects (`~/.claude/skills/`).
  54. ## Other Ways to Use Lavish
  55. The skill is the recommended path, but it is not the only one.
  56. ### Zero setup
  57. Lavish is an AXI, so any capable agent can run the CLI directly with nothing installed at all.
  58. Just tell your agent:
  59. ```
  60. Use `npx -y lavish-axi` to write a product or technical plan for what we discussed.
  61. ```
  62. ### Session hook
  63. Want Lavish's ambient context - including your live open sessions - fed into every agent session instead of loading on demand?
  64. Install the CLI globally and opt into the hook:
  65. ```sh
  66. npm install -g lavish-axi
  67. lavish-axi setup hooks
  68. ```
  69. This installs a `SessionStart` hook for **Claude Code**, **Codex**, **OpenCode**, and **GitHub Copilot CLI** that surfaces open sessions, visualization playbooks, and usage guidance at the start of each session.
  70. Unlike the skill, the hook also shows your live open sessions, so a fresh agent session can resume an in-flight review.
  71. **Restart your agent session after running this** so the new hook takes effect.
  72. ### Agent Plugin
  73. Lavish also ships as an [Agent Plugin](https://agent-plugins.org) - the vendor-neutral packaging standard for skills and MCP servers - so clients that speak that format can load it directly.
  74. **No marketplace is involved.** The installed npm package _is_ the plugin: `plugin.json` sits at the package root next to the `skills/` directory, so whatever `npm install` already put on disk is a complete, conformant plugin. Install the CLI, then register it:
  75. ```sh
  76. npm install -g lavish-axi
  77. lavish-axi setup plugin
  78. ```
  79. That registers the installed package with every supported client it finds - **VS Code**, **Cursor**, and **GitHub Copilot CLI** - and reports which ones were absent. It is opt-in and idempotent, and it repairs the registered path after a reinstall or relocation. Reload each client afterward.
  80. Each client is registered independently: one that cannot be registered is reported with what to do about it, and never blocks the others or fails the command.
  81. To register by hand instead, point any client at the package directory (`npm root -g`/`lavish-axi`):
  82. | Client | Register with |
  83. | ------------------ | ------------------------------------------------------------------------------------------------------------------ |
  84. | VS Code | `"chat.pluginLocations": { "<package-dir>": true }` in user settings |
  85. | Cursor | link the package dir at `~/.cursor/plugins/local/lavish-axi` (`setup plugin` handles Windows link compatibility) |
  86. | GitHub Copilot CLI | `copilot plugin install <package-dir>` (or `copilot plugin install kunchenguid/lavish-axi` straight from the repo) |
  87. Codex and ChatGPT install plugins only from marketplace sources, so Codex users should use the session hook above instead.
  88. Lavish declares no MCP server - the CLI itself is the agent interface - so a plugin install brings the same `lavish` skill, and the skill and plugin are alternatives rather than a stack.
  89. ### From source
  90. ```sh
  91. git clone https://github.com/kunchenguid/lavish-axi.git
  92. cd lavish-axi
  93. pnpm install --frozen-lockfile
  94. pnpm run build
  95. pnpm link
  96. ```
  97. ## How It Works
  98. ```
  99. ┌───────────────┐
  100. │ Agent writes │
  101. │ artifact.html │
  102. └───────┬───────┘
  103. ▼
  104. ┌────────────────────────┐
  105. │ lavish-axi <file_path> │
  106. │ opens local browser UI │
  107. └───────┬────────────────┘
  108. ▼
  109. ┌────────────────────────┐
  110. │ Human annotates text │
  111. │ or elements, sends │
  112. │ chat, or queues layout │
  113. │ issues from the inbox │
  114. └───────┬────────────────┘
  115. ▼
  116. ┌────────────────────────┐
  117. │ lavish-axi poll waits │
  118. │ and returns prompts │
  119. │ the user queued │
  120. └────────────────────────┘
  121. ```
  122. - **File-path identity** - Sessions are keyed by the canonical HTML file path, so agents do not need opaque IDs.
  123. - **Portable artifacts** - The artifact runs in a sandboxed iframe while Lavish injects a small SDK for annotations, snapshots, feedback controls, and render-time layout checks.
  124. Author-defined links and popups can open in top-level tabs, while artifact documents remain sandboxed without same-origin access.
  125. Lavish does not inject any design system, so the saved HTML file renders identically whether you open it through `lavish-axi` or directly in a browser.
  126. Run `lavish-axi design` for the single source of agent-facing design guidance, including optional CDN snippets and the whiteboard (Mermaid) opt-in snippet.
  127. - **Self-paint warning** - `lavish-axi <html-file>`, `export`, and `share` run a render-free check for artifacts missing an explicit page background and return a one-line `self_paint_warning`.
  128. The check fails open - any stylesheet link, `@import`, Tailwind runtime script, `color-scheme`, or `html`/`body`/`:root` background signal suppresses it - and it never blocks the open.
  129. - **Open-time layout gate** - The browser chrome masks an artifact only while the real in-iframe audit waits for fonts and final geometry.
  130. The first completed client-side check reveals the artifact, whatever it found and even if reporting that check to the server fails; the gate never holds the review hostage waiting for a repair or a network round-trip.
  131. The user can click **Show anyway**, and a bounded safety timeout fails open from every gate state.
  132. If the review cannot load at all - the chrome's own script never runs, or the server does not answer the artifact's load request after several retries - the mask names the problem and offers **Check and reload** without removing the independent **Show anyway** escape.
  133. A review already loaded in another browser tab is named the same way, with a **Take over here** button that loads the artifact in the current tab, because Lavish loads an artifact in one tab at a time. The takeover warning reads "Unsent answers stay in the tab or window where you entered them; taking over in another window does not bring them along."
  134. - **Layout issues inbox** - Detection is passive. After fonts and finite animations settle, the injected SDK confirms severe failures from direct rendered evidence such as materially escaped meaningful content or required controls, clipped text fragments, viewport reachability, or near-total semantic occlusion.
  135. Explicit ellipsis and line clamp, standard visually hidden accessibility text, intentional scrollers or masks, parent overhang, generic element scroll geometry, decorative overlap, and uncertain motion do not produce findings by themselves.
  136. Proven failures are filed in a **Layout issues** button in the top bar, which is hidden while nothing is unresolved and otherwise shows the unresolved count.
  137. Its drawer lists each issue with severity, a plain-language explanation, the affected viewport, the target/component identity, when it was last seen, and its lifecycle state, plus per-issue **Reveal** (highlight it in the artifact) and **Dismiss** actions.
  138. Nothing is selected by default. The user picks issues (or **Select all**) and **Queue selected fixes** turns that whole group into one ordinary queued prompt, tagged `layout-warnings`, that reaches the agent through the normal feedback path when they send.
  139. Detection never returns `lavish-axi poll` and never wakes an agent; only the user queueing a fix does. The one exception is a fatal `artifact_failures` response, for failures that make the review itself unusable, such as the artifact document or one of its own local assets failing to load.
  140. - **Layout issue lifecycle** - Each issue is identified by a stable fingerprint of the diagnostic rule, the normalized target identity, and the viewport class, so repeat detections update one record instead of inflating the count.
  141. `Open` means the latest completed check for its viewport still detects it. `Queued for fix` means the user asked for a repair - it stays unresolved and counted, and cannot be queued again while that request is outstanding.
  142. `Resolved` requires a newer successful artifact load plus a complete check at the same viewport that no longer detects it; it then leaves the count but keeps a bounded history.
  143. `Still present` (recurring) means a queued issue survived a newer revision, so it is selectable again with its earlier attempt retained. `Unverified` means a reload or check failed or was incomplete, so the prior issue was preserved rather than cleared. `Returned` means a resolved issue came back on a later revision.
  144. Dismissal applies only to the current artifact revision; a later revision surfaces the issue again if it is still detected. A check at one viewport never clears an issue found at another, and a viewport removed from the configured diagnostic set (`LAVISH_AXI_DIAGNOSTIC_VIEWPORTS`, default all) is marked obsolete with an explicit reason rather than reading as fixed.
  145. - **Revisions legend** - Opt-in. After a round of feedback the agent regenerates the whole file, and a one-sentence edit is invisible on a long artifact. The agent can declare what it changed in the artifact itself: one `<script type="application/json" data-lavish-revisions>` array of `{ id, label, timestamp, summary }` entries, plus `data-lavish-revision="<id>"` on each block it edited or added. Run `lavish-axi design` for the snippet.
  146. A **Revisions** button then appears in the top bar with a legend listing each round - colour swatch, label, time, and the agent's summary - and **Reveal** steps through that round's changed blocks, flashing them one at a time.
  147. Each revision's swatch carries a distinct border style and fill pattern as well as a colour, so the rounds stay distinguishable without colour. Artifacts with no registry show no button and are otherwise unaffected, a malformed registry is ignored rather than surfaced as an error, and at most 6 revisions are listed - one per distinguishable swatch.
  148. Lavish never marks up the artifact for this: the legend lives in the browser chrome, so the served page stays identical to the saved file, and the registry and marks travel with the file through export.
  149. - **Live tab title and icon** - Opt-in. The browser tab adopts the artifact's `<title>` and first `<link rel="icon">` when it loads. A long-lived artifact can keep the tab current afterwards with `window.lavish.setDocumentMeta({ title, icon })`: a string sets the field (a title that is blank after trimming restores the load-time title), `null` restores the load-time value, and an omitted field is left alone. The title is trimmed to 120 characters and shown as `<title> · Lavish`; the icon must be a `data:image/svg+xml` URL of at most 8192 characters. Anything else is ignored. A value stays until the next call or until the tab itself reloads, so call again after each page update. The call is a no-op when the page is not open in Lavish, so feature-detect with `window.lavish?.setDocumentMeta?.(...)`.
  150. - **Local assets** - Copy local images, CSS, fonts, and scripts next to the HTML artifact and reference them with relative paths from that directory; root-prefixed paths such as `/assets/logo.png` will not resolve through Lavish's artifact route.
  151. - **Export and sharing** - `lavish-axi export` writes `<name>.export.html` by inlining local assets only, stripping the annotation SDK, and leaving remote CDN/font references as links that still need network access.
  152. `lavish-axi share` publishes the same local-inlined HTML to [ht-ml.app](https://ht-ml.app), a third-party hosting service not part of Lavish.
  153. Publishing sends the artifact to ht-ml.app's servers, public by default, or private and password-protected with `--private` (Lavish generates the password and returns it once, in the command output and in the browser publish dialog) or `--password <pw>` (one you supply, never echoed back). A generated password is a shared secret: give it to whoever should read the page, and expect it to appear in your agent's transcript, because the agent has to relay it. Lavish does not store it.
  154. The response includes a secret `update_key` shown once. Keep it to republish the same URL later with `--site <site_id> --update-key <key>`, which replaces the HTML in place and leaves the password alone unless you pass `--private` (rotate to a new generated one) or `--password <pw>` (set one). Locking a page that was public is not instant - it can keep answering from ht-ml.app's CDN cache for minutes after the password is set - while a page that was already private has no such cached copy.
  155. A page's password cannot be removed: ht-ml.app accepts a request to clear one and silently ignores it, so Lavish offers no way to make a private page public rather than telling you it did something the host did not do. Republish as a new page if you need a public URL.
  156. ht-ml.app has no delete endpoint, so `--unpublish --site <site_id> --update-key <key>` replaces the page with a short placeholder and locks it behind a discarded random password rather than removing it: the URL still resolves and the host still holds what was published. The content swap is immediate, but the lock is not: a page that was public can keep serving the placeholder to uncredentialed visitors from ht-ml.app's CDN cache for minutes afterwards. The `update_key` plus `--private` republishes real content behind a new password you can share.
  157. Bundling never fetches remote URLs, Lavish itself does not set a CSP, local reads stay confined and size-capped, and absolute `file://` paths outside safe inlined asset references are redacted before output.
  158. Per-asset and per-bundle inline caps default to 10 MB and 25 MB, overridable with `LAVISH_AXI_EXPORT_MAX_ASSET_BYTES` and `LAVISH_AXI_EXPORT_MAX_BUNDLE_BYTES`.
  159. Unresolved local assets or export notices such as author-set CSP meta tags and redacted file URLs are surfaced in command or browser output.
  160. Use `--token` or `LAVISH_AXI_HTML_APP_TOKEN` for an optional bearer token when publishing a new page (a republish or `--unpublish` authorizes with the `update_key` instead and rejects `--token`); set `LAVISH_AXI_HTML_APP_API_URL` to override the ht-ml.app API base and point `share` at a backend you control (see [Self-hosting the share backend](docs/self-hosting-share.md) for the contract it must implement).
  161. - **Live reload** - Lavish watches the HTML artifact file by default and preserves review context across reloads: the artifact iframe scroll position, an open annotation card's unsent text, and answers to `data-lavish-question` controls (application-owned form state is left alone). Supported review state and the unsent queue are saved in that tab's `sessionStorage` and survive a full reload of the review page in the same tab when browser storage is available. They are not shared with another tab or window; closing the owning tab can lose work that has not been sent. While a queued layout-issue batch is outstanding, closely spaced saves coalesce so one batch of fixes costs one refresh. To also reload on sibling asset changes, add `data-lavish-live-reload-root` to the root element or `<meta name="lavish-live-reload" content="root">`.
  162. If the element an unsent annotation was attached to is gone from the artifact for good, Lavish cannot reopen that card, and if the artifact replaces a queued note while you are editing it, the replacement is kept as the artifact sent it. Either way, Lavish writes your edited text into the conversation panel under **Unsent annotation** - selectable, never written over anything you have typed, and kept there across reloads; no note is ever dropped to make room for a newer one, and a note the browser refuses to store says so where it is shown.
  163. - **Feedback controls** - Native controls (radios, checkboxes, inputs, selects, buttons, labels, disclosure summaries, contenteditable) and custom widgets with an interactive ARIA role (`button`, `checkbox`, `combobox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `switch`, `tab`, `treeitem`) are interactive automatically, so they do not need `data-lavish-action`. A link (`<a href>`) stays annotatable when it carries one of these roles or sits inside such a widget.
  164. Artifacts can start in explore mode with `data-lavish-annotate="off"` on the root `<html>` element so stray clicks do not open annotation cards. Annotation stays on by default (or with `"on"`); unknown values default to on. The toolbar reflects the page default and can override it; the reviewer's choice persists across artifact reloads within that review page. See `lavish-axi playbook input` for author guidance.
  165. For reversible choices, let option clicks update local state, then queue exactly one final answer from a per-question submit or Queue answer button with `window.lavish.queuePrompt()`.
  166. If someone may open a decision artifact as a standalone HTML file, `lavish-axi playbook input` provides an optional Copy all answers control they can use to paste their form answers back into chat.
  167. Mark only custom (non-native) clickable elements with `data-lavish-action` so Lavish does not annotate them, and use `data-lavish-question` or `queueKey` when pre-send updates for the same question should replace each other.
  168. Everything you send is part of the conversation: a note on an element, a text selection, a table cell, a diagram node, a whiteboard, a layout-issue batch, or a composer message each becomes a bubble on your side of the Conversation panel, with an anchor line naming what it was attached to (the element tag, text selection, table cell, diagram node, whiteboard, or layout issues), a quoted excerpt, and, when available, the selector on hover. A note you have queued but not sent sits at the end of the conversation as a dashed bubble labelled **Queued** with edit and remove controls. Clicking the bubble or its edit control opens its words for editing in place and scrolls the artifact to the element it points at; clicking that element again in annotate mode opens the same note rather than a fresh card. Saving a note with no words and no images removes it, and **Send** delivers an open edit as typed. While its batch is in flight it reads **Sending** and can no longer be edited, and once the server accepts it, it settles in place as a sent bubble in every tab of the session. The panel keeps the newest stored transcript up to 5 MiB; older bubbles drop from view, but an accepted note still settles and is not sent twice. Agent replies render a small Markdown subset - paragraphs, line breaks, headings as bold lead lines, bullet and numbered lists, fenced and inline code, bold, italic, and http(s) links - while tables, images, and raw HTML stay as the text the agent wrote; your own messages keep their line breaks and are never parsed.
  169. On wider screens, the conversation and the queued notes share one scrollable Conversation panel above a sticky composer, so long feedback queues do not push the text box or send controls off screen. The sidebar button in the top bar hides that panel so the artifact takes the full width, and shows it again; while it is hidden the button counts queued notes or marks an agent reply you have not seen, and the choice is remembered in this browser for every review.
  170. The browser chrome keeps editing actions in the overflow menu (copy path, reload artifact, copy DOM snapshot, export standalone HTML, publish link, end session), while the composer exposes **Send & End** beside **Send to Agent** to submit queued prompts and user-ended attribution together. Once **Send & End** starts, Lavish pauses new feedback, waits up to 5 seconds for feedback preparation already underway, keeps any open annotation draft intact until delivery succeeds, then holds that exact terminal batch. A completed reservation survives a page reload, including when its prompts were already delivered and only the pending end remains; incomplete preparation is not restored. If preparation times out, Lavish keeps the review open and its existing queue editable with a visible error. A transient delivery failure permits only retrying the same terminal batch through **Send & End** until it succeeds. If a snapshot makes the request too large (HTTP 413), Lavish retries that exact batch once without the optional snapshot. An actionable attachment rejection (HTTP 400), recoverable layout-selection conflict (HTTP 409), or unrecoverable 413 instead cancels the terminal reservation without ending the session, keeps the prompts queued, and restores editing, removal, **Send to Agent**, **Send & End**, and **End session** so the reviewer can revise or remove stale feedback before submitting again.
  171. Unsent queued notes belong to the tab where you entered them, not to a server-shared draft. Empty **Send to Agent** reports "Nothing queued in this tab." followed by the same message: "Unsent answers stay in the tab or window where you entered them; taking over in another window does not bring them along." Annotate mode alone does not queue a note, so use the annotation card's **Queue** action first. Only feedback accepted by **Send** is stored on the server for delivery to the agent.
  172. Composer feedback is visibly queued before the text box clears and stays queued until acknowledged. Send waits up to 5 seconds for the artifact's DOM snapshot, then delivers without that optional context if the frame no longer answers; a late snapshot cannot submit the batch twice. A failed or still-unacknowledged POST keeps the queue and shows persistent recovery guidance unless a transcript sync proves the server already accepted that feedback.
  173. - **Reviewing on a phone** - Below 860px wide, the artifact takes the whole screen above a **Conversation** dock, and the conversation opens as a bottom sheet over it: tap the dock, swipe it up, or press the chevron to raise it; tap the dimmed artifact, swipe the sheet down, press the chevron, or press Escape to lower it. The dock reports what matters while the sheet is down - how many prompts are queued, a reply that arrived while you were reading, or whether the agent is listening - and the sheet stays open across a reload of the review page. The sheet sizes itself to the visible viewport and respects safe-area insets; if the keyboard or attachments leave little room, conversation content yields or scrolls while the send actions remain pinned above the bottom edge. In landscape the sheet covers the top bar as well. Wider screens keep the side-by-side layout.
  174. - **Keyboard shortcuts** - In the chrome composer, Enter sends queued prompts and Shift+Enter inserts a newline.
  175. In the annotation card, Enter queues the annotation, Shift+Enter inserts a newline, and Ctrl+Enter (Cmd+Enter on macOS) queues it and sends all queued prompts immediately. Escape closes the card, same as Cancel, but only while it is empty (no text, no attachment); with unsent text or an attachment present, Escape does nothing rather than risk discarding it.
  176. While editing a queued note, Enter saves it, Shift+Enter inserts a newline, and Escape discards the edit.
  177. Cmd+I or Ctrl+I toggles between annotate and explore mode from either the browser chrome or the artifact iframe, including while focus is in a textarea or control.
  178. In annotate mode a plain click on a link annotates it; Ctrl+click (Cmd+click on macOS) follows the link instead, opening it in a new tab as the browser normally would, without leaving annotate mode. Off macOS, Meta+click (the Windows or Super key) annotates like a plain click.
  179. - **Agent presence** - The browser shows when no agent is listening and keeps human feedback actions available while the agent is working. Feedback accepted by **Send** is queued on the server for the next successful `lavish-axi poll` delivery even across reloads; never-sent notes remain in the originating tab. An agent reply concludes delivered work and returns presence to waiting (see the CLI Reference for reply and poll commands). A supervisor-owned process listener is shown as an external listener rather than an idle captain turn.
  180. - **Delivery receipts** - Every note you have sent carries three emoji under it that light up in turn: 👀 **Seen** when a `lavish-axi poll` takes the note, 🛠️ **Working** when the artifact file changes after that, and ✅ **Done** when the agent replies. A step that has not happened yet is the same emoji greyed out. All three come from what the server observes; the agent does nothing extra. Until 👀 lights, the row says why: no agent is listening, or the agent is busy and the note is delivered on its next poll. A note answered without touching the artifact goes Seen to Done with Working still grey. A reply marks every note the agent has seen as Done, not notes still waiting for a poll. Each emoji names its step and time on hover and to screen readers. Notes sent before receipts existed show no receipt row.
  181. In a Herdr-managed pane, set `LAVISH_AXI_HERDR_CHIME=1` to show a Herdr request notification and play its chime once an indefinite poll enters the waiting state. Immediate queued feedback and timed debug polls do not trigger a notification. The integration is off unless both `LAVISH_AXI_HERDR_CHIME` and Herdr's `HERDR_ENV` session marker equal `1`; leaving either unset or using any other value opts out. Notification delivery runs without blocking feedback: if Herdr is unavailable, rejects the notification, stalls, or fails, the poll continues unchanged.
  182. Closing the last review tab while a poll is active starts a reconnect grace period, 10 seconds by default. A reload or quick reconnect keeps an active poll waiting; if every review stays disconnected, the poll returns `browser_disconnected` without ending the resumable session, and the agent asks whether to reopen or end it instead of acting uninvited.
  183. A phone that locks its screen or backgrounds the tab drops the connection too, so set `LAVISH_AXI_DISCONNECT_GRACE_MS` on the server to a longer millisecond budget, or to `0` or `off` so a disconnect never ends the poll (it then waits for feedback, an end, or its own timeout). Empty or invalid values keep the 10-second default.
  184. The no-timeout poll always writes an immediate stderr banner so it is visibly not hung; it adds the periodic stderr wait ticks only in an interactive terminal, so when stderr is piped (as under agent harnesses) the captured output carries no tick noise. Stdout always stays reserved for the final response; if the poll is interrupted or times out before feedback arrives, re-run it because feedback remains queued until delivery. Poll delivery consumes the response, so read the complete response before truncating or filtering it.
  185. Codex-specific guidance keeps that poll attached to the active turn instead of hiding it in a background task, because completed background tasks may not resume the agent.
  186. - **Session end etiquette** - Lavish tracks who ended a session: a human clicking **End session** (or **Send & End**) in the browser is a user-initiated end, while `lavish-axi end <html-file>` is agent-initiated.
  187. When either side ends the session, every open review tab becomes visibly read-only and disables its feedback controls; feedback submitted after the end is refused instead of being accepted without an agent to receive it.
  188. A plain `lavish-axi <html-file>` after a user-initiated end refuses to reopen the browser and returns guidance instead; pass `--reopen` only when the user asks for further review or something important needs their visual attention.
  189. Agent-initiated ends keep reopening normally, same as before.
  190. `lavish-axi poll`'s `ended` response and the `feedback` response for the final batch before an end both carry `next_step` guidance telling the agent to stop polling and deliver remaining updates in chat instead of reopening.
  191. - **Precise targets** - Text annotations include selected text plus range anchors, and text selections carry those anchors only.
  192. Clicking an element inside a table also carries the cell's visible row and column names alongside the exact CSS locator, so filtered or sorted rows do not make feedback look misdirected.
  193. When merged cells make either name ambiguous, Lavish leaves that name out rather than guessing; an explicit `<th scope="row">` remains authoritative even when a `rowspan` makes the row's position ambiguous.
  194. The CSS locator still points at the exact element you clicked, so an annotation with an omitted name is only less descriptive, never mislabelled.
  195. - **Image attachments** - Attach reference images (PNG, JPEG, WebP) in either the Conversation composer or an annotation card by pasting, drag-dropping, or using its image picker; each image shows a thumbnail chip with upload, remove, retry, and error states. If a sent image is later evicted under the attachment storage limits, its transcript-history thumbnail becomes an **Image expired** placeholder.
  196. A paste containing both text and images preserves the text while attaching the images (a copied file's own name or path is treated as placeholder and not pasted). Conversation messages may contain text and images together or images only.
  197. Images are stored under the state dir and the queued prompt carries a server-generated absolute `path` and content-hash `id` (plus mime and dimensions) - never the raw bytes - so `lavish-axi poll` hands the agent a local file path to open.
  198. Limits are `LAVISH_AXI_MAX_ATTACHMENT_BYTES` (default 10 MiB per image), `LAVISH_AXI_MAX_ATTACHMENTS_PER_PROMPT` (default 4), and `LAVISH_AXI_MAX_PROMPT_ATTACHMENT_BYTES` (default 25 MiB per prompt); if any image is missing or any prompt breaches a count or byte cap, the entire send batch is rejected, the queue is preserved, and the reason is surfaced in the composer rather than silently dropping images.
  199. As a browser-side abuse guard, each chrome page allows 30 upload attempts per rolling minute, 4 uploads in flight at once, and 256 MiB of attempted image bytes over its lifetime; rejected uploads stay visible for retry or removal.
  200. Unreferenced attachments expire after `LAVISH_AXI_ATTACHMENT_TTL_MS` (default 7 days; `0`/`off` disables); `LAVISH_AXI_MAX_ATTACHMENT_DISK_MB` (default 512 MiB; `0`/`off` disables) caps total attachment disk and may evict older unreferenced images sooner.
  201. The cap is enforced when an image is uploaded, not just periodically: the upload first reclaims unreferenced files (oldest first, and never one added within the last hour), and if it still would not fit, that upload is refused with a storage-full error on its chip instead of discarding an image the user is about to send.
  202. - **Mermaid diagrams** - Whiteboards are an opt-in: agents author a diagram as Mermaid only when you ask for an editable whiteboard, and hand-authored inline SVG illustrations are the default figure medium otherwise.
  203. In the Lavish browser, every rendered Mermaid diagram in a `.mermaid` container becomes an embedded editable Excalidraw whiteboard.
  204. Click a diagram to unlock editing, and use its Fullscreen action to edit it over the whole viewport.
  205. Whiteboard scenes autosave locally.
  206. If a live reload changes the Mermaid source, an unmodified whiteboard silently re-converts to the new diagram. If the reviewer had edited the scene, reopening it lets them re-convert and discard the saved edits or keep editing the saved scene.
  207. Use **Queue feedback** to add a bounded edit summary plus local `.excalidraw` scene and PNG preview paths to the Conversation panel, then click **Send to Agent** to deliver it.
  208. The agent updates the artifact's Mermaid source, which remains authoritative.
  209. Flowchart, sequence, class, ER, and state diagrams convert to editable shapes; other diagram types are images that reviewers can draw and annotate.
  210. Lavish changes only the browser view, so saved, standalone, and exported artifacts still render plain Mermaid.
  211. - **Whiteboard libraries** - Copy Excalidraw library files (`.excalidrawlib`, for example from [libraries.excalidraw.com](https://libraries.excalidraw.com)) into `~/.lavish-axi/excalidraw-libraries/`, or `LAVISH_AXI_STATE_DIR/excalidraw-libraries/` when set. Every whiteboard's library panel lists their items, and an item you drop on the canvas reaches the agent by name in the edit summary.
  212. Agents run `lavish-axi libraries` to find item refs and can show a flowchart node as one of those icons by adding a `%% lavish-icon <node-id> <library-id>/<item name>` comment to the Mermaid source. Mermaid ignores the comment, so saved, exported, and shared copies, and whiteboards missing that library, show the plain node.
  213. Lavish only reads that directory and never downloads libraries. Files over 10 MB, more than 25 MB or 5,000 items in total, and unreadable files are skipped; `lavish-axi libraries` lists each skip with its reason.
  214. Each library carries its author's terms (AWS Architecture Icons, for example, are covered by AWS's own usage terms), so check them before using one.
  215. - **Server cleanup** - The detached server stops after the last session ends when nothing is connected, or after `LAVISH_AXI_IDLE_TIMEOUT_MS` (default 30 minutes) with no browser or poll connections.
  216. Set `LAVISH_AXI_IDLE_TIMEOUT_MS=0` or `off` to disable idle self-shutdown.
  217. - **Server upgrades** - One background server serves every session, so upgrading `lavish-axi` while reviews are open makes the next `lavish-axi <html-file>` replace that server. Only a newer CLI replaces an older server: a CLI older than the running server uses it as is, so two installed versions on one machine do not restart each other's server. Releases up to and including 0.1.86 still replace a server of a different version, so this turn-by-turn restart stops only when both installed versions contain this fix. Only the review page for the artifact being opened reloads itself once the replacement answers - and not even that one while you have unsent annotation text open, which gets the same banner instead so the reload is yours to make. Every other open review page keeps working and shows a banner reading "Lavish was updated. This page is running the previous version.", with a Check and reload button and a Dismiss button, so no page you are reading reloads on its own. After `lavish-axi stop` those pages say Lavish was stopped and to reload after you start it again, and a restart that only picks up a local build says that rather than claiming an update. An open review page whose server simply goes away - idle self-shutdown, a crash, a machine that slept - shows that same banner once reconnecting has failed for a few seconds, rather than retrying a dead server silently while looking fine; it clears itself if the server comes back, and dismissing it keeps it dismissed until then.
  218. A page still using the legacy event stream reloads once when it reconnects to the replacement server, moving itself onto the current transport without retaining an HTTP connection. If unsent annotation text is open, it shows the neutral server-restarted banner instead and waits for you to reload.
  219. Every **Check and reload** control asks the server whether it is running before it navigates; while nothing answers, the page stays where it is and says so, and a check that gets no answer at all says that instead of guessing.
  220. In-flight `lavish-axi poll` commands end with an interrupted-poll error and are safe to re-run; server-accepted feedback remains queued until delivery, while never-sent notes and supported annotation drafts survive a same-tab reload as described under **Live reload**.
  221. A page waits for the replacement rather than reloading into a port nothing is listening on, and tells the user to restart Lavish if it never returns.
  222. - **Local-first state** - Session state stays under `~/.lavish-axi/` by default, or `LAVISH_AXI_STATE_DIR` when set.
  223. - **Diagnostic viewports** - `LAVISH_AXI_DIAGNOSTIC_VIEWPORTS` sets which viewport classes the layout-issue inbox tracks (`mobile`, `compact`, `desktop`; comma-separated, default all). Warnings whose class leaves the set are marked obsolete with an explicit reason instead of silently reading as fixed.
  224. - **Server port** - Set `LAVISH_AXI_PORT` to choose the server port; it defaults to `4387`.
  225. - **Network binding** - With Tailscale running, the review server automatically listens only on loopback (`127.0.0.1`) and this machine's Tailscale IPv4 address - never on `0.0.0.0` or every interface. The generated session link uses the machine's MagicDNS name, so it is the phone-ready URL to open from another device on the same tailnet. When Tailscale is absent or down, Lavish silently falls back to loopback-only and prints no phone URL. If Tailscale is running but MagicDNS is unavailable, Lavish visibly warns that phone access is unavailable and remains loopback-only. Binding beyond loopback exposes an unauthenticated server that can read and serve arbitrary local files to devices that can reach it, so the tailnet should be trusted. Any explicit `LAVISH_AXI_HOST` overrides automatic Tailscale binding; wildcard values are restricted to loopback, while a non-wildcard value selects that concrete bind address, and the server listens on loopback as well so every local CLI finds it whatever its own `LAVISH_AXI_HOST` says. An address that cannot be bound - the tailnet address while another process holds it, while Tailscale restarts, or an explicit hostname that temporarily does not resolve - is reported as `network_warning` in `lavish-axi <file>` output and logged to `server.log`; session links point at loopback meanwhile unless `LAVISH_AXI_LINK_HOST` overrides them, and the server keeps retrying that address in the background and immediately on the next CLI invocation. Once it binds, the warning clears and new session links use it again, with no restart. If no listener can bind, startup fails rather than claiming a reachable server. `LAVISH_AXI_LINK_HOST` controls the link host when automatic Tailscale binding is disabled.
  226. - **One server per port** - Agents on one machine can run with different `LAVISH_AXI_HOST` settings, or none, and still share one server: before starting one, the CLI looks for a running server on its configured host, loopback, and every other local address. A running server that was never asked to listen on the address a CLI's `LAVISH_AXI_HOST` names is replaced once by a server that listens on that address plus every address the old one served, keeping all sessions. Upgrade and network-change restarts keep every address the old server served in the same way, except an address that is no longer on this machine. Switching to an address the running server already serves, including loopback, reuses it, so run `lavish-axi stop` first to drop an address. Another server of the same installation (the same state directory) found on the same port at a different address is shut down through its own shutdown endpoint, after the kept server is made to serve that address too, so review links already handed out there keep working. A server belonging to another state directory that reports its installation identity is never used, replaced, or stopped: when it holds loopback or the configured address, the CLI fails with an error naming its state directory, so pick another `LAVISH_AXI_PORT`. Older servers that cannot report an identity are treated as belonging to this installation only at those control addresses, for upgrade compatibility.
  227. - **Allowed hosts** - To defend against DNS rebinding, the server rejects (`403`) any request whose `Host` header is missing or not one it answers to: loopback names plus the concrete Tailscale IPv4 address and MagicDNS name when the Tailscale listener is successfully bound. If you configure a reverse proxy or another intentional hostname, list it in `LAVISH_AXI_ALLOWED_HOSTS` (whitespace-separated). Behind a reverse proxy, the forwarded `X-Forwarded-Host` is validated against the same list, so add the public hostname there and have the proxy send it together with `X-Forwarded-Proto`. Set `LAVISH_AXI_ALLOWED_HOSTS` to `*` to disable the check entirely, only when the server sits behind your own authentication or proxy. Mutating routes also reject a present foreign `Origin` or `Referer` (`403`); header-less CLI control requests remain allowed where supported.
  228. - **Browser opening** - Set `LAVISH_AXI_NO_OPEN=1`, equivalent to `--no-open`, to create or resume a session without launching a browser window.
  229. ## CLI Reference
  230. | Command | Description |
  231. | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  232. | `lavish-axi` | Show current sessions and usage guidance. |
  233. | `lavish-axi update` | Check for or apply the latest npm release through the AXI SDK self-updater. |
  234. | `lavish-axi <html-file>` | Open or resume a Lavish Editor session, with the open-time layout gate enabled by default. Unresolved layout issues from earlier in the session are preserved. Refuses to reopen a session the user explicitly ended from the browser unless `--reopen` is passed. |
  235. | `lavish-axi poll <html-file>` | Long-poll until the user sends feedback, ends the session, or leaves every review disconnected past the reconnect grace period; detected layout issues arrive only when queued. On `browser_disconnected`, ask before reopening or ending the still-resumable session. On `ended`, stop polling and do not reopen uninvited. |
  236. | `lavish-axi reply <html-file>` | Post an agent reply and exit 0 only after the server accepts it, so the review page stops showing Working. Exits non-zero if the server does not confirm within 10 seconds. Use this when handing a result back without starting a long-poll. `poll --agent-reply` still posts a reply and then waits. |
  237. | `lavish-axi end <html-file>` | End a session as the agent; unlike a user-initiated end from the browser, this still allows a plain reopen later. |
  238. | `lavish-axi export <html-file>` | Write a portable copy of the artifact: one HTML file with its local assets inlined, so it opens with no server and no sibling files. Remote CDN/font references are left as links. |
  239. | `lavish-axi share <html-file>` | Publish the artifact (local assets inlined) to [ht-ml.app](https://ht-ml.app), a third-party host not part of Lavish, and print a visitable URL plus a secret update key; shares are public by default, `--private` locks one behind a generated password, and the same command republishes or unpublishes an existing page with `--site`/`--update-key`. |
  240. | `lavish-axi stop` | Shut down the background server. |
  241. | `lavish-axi playbook [id]` | List focused artifact guidance or show one playbook; agents must open each matching playbook before writing HTML. |
  242. | `lavish-axi libraries` | List the Excalidraw libraries in the whiteboard library directory; `--search <text>` or `--library <id>` lists item refs for `%% lavish-icon` nodes. |
  243. | `lavish-axi design` | Show agent-facing design guidance, including optional CDN snippets and the whiteboard (Mermaid) opt-in snippet. |
  244. | `lavish-axi setup hooks` | Install or repair optional SessionStart hooks for Claude Code, Codex, OpenCode, and GitHub Copilot CLI; restart the agent session afterward. |
  245. | `lavish-axi setup plugin` | Register the installed package as an [Agent Plugin](https://agent-plugins.org) in VS Code, Cursor, and GitHub Copilot CLI; opt-in, idempotent, no marketplace involved. Reload each client afterward. |
  246. | `lavish-axi server` | Run the local Lavish Editor server. |
  247. Known playbook IDs: `diagram`, `table`, `comparison`, `plan`, `code`, `input`, `explanation`, `slides`.
  248. One artifact often combines several playbooks, such as a plan that includes a comparison and a diagram, so agents must match against each `use_when` trigger and open every matching playbook before writing HTML.
  249. For flows, architecture, state, or sequence diagrams, open the diagram playbook for the recommended tooling and SVG guidance.
  250. ### Flags
  251. | Command | Flag | Description |
  252. | ------------------------ | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  253. | `lavish-axi <html-file>` | `--no-open` | Ensure the server/session exists without opening another browser window. |
  254. | `lavish-axi <html-file>` | `--no-gate` | Skip the open-time layout curtain for this browser open. |
  255. | `lavish-axi <html-file>` | `--reopen` | Reopen a session the user explicitly ended from the browser; without it, a plain open refuses and explains why instead of reopening uninvited. |
  256. | `lavish-axi update` | `--check` | Report current vs latest npm version without installing an update. |
  257. | `lavish-axi export` | `--out <path>` | Write the export to a specific path instead of `<name>.export.html` next to the source. |
  258. | `lavish-axi share` | `--private` | Make the page private behind a password Lavish generates and returns once; hand it to viewers as a shared secret. |
  259. | `lavish-axi share` | `--password <pw>` | Make the third-party ht-ml.app page private with a password you supply; viewers must supply the password. An empty or whitespace-only value (an unquoted `$PW` that is unset) is refused rather than publishing a public page. |
  260. | `lavish-axi share` | `--site <site_id>` | Republish an existing page in place (with `--update-key`) instead of creating a new one; the URL does not change. |
  261. | `lavish-axi share` | `--update-key <key>` | The secret returned when the page was published; required to republish or unpublish it. |
  262. | `lavish-axi share` | `--unpublish` | Replace a published page with a locked placeholder (ht-ml.app cannot delete); takes `--site` and `--update-key` and no file. |
  263. | `lavish-axi share` | `--token <t>` | Attach an optional bearer token (`LAVISH_AXI_HTML_APP_TOKEN`) when creating a page; never required, and rejected on a republish or `--unpublish`, where the `update_key` is the credential. |
  264. | `lavish-axi poll` | `--owner <label>` | Identify the process listening for this session; the non-empty label appears in the home session listing. `none` is reserved for sessions without a listener. A second concurrent poll is refused instead of silently returning `waiting`. |
  265. | `lavish-axi poll` | `--takeover` | Explicitly displace the current poll listener. The displaced poll exits with typed `LISTENER_REPLACED`; without this flag, the new poll fails with typed `LISTENER_ACTIVE`. |
  266. | `lavish-axi poll` | `--agent-reply "..."` | Show a concise agent reply in the existing browser chat, conclude delivered work (every note the agent has seen is marked Done), and return presence to waiting before polling again. Keep replies concise by default. |
  267. | `lavish-axi poll` | `--agent-reply-file <path>` | When a longer reply is genuinely necessary, read Markdown from a file (`-` for stdin) so newlines survive quoting. Use blank-line paragraphs, `- ` / `1. ` lists, and `## ` headings so the Conversation panel renders it scannably. The Markdown subset is under Feedback controls. Cannot be combined with `--agent-reply`. |
  268. | `lavish-axi poll` | `--timeout-ms <ms>` | Test/debug escape hatch only; agents should normally omit it and leave the long poll running. |
  269. | `lavish-axi reply` | `--agent-reply "..."` | Concise reply text. Required unless `--agent-reply-file` is set. The command exits 0 only after the server accepts it. Empty text is refused. Prefer this over `poll --agent-reply` when you are not about to long-poll. |
  270. | `lavish-axi reply` | `--agent-reply-file <path>` | Read the reply from a file (`-` for stdin) so newlines survive quoting. Cannot be combined with `--agent-reply`. Same Markdown guidance as `poll --agent-reply-file`. |
  271. | `lavish-axi stop` | `--port <port>` | Shut down a server running on a non-default port. |
  272. | `lavish-axi server` | `--verbose` | Log session and watcher events to stderr; can also be enabled with `LAVISH_AXI_DEBUG=1`. Detached server output is appended with UTC timestamps to `~/.lavish-axi/server.log` (or `LAVISH_AXI_STATE_DIR/server.log`) for startup, shutdown-cause, and crash diagnostics. |
  273. | `lavish-axi server` | `--also-listen <host>` | Also listen on this concrete address (repeatable). The CLI passes it when it replaces a running server, so the replacement keeps every address the old one served; see One server per port. |
  274. ## Telemetry
  275. The npm release sends anonymous usage telemetry to an [Umami](https://umami.is) server at `https://a.kunchenguid.com`. The host and website ID are baked into the published bundle at build time, so telemetry is on by default for `npx -y lavish-axi`.
  276. Each `lavish-axi` run sends two requests, except `lavish-axi --version` (also `-v` and `-V`), which sends none: a page view when the command starts, and a `command` event when it finishes. Both carry:
  277. - the command name (for example `open`, `poll`, or `home` when you run it with no command), but not its arguments, file paths, artifact content, or prompts
  278. - the Lavish version, `process.platform`, and `process.arch`
  279. The `command` event also carries a `status` field: `success`, or `error` only when the CLI itself throws. A command that fails and sets a nonzero exit code is handled by the CLI framework, so it still reports `success`. No user identifier is sent. Requests time out after 1 second, and failures are ignored, so telemetry never changes what a command does.
  280. Set `LAVISH_AXI_TELEMETRY=0` (or `false` or `off`) to turn it off. A build from source sends nothing unless `LAVISH_AXI_UMAMI_WEBSITE_ID` is set, and `LAVISH_AXI_UMAMI_HOST` overrides the host.
  281. ## Development
  282. ```sh
  283. pnpm run check # Run all verification commands
  284. pnpm run build # Bundle the publishable CLI, chrome, and design assets
  285. pnpm run build:skill # Regenerate the installable lavish skill
  286. pnpm test # Run node:test tests
  287. pnpm run lint # Run ESLint
  288. pnpm run format:check # Check Prettier formatting
  289. pnpm run typecheck # Run TypeScript checkJs validation
  290. ```
src/cli.js · Bundled script · 2,664 lines · 1 finding marked
  1. import { spawn, spawnSync } from "node:child_process";
  2. import {
  3. closeSync,
  4. createReadStream,
  5. existsSync,
  6. mkdirSync,
  7. openSync,
  8. readFileSync,
  9. realpathSync,
  10. writeFileSync,
  11. } from "node:fs";
  12. import { access, readFile, writeFile } from "node:fs/promises";
  13. import { get as httpGet } from "node:http";
  14. import { isIP } from "node:net";
  15. import os from "node:os";
  16. import path from "node:path";
  17. import { fileURLToPath } from "node:url";
  18. import { AxiError, installSessionStartHooks, RESERVED_COMMANDS, runAxiCli } from "axi-sdk-js";
  19. import { createDesignOutput, DESIGN_PRIORITY_RULE, DESIGN_SYSTEM_HINT } from "./design-reference.js";
  20. import {
  21. buildSelfContainedHtml,
  22. exportFileName,
  23. exportWarningSummaries,
  24. splitExportWarnings,
  25. } from "./export-bundle.js";
  26. import {
  27. createUnpublishedPageHtml,
  28. hostRejectedShareWrite,
  29. normalizeSiteId,
  30. publishedDespiteError,
  31. publishToHtmlApp,
  32. updateHtmlApp,
  33. } from "./html-app.js";
  34. import { localInterfaceAddresses } from "./local-address.js";
  35. import {
  36. clientHost,
  37. defaultPort,
  38. ensureStateDir,
  39. hostForUrl,
  40. isWildcardHost,
  41. LOOPBACK_HOST,
  42. resolveConcreteListenHosts,
  43. serverLogFile,
  44. stateDir,
  45. stateFile,
  46. stateId,
  47. } from "./paths.js";
  48. import {
  49. computeVsCodePluginLocationsUpdate,
  50. linkCursorLocalPlugin,
  51. readPluginManifest,
  52. resolveCursorLocalPluginsDir,
  53. resolvePluginRoot,
  54. resolveVsCodeSettingsFile,
  55. spawnPluginClientSync,
  56. writeTextFileAtomically,
  57. } from "./plugin.js";
  58. import { findPlaybook, listPlaybooks, playbookIds, PLAYBOOK_ROUTER_HELP } from "./playbooks.js";
  59. import { analyzeSelfPaint, SELF_PAINT_WARNING } from "./self-paint.js";
  60. import { resolveDesignAssetPath, serve } from "./server.js";
  61. import { isHtmlPath } from "./artifact-path.js";
  62. import { canonicalFile, sessionKey, SessionStore } from "./session-store.js";
  63. import { generateSharePassword } from "./share-password.js";
  64. import { initDefaultTelemetry } from "./telemetry.js";
  65. import { excalidrawLibrariesDir, loadExcalidrawLibraries } from "./whiteboard-library-store.js";
  66. const SHARE_VALUE_FLAGS = ["--password", "--token", "--site", "--update-key"];
  67. const COMMANDS = new Set([
  68. "open",
  69. "poll",
  70. "reply",
  71. "end",
  72. "stop",
  73. "server",
  74. "playbook",
  75. "design",
  76. "setup",
  77. "export",
  78. "share",
  79. "libraries",
  80. ]);
  81. // SDK-reserved built-ins (e.g. `update`) must reach runAxiCli untouched; otherwise
  82. // the bare-arg normalization below would rewrite them into the hidden `open` command.
  83. const RESERVED = new Set(RESERVED_COMMANDS);
  84. const DESCRIPTION =
  85. "Lavish Editor helps agents turn rich HTML artifacts into collaborative human review surfaces. Whenever you are about to give user a complex response that will be easier to understand via a rich / interactive page, consider using Lavish Editor. " +
  86. "First generate an interactive HTML artifact according to user request, then run `lavish-axi <html-file>` so the user can visually review it, annotate elements or selected text, queue prompts, and send feedback back through `lavish-axi poll`.";
  87. export const POLL_WAKE_PATH_RULES = Object.freeze([
  88. "Keep the poll in the foreground by default and let it return the feedback directly to the agent.",
  89. "A background poll is allowed only through a harness-native tracked background-job facility whose completion result is guaranteed to resume or notify the same agent.",
  90. "Never use `nohup`, shell `&`, `disown`, redirected fire-and-forget processes, or a detached terminal without an explicit verified callback merely to keep polling alive.",
  91. "If the harness has no completion-aware background facility, use the foreground poll or first wire a verified wake callback into the surrounding supervisor.",
  92. "Do not tell the user the artifact is being monitored until that wake path is live.",
  93. "If the poll gets killed or times out before feedback arrives, re-run it - feedback remains queued until delivery. Poll delivery consumes the response, so read it completely.",
  94. "If it returns browser_disconnected, the review window stayed disconnected past its reconnect grace period but the session remains resumable; ask the user whether to reopen or end it, and do neither uninvited.",
  95. ]);
  96. export const POLL_SEND_AND_END_RULE =
  97. "`Send & End` ends the session. Its final feedback is still delivered once. After that response, polling stops, and the agent must not reopen the session uninvited.";
  98. export const POLL_AGENT_REPLY_RULE =
  99. "Keep the reply concise. Only when a longer reply is genuinely necessary, use Markdown structure - blank-line paragraphs, `- ` / `1. ` lists, `## ` headings - so it renders scannably instead of a wall of text, and pass that body with `--agent-reply-file <path>` (`-` reads stdin) so newlines survive quoting.";
  100. const POLL_AGENT_REPLY_HELP_POINTER =
  101. "The Conversation panel's Markdown subset is in README's Feedback controls bullet.";
  102. const POLL_AGENT_REPLY_NEXT_POINTER =
  103. "The Conversation panel's Markdown subset is in `lavish-axi poll --help` and README.";
  104. const POLL_VALUE_FLAGS = ["--agent-reply", "--agent-reply-file", "--timeout-ms", "--owner"];
  105. const AGENT_REPLY_JSON_LIMIT_BYTES = 2 * 1024 * 1024;
  106. const AGENT_REPLY_JSON_ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ agent_reply: "" }));
  107. const AGENT_REPLY_INPUT_LIMIT_BYTES = AGENT_REPLY_JSON_LIMIT_BYTES - AGENT_REPLY_JSON_ENVELOPE_BYTES;
  108. const AGENT_REPLY_LIMIT_LABEL = "2 MB JSON request limit";
  109. const POLL_STATE_HEADER = "lavish-poll-state";
  110. const CODEX_POLL_WAKE_PATH_GUIDANCE =
  111. "Codex detected: completed background tasks may not resume Codex automatically, so keep the poll attached to the active turn.";
  112. // Inlined at build time from package.json; falls back to reading package.json so source-run tests work.
  113. export const VERSION =
  114. process.env.LAVISH_AXI_BUILD_VERSION ||
  115. JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
  116. export function detectInvokingAgent(env = process.env) {
  117. return ["CODEX_SANDBOX", "CODEX_THREAD_ID"].some((key) => Object.hasOwn(env, key)) ? "codex" : "generic";
  118. }
  119. export function shouldNarratePollWaitTicks({ isTTY }) {
  120. return Boolean(isTTY);
  121. }
  122. export function herdrPollChimeEnabled(env = process.env) {
  123. return env.HERDR_ENV === "1" && env.LAVISH_AXI_HERDR_CHIME === "1";
  124. }
  125. /**
  126. * @param {{
  127. * env?: NodeJS.ProcessEnv,
  128. * runner?: (command: string, args: string[], options: { stdio: "ignore" }) => import("node:child_process").ChildProcess,
  129. * }} [options]
  130. */
  131. export function notifyHerdrPollReady({ env = process.env, runner = spawn } = {}) {
  132. if (!herdrPollChimeEnabled(env)) return false;
  133. try {
  134. const child = runner(
  135. "herdr",
  136. [
  137. "notification",
  138. "show",
  139. "Lavish review ready",
  140. "--body",
  141. "The artifact is open and Lavish is polling for your feedback.",
  142. "--sound",
  143. "request",
  144. ],
  145. { stdio: "ignore" },
  146. );
  147. const kill = () => {
  148. try {
  149. child.kill("SIGKILL");
  150. } catch {
  151. return;
  152. }
  153. };
  154. const timer = setTimeout(kill, 2_000);
  155. timer.unref();
  156. const cleanup = () => {
  157. clearTimeout(timer);
  158. process.off("exit", kill);
  159. };
  160. child.on("error", () => {});
  161. child.once("close", cleanup);
  162. process.once("exit", kill);
  163. child.unref();
  164. return true;
  165. } catch {
  166. // A desktop notification is optional and must never interrupt feedback delivery.
  167. return false;
  168. }
  169. }
  170. export function pollExecutionGuidance({ agent = "generic" } = {}) {
  171. const sharedGuidance = POLL_WAKE_PATH_RULES.join(" ");
  172. const agentGuidance = agent === "codex" ? ` ${CODEX_POLL_WAKE_PATH_GUIDANCE}` : "";
  173. return `${sharedGuidance}${agentGuidance}`;
  174. }
  175. // Mirrors the SDK's own version-flag detection so the fast path below prints exactly
  176. // what `runAxiCli` would have printed, for exactly the same argv shapes.
  177. export function isVersionOnlyArgv(argv) {
  178. return argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v" || argv[0] === "-V");
  179. }
  180. export async function run(argv) {
  181. // `--version` sits on the agent-startup hot path (harnesses probe every tool's version
  182. // at session start), so it must never pay for state-dir creation or the telemetry
  183. // request drain in the `finally` below - that drain alone costs up to a full second.
  184. if (isVersionOnlyArgv(argv)) {
  185. process.stdout.write(`${VERSION}\n`);
  186. return;
  187. }
  188. await ensureStateDir();
  189. const normalizedArgv = normalizeArgv(argv);
  190. const agent = detectInvokingAgent(process.env);
  191. const isTopLevelHelp = argv.length === 1 && argv[0] === "--help";
  192. const command = telemetryCommandName(argv);
  193. const telemetry = initDefaultTelemetry({
  194. app: "lavish-axi",
  195. version: VERSION,
  196. platform: process.platform,
  197. arch: process.arch,
  198. });
  199. telemetry.pageview(`/${command}`, { command });
  200. try {
  201. await runAxiCli({
  202. description: DESCRIPTION,
  203. version: VERSION,
  204. argv: isTopLevelHelp ? [] : normalizedArgv,
  205. topLevelHelp: createTopLevelHelp({ agent }),
  206. home: async () =>
  207. createHomeOutput({
  208. bin: process.argv[1] || "lavish-axi",
  209. sessions: isTopLevelHelp ? [] : await visibleSessions(),
  210. includeSessions: !isTopLevelHelp,
  211. agent,
  212. }),
  213. commands: {
  214. open: openCommand,
  215. poll: pollCommand,
  216. reply: replyCommand,
  217. end: endCommand,
  218. stop: stopCommand,
  219. playbook: playbookCommand,
  220. design: designCommand,
  221. setup: setupCommand,
  222. server: serverCommand,
  223. export: exportCommand,
  224. share: shareCommand,
  225. libraries: librariesCommand,
  226. },
  227. getCommandHelp: (command) => getCommandHelp(command, { agent }),
  228. });
  229. telemetry.track("command", { command, status: "success" });
  230. } catch (error) {
  231. telemetry.track("command", { command, status: "error" });
  232. throw error;
  233. } finally {
  234. await telemetry.close(1_000);
  235. }
  236. }
  237. export function collapseHomeDirectory(file, home) {
  238. const normalizedFile = file.replaceAll("\\", "/");
  239. const normalizedHome = home.replaceAll("\\", "/");
  240. if (normalizedFile === normalizedHome) {
  241. return "~";
  242. }
  243. if (normalizedFile.startsWith(`${normalizedHome}/`)) {
  244. return `~/${normalizedFile.slice(normalizedHome.length + 1)}`;
  245. }
  246. return file;
  247. }
  248. export function normalizeArgv(argv) {
  249. const first = argv[0];
  250. if (!first || COMMANDS.has(first) || RESERVED.has(first)) {
  251. return argv;
  252. }
  253. if (first.startsWith("-")) {
  254. return argv.some((arg) => isHtmlPath(arg)) ? ["open", ...argv] : argv;
  255. }
  256. return ["open", ...argv];
  257. }
  258. export function telemetryCommandName(argv) {
  259. const normalized = normalizeArgv(argv);
  260. return normalized[0] && !normalized[0].startsWith("-") ? normalized[0] : "home";
  261. }
  262. export function createHomeOutput({ bin, sessions, includeSessions = true, agent = "generic" }) {
  263. return {
  264. bin: collapseHomeDirectory(bin, os.homedir()),
  265. description: DESCRIPTION,
  266. ...(includeSessions
  267. ? {
  268. sessions: sessions.map((session) => ({
  269. file: session.file,
  270. status: session.status,
  271. url: session.url,
  272. pending_prompts: session.pending_prompts || 0,
  273. listener: session.listener || "none",
  274. })),
  275. }
  276. : {}),
  277. visual_guidance: [
  278. "Use visual hierarchy to make the most important decisions, risks, tradeoffs, and next actions obvious at a glance",
  279. "Show, don't tell: explain concepts, flows, relationships, and comparisons with labeled illustrations - hand-authored inline SVG, per the diagram playbook - and show existing UI or state with screenshots of the real pages (run the app read-only if needed); reserve prose for what cannot be shown, such as rationale, trade-offs, and open questions",
  280. "Structure the prose that remains with sections, cards, tables, annotated snippets, and side-by-side comparisons instead of long paragraphs",
  281. "Choose typography, spacing, color, and layout deliberately so the artifact has a clear point of view",
  282. "Prevent horizontal overflow at every nesting level: nested grid/flex children also need minmax(0, 1fr) tracks and min-width: 0, especially when badges, labels, or status text use wide pixel or monospace fonts; wrap, truncate, or contain long unbreakable text deliberately",
  283. ],
  284. playbooks: listPlaybooks(),
  285. help: [
  286. "Run `lavish-axi <html-file>` to open or resume a Lavish Editor session. If the user explicitly ended the session from the browser, this refuses to reopen it and explains why instead of reopening uninvited - pass `--reopen` only when the user asks for further review or something important needs their visual attention",
  287. "Unless the user specifies another location, create HTML artifacts in the current working directory under `.lavish/`",
  288. "Lavish serves the html file through a local express.js server. If your html needs to reference other filesystem assets such as images, CSS, fonts, and local scripts, copy them into the same directory as the HTML file, then reference them with relative paths from that directory. Never prepend `/` to those asset paths - root paths won't work",
  289. `Run \`lavish-axi poll <html-file>\` to wait for user feedback. It long-polls and stays silent until the user sends feedback, ends the session, or leaves every review window disconnected past the reconnect grace period, so leave it running - never kill it. Detected layout issues never return this poll: the browser files them in the user's Layout issues inbox in the Lavish top bar, and they arrive as an ordinary tag "layout-warnings" prompt only when the user selects them and queues the fixes. Never edit the artifact to chase a layout issue the user has not queued. The only exception is a fatal artifact_failures response, which means the review surface itself could not be used. ${pollExecutionGuidance({ agent })} ${POLL_SEND_AND_END_RULE}`,
  290. 'Run `lavish-axi reply <html-file> --agent-reply "<message>"` to show a concise reply and exit once Lavish Editor accepts it, when you are handing a result back and are not about to long-poll. The board stops showing Working only after this command exits 0. Use `lavish-axi poll <html-file> --agent-reply "<message>"` when that reply should be followed by another wait for feedback. A longer reply uses `--agent-reply-file <path>` (`-` reads stdin) on either command. Run `lavish-axi reply --help` for the receipt contract',
  291. 'Mermaid is the whiteboard opt-in, not the diagram default: only when the user asks for an editable whiteboard, author that diagram as Mermaid in a `.mermaid` container. Rendered Mermaid diagrams there become embedded, editable Excalidraw whiteboards in the browser (click a diagram to unlock editing; a Fullscreen action opens it over the whole viewport) - flowchart, sequence, class, ER, and state diagrams convert to editable shapes; other types embed as an image to draw on. Scenes autosave locally; an unmodified autosave silently re-converts when a reload changes the Mermaid source. If the reviewer edited the scene, they choose to re-convert and discard saved edits or keep editing the saved scene. Standalone and exported copies still render plain Mermaid. Queue feedback adds a prompt to the Conversation panel; when the user sends it, poll returns a tag "whiteboard" prompt carrying a bounded edit summary plus local scenePath (.excalidraw JSON) and previewPath (PNG) files - read the summary first, open the files only when needed, then apply the edits by updating the Mermaid source in the artifact (never try to write the scene back)',
  292. "Run `lavish-axi end <html-file>` to end a session as the agent - ending it this way still allows a plain reopen later. When the user ends it from the browser instead, a later `lavish-axi <html-file>` refuses to reopen it without `--reopen`",
  293. "Run `lavish-axi export <html-file> [--out <path>]` to write a portable copy of the artifact - one HTML file with its LOCAL assets inlined - so it opens with no Lavish server and no sibling files. Remote CDN/font references are left as links, so it needs network to render those. Users can also export from the browser chrome's overflow menu",
  294. "Run `lavish-axi share <html-file> [--private | --password <pw>]` to publish the artifact on ht-ml.app (https://ht-ml.app), a third-party hosting service not part of Lavish, and get back a visitable URL. Shares are PUBLIC by default, so anyone with the link can open them. Pass --private to publish a PRIVATE page behind a password Lavish generates and returns - hand the user that password with the URL and say it is a shared secret anyone they give it to can use; --password <pw> uses one you were already given instead. Local assets are inlined; remote refs load over the network. It also returns a secret update_key that can republish or lock the same URL later - run `lavish-axi share --help` before using it. Users can also publish from the browser chrome's overflow menu",
  295. "A request under a hostname Lavish does not answer to (a reverse-proxy name, a LAN IP) gets 403 `forbidden host`. Set `LAVISH_AXI_ALLOWED_HOSTS` in the environment that starts the server, running `lavish-axi stop` first if one is already up. See README's Allowed hosts section for the rules",
  296. "Run `lavish-axi stop` to shut down the background server (it also self-stops when idle or after the last session ends with nothing connected)",
  297. `Run \`lavish-axi playbook <playbook_id>\` for focused artifact guidance. ${PLAYBOOK_ROUTER_HELP}`,
  298. DESIGN_SYSTEM_HINT,
  299. "Use lavish-axi when the user asks for a visual artifact, HTML explainer, interactive prototype, review surface, product or technical plan, comparison, report, or browser-based feedback loop",
  300. ],
  301. };
  302. }
  303. export function createPlaybookOutput(args) {
  304. const id = args[0];
  305. if (!id) {
  306. return {
  307. playbooks: listPlaybooks(),
  308. help: ["Run `lavish-axi playbook <playbook_id>` for focused artifact guidance", PLAYBOOK_ROUTER_HELP],
  309. };
  310. }
  311. const playbook = findPlaybook(id);
  312. if (!playbook) {
  313. throw new AxiError(`Unknown playbook: ${id}`, "VALIDATION_ERROR", [
  314. `Run \`lavish-axi playbook\` to list known IDs: ${playbookIds().join(", ")}`,
  315. ]);
  316. }
  317. return { playbook };
  318. }
  319. export function createOpenOutput({
  320. file,
  321. url,
  322. status,
  323. agent = "generic",
  324. selfPaintWarning = undefined,
  325. networkWarning = undefined,
  326. }) {
  327. const selfPaintPrefix = selfPaintWarning
  328. ? `First fix the unpainted page surface flagged in self_paint_warning and save - Lavish live-reloads the artifact automatically, so you do not need to re-run \`lavish-axi ${file}\`. `
  329. : "";
  330. // A failed bind is invisible to the person holding a review link at that address - the page
  331. // simply does not load - so the agent is told to pass it on rather than leave it in a field.
  332. const networkPrefix = networkWarning
  333. ? "Lavish could not serve every address it was asked to (see network_warning): when you next message the user, tell them, because review links at that address will not load until it clears. "
  334. : "";
  335. return {
  336. session: { file, url, status },
  337. ...(networkWarning ? { network_warning: networkWarning } : {}),
  338. ...(selfPaintWarning ? { self_paint_warning: selfPaintWarning } : {}),
  339. next_step: `${networkPrefix}${selfPaintPrefix}Do not respond to the user just yet. Now you must run \`lavish-axi poll ${file}\`. This command long-polls until the user sends feedback, ends the session, or leaves every review window disconnected past the reconnect grace period, and it stays silent the whole time - that is normal, never kill it. Layout issues the browser detects do not return this poll; they wait in the user's Layout issues inbox until the user queues them, then arrive as an ordinary tag "layout-warnings" prompt. Do not pass --timeout-ms during normal agent use. ${pollExecutionGuidance({ agent })} After applying feedback, run \`lavish-axi poll ${file} --agent-reply "<message for the user>"\` without --timeout-ms to show a concise response in Lavish Editor and keep waiting for more feedback. If instead you are handing back a result without starting another long-poll, run \`lavish-axi reply ${file} --agent-reply "<message for the user>"\` to get an acceptance receipt. ${POLL_AGENT_REPLY_RULE} ${POLL_AGENT_REPLY_NEXT_POINTER} If the user ends the session, stop polling and do not reopen it by re-running \`lavish-axi ${file}\` unless the user asks for further review or something genuinely important needs their visual attention - deliver routine updates directly in this conversation instead. When reopening is warranted, run \`lavish-axi ${file} --reopen\`.`,
  340. };
  341. }
  342. // Shown when a plain `lavish-axi <file>` targets a session the user explicitly ended from the
  343. // browser. Reviving it silently would reopen a browser window the human deliberately closed, so
  344. // this refuses and requires the explicit --reopen opt-in instead of erroring - the session
  345. // staying closed is the correct, idempotent outcome unless the agent has a real reason to reopen.
  346. export function createUserEndedOpenOutput({ file, url, networkWarning = undefined }) {
  347. return {
  348. session: { file, url, status: "user-ended" },
  349. ...(networkWarning ? { network_warning: networkWarning } : {}),
  350. next_step: `The user explicitly ended this Lavish Editor session from the browser, so \`lavish-axi ${file}\` did not reopen it. Do not reopen unless the user asks for further review or something genuinely important needs their visual attention - deliver routine updates directly in this conversation instead. When reopening is warranted, run \`lavish-axi ${file} --reopen\`.`,
  351. };
  352. }
  353. async function openCommand(args) {
  354. const file = firstPositionalArg(args);
  355. if (!file) {
  356. throw new AxiError("HTML file path is required", "VALIDATION_ERROR", ["Run `lavish-axi <html-file>`"]);
  357. }
  358. await assertHtmlFile(file);
  359. const absolute = await canonicalFile(file);
  360. const selfPaintWarning = await selfPaintWarningForFile(absolute);
  361. const noGate = args.includes("--no-gate");
  362. const reopen = args.includes("--reopen");
  363. const baseUrl = await ensureServer({
  364. forceRestart: shouldForceRestartForLocalBuild(process.argv[1] || ""),
  365. reloadKey: sessionKey(absolute),
  366. });
  367. const response = await postJson(`${baseUrl}/api/sessions`, { file: absolute, noGate, reopen });
  368. if (response.status === "user-ended") {
  369. return createUserEndedOpenOutput({
  370. file: absolute,
  371. url: response.url,
  372. networkWarning: response.network_warning,
  373. });
  374. }
  375. if (shouldOpenBrowser(args, process.env)) {
  376. try {
  377. const open = (await import("open")).default;
  378. await open(response.url);
  379. } catch {
  380. response.status = "ready";
  381. }
  382. }
  383. return createOpenOutput({
  384. file: absolute,
  385. url: response.url,
  386. status: response.status || "opened",
  387. agent: detectInvokingAgent(process.env),
  388. selfPaintWarning,
  389. networkWarning: response.network_warning,
  390. });
  391. }
  392. // A read failure here must not break the open - the server reports unreadable artifacts
  393. // through its own fatal path, and the self-paint check always fails open.
  394. async function selfPaintWarningForFile(absolute) {
  395. try {
  396. return analyzeSelfPaint(await readFile(absolute, "utf8")).painted ? undefined : SELF_PAINT_WARNING;
  397. } catch {
  398. return undefined;
  399. }
  400. }
  401. export function shouldOpenBrowser(args, env) {
  402. return !args.includes("--no-open") && env.LAVISH_AXI_NO_OPEN !== "1";
  403. }
  404. async function pollCommand(args) {
  405. const file = firstPositionalArg(args, POLL_VALUE_FLAGS);
  406. if (!file) {
  407. throw new AxiError("HTML file path is required", "VALIDATION_ERROR", ["Run `lavish-axi poll <html-file>`"]);
  408. }
  409. const ownerFlag = inspectValueFlag(args, "--owner");
  410. const owner = ownerFlag.present ? String(ownerFlag.value || "").trim() : null;
  411. if (ownerFlag.present && (!owner || owner.startsWith("-") || owner.toLowerCase() === "none")) {
  412. throw new AxiError(
  413. owner?.toLowerCase() === "none" ? "--owner none is reserved" : "--owner requires a non-empty label",
  414. "VALIDATION_ERROR",
  415. ["Pass `--owner <label>` to identify the process listening for feedback"],
  416. );
  417. }
  418. const takeover = args.includes("--takeover");
  419. const agentReply = await resolveAgentReply(args);
  420. const absolute = await canonicalFile(file);
  421. const baseUrl = await ensureServer();
  422. const timeoutMs = flagValue(args, "--timeout-ms");
  423. const query = new URLSearchParams({ file: absolute });
  424. if (timeoutMs) query.set("timeoutMs", timeoutMs);
  425. if (owner) query.set("owner", owner);
  426. if (takeover) query.set("takeover", "1");
  427. // The indefinite poll looks hung from the agent's side (stdout stays empty until the user
  428. // acts), so narrate the wait on stderr and leave re-run guidance behind if the agent's
  429. // harness kills the process anyway. stderr keeps the stdout JSON contract intact.
  430. // The one-shot banner is that "not hung" signal and stays unconditional; only the recurring
  431. // ticks - one line per minute, unbounded - are gated on an interactive stderr so piped,
  432. // merged agent captures do not accumulate them.
  433. const onPollSignal = (signal) => {
  434. process.stderr.write(`\n${pollInterruptedText(absolute)}\n`);
  435. process.exit(signal === "SIGINT" ? 130 : 143);
  436. };
  437. if (!timeoutMs) {
  438. // Register before the banner write below: a harness that kills the poll as soon as the
  439. // banner appears can deliver the signal before the next statement runs, and without a
  440. // handler the default disposition exits silently with no re-run guidance.
  441. process.on("SIGINT", onPollSignal);
  442. process.on("SIGTERM", onPollSignal);
  443. }
  444. const waitReporter = timeoutMs
  445. ? null
  446. : startPollWaitReporter({
  447. file: absolute,
  448. narrateTicks: shouldNarratePollWaitTicks({ isTTY: process.stderr.isTTY }),
  449. });
  450. try {
  451. const request =
  452. agentReply || takeover
  453. ? {
  454. method: "POST",
  455. headers: { "content-type": "application/json" },
  456. body: JSON.stringify(agentReply ? { agent_reply: agentReply } : {}),
  457. }
  458. : {};
  459. const response = await fetchJson(`${baseUrl}/api/poll?${query}`, {
  460. ...request,
  461. // Poll ownership is claimed before the response is available. Retrying a transport failure
  462. // can leave the first claim alive and make the retry reject itself as LISTENER_ACTIVE.
  463. retries: 0,
  464. onResponse: (pollResponse) => {
  465. if (pollResponse.headers.get(POLL_STATE_HEADER) === "listening") notifyHerdrPollReady();
  466. },
  467. });
  468. if (response.code === "LISTENER_REPLACED") {
  469. throw new AxiError("Lavish Editor poll listener was replaced by a takeover", "LISTENER_REPLACED", [
  470. `Re-run lavish-axi poll ${absolute} only if you intend to take over listening`,
  471. ]);
  472. }
  473. return createPollOutput({ file: absolute, response, agent: detectInvokingAgent(process.env) });
  474. } finally {
  475. waitReporter?.stop();
  476. if (!timeoutMs) {
  477. process.off("SIGINT", onPollSignal);
  478. process.off("SIGTERM", onPollSignal);
  479. }
  480. }
  481. }
  482. const REPLY_VALUE_FLAGS = ["--agent-reply", "--agent-reply-file"];
  483. const REPLY_TOO_LARGE_HELP = "Shorten the reply, then retry `lavish-axi reply <html-file>`";
  484. async function replyCommand(args) {
  485. const file = firstPositionalArg(args, REPLY_VALUE_FLAGS);
  486. if (!file) {
  487. throw new AxiError("HTML file path is required", "VALIDATION_ERROR", [
  488. 'Run `lavish-axi reply <html-file> --agent-reply "<message>"`',
  489. ]);
  490. }
  491. const inline = inspectValueFlag(args, "--agent-reply");
  492. const fromFile = inspectValueFlag(args, "--agent-reply-file");
  493. if (!inline.present && !fromFile.present) {
  494. throw new AxiError("An agent reply is required", "VALIDATION_ERROR", [
  495. 'Pass exactly one of --agent-reply "<message>" or --agent-reply-file <path> (`-` reads stdin)',
  496. "Use `lavish-axi poll <html-file> --agent-reply` when the reply should be followed by a wait for feedback",
  497. ]);
  498. }
  499. const text = await resolveAgentReply(args, { tooLargeHelp: REPLY_TOO_LARGE_HELP });
  500. if (!String(text || "").trim()) {
  501. throw new AxiError("Agent reply text was empty", "VALIDATION_ERROR", [
  502. 'Pass --agent-reply "<message>" or --agent-reply-file <path> with a non-empty body',
  503. ]);
  504. }
  505. await assertHtmlFile(file);
  506. const absolute = await canonicalFile(file);
  507. const baseUrl = await ensureServer();
  508. await postAgentReply(`${baseUrl}/api/${sessionKey(absolute)}/agent-reply`, text, absolute);
  509. return createReplyOutput(absolute);
  510. }
  511. function createReplyOutput(file) {
  512. return {
  513. reply: { file, status: "sent" },
  514. next_step: `Lavish Editor accepted the reply for ${file} and is no longer showing Working. Run \`lavish-axi poll ${file}\` when you are ready to wait for more feedback.`,
  515. };
  516. }
  517. export function pollWaitBannerText(file) {
  518. return (
  519. `[lavish-axi] Long-polling for user feedback on ${file}. This stays silent until the user sends feedback, ends the session, or leaves every review window disconnected past the reconnect grace period - leave it running. ` +
  520. `Detected layout issues do NOT return this poll: they wait in the user's Layout issues inbox until the user queues them as ordinary feedback. ` +
  521. `If it gets killed or times out before feedback arrives, re-run \`lavish-axi poll ${file}\` - feedback remains queued until delivery. Poll delivery consumes the response, so read it completely.`
  522. );
  523. }
  524. export function pollWaitTickText(elapsedMs) {
  525. const minutes = Math.round(elapsedMs / 60_000);
  526. return `[lavish-axi] Still waiting for user feedback (${minutes}m). Leave this running until the user sends feedback, ends the session, or leaves every review window disconnected.`;
  527. }
  528. export function pollInterruptedText(file) {
  529. return (
  530. `[lavish-axi] Poll interrupted before user feedback arrived. The user may still be reviewing - ` +
  531. `re-run \`lavish-axi poll ${file}\` to keep waiting; feedback remains queued until delivery. Poll delivery consumes the response, so read it completely.`
  532. );
  533. }
  534. export function startPollWaitReporter({
  535. file,
  536. write = (line) => {
  537. process.stderr.write(line);
  538. },
  539. intervalMs = 60_000,
  540. narrateTicks = true,
  541. }) {
  542. write(`${pollWaitBannerText(file)}\n`);
  543. if (!narrateTicks) return { stop: () => {} };
  544. let elapsedMs = 0;
  545. const timer = setInterval(() => {
  546. elapsedMs += intervalMs;
  547. write(`${pollWaitTickText(elapsedMs)}\n`);
  548. }, intervalMs);
  549. timer.unref?.();
  550. return { stop: () => clearInterval(timer) };
  551. }
  552. /**
  553. * @returns {{
  554. * session: { file: string, status: string, session_ended?: boolean, ended_by?: string },
  555. * prompts?: any[],
  556. * artifact_failures?: any[],
  557. * next_step?: string,
  558. * dom_snapshot?: string,
  559. * }}
  560. */
  561. export function createPollOutput({ file, response, agent = "generic" }) {
  562. if (response.status === "missing") {
  563. throw new AxiError("No active Lavish Editor session for this file", "NOT_FOUND", [
  564. `Run \`lavish-axi ${file}\` first`,
  565. ]);
  566. }
  567. if (response.status === "feedback") {
  568. const artifactFailures = Array.isArray(response.artifact_failures) ? response.artifact_failures : [];
  569. const sessionEnded = Boolean(response.session_ended);
  570. const endedBy = typeof response.ended_by === "string" ? response.ended_by : undefined;
  571. return {
  572. session: {
  573. file,
  574. status: "feedback",
  575. ...(sessionEnded ? { session_ended: true, ...(endedBy ? { ended_by: endedBy } : {}) } : {}),
  576. },
  577. prompts: response.prompts || [],
  578. ...(artifactFailures.length > 0 ? { artifact_failures: artifactFailures } : {}),
  579. next_step: createFeedbackNextStep(file, artifactFailures, sessionEnded, endedBy, response.prompts || [], agent),
  580. dom_snapshot: response.dom_snapshot || "",
  581. };
  582. }
  583. if (response.status === "ended") {
  584. return {
  585. session: { file, status: "ended", ...(response.ended_by ? { ended_by: response.ended_by } : {}) },
  586. next_step: createEndedNextStep(file, response.ended_by),
  587. };
  588. }
  589. if (response.status === "browser_disconnected") {
  590. return {
  591. session: { file, status: "browser_disconnected" },
  592. next_step:
  593. "The Lavish review window was closed or disconnected. The session remains open and resumable; ask the user whether they want to reopen it or end the session. Do not reopen or end it without their direction.",
  594. };
  595. }
  596. return {
  597. session: { file, status: response.status || "waiting" },
  598. next_step: `No user feedback arrived before the optional timeout. Run \`lavish-axi poll ${file}\` without --timeout-ms to wait indefinitely - feedback remains queued until delivery, so re-running the poll is safe while waiting. Poll delivery consumes the response, so read it completely.`,
  599. };
  600. }
  601. function createFeedbackNextStep(file, artifactFailures, sessionEnded, endedBy, prompts = [], agent = "generic") {
  602. const count = artifactFailures.length;
  603. const whiteboardNote = prompts.some((prompt) => prompt && prompt.tag === "whiteboard")
  604. ? `This feedback includes whiteboard edits (tag "whiteboard"): read the edit summary in the prompt text first, and only when it is not enough, open the target's scenePath (.excalidraw scene JSON) or previewPath (PNG) local files for detail. The artifact's Mermaid source stays authoritative - apply the edits by updating the Mermaid text in ${file} (Lavish live-reloads it); never try to write the .excalidraw scene back. `
  605. : "";
  606. const layoutNote = prompts.some((prompt) => prompt && prompt.tag === "layout-warnings")
  607. ? `This feedback includes layout issues the user selected from the Lavish Layout issues inbox (tag "layout-warnings"): the target lists the exact warning ids and targets. Apply every listed fix in one pass before saving so the user's review refreshes once. Queueing is a repair request, not a resolution - Lavish only marks a warning resolved after a newer artifact load and a complete check at the same viewport no longer detects it. `
  608. : "";
  609. const attachmentNote = prompts.some((prompt) => Array.isArray(prompt?.attachments) && prompt.attachments.length)
  610. ? `Some prompts carry image attachments the user added: each is an object in the prompt's \`attachments\` array with an absolute local \`path\` (plus id, mime, and dimensions). Open those image files to see what the user is referring to. `
  611. : "";
  612. if (sessionEnded) {
  613. const failureNote =
  614. count > 0
  615. ? endedBy === "user"
  616. ? `${count} fatal artifact failure${count === 1 ? "" : "s"} arrived alongside this final feedback - the review surface itself could not be used. Repair ${file}, then open it directly and confirm it renders without reopening this ended Lavish session. `
  617. : `${count} fatal artifact failure${count === 1 ? "" : "s"} arrived alongside this final feedback - the review surface itself could not be used. Repair ${file}, then run \`lavish-axi ${file}\` to open a fresh session. `
  618. : "";
  619. if (endedBy === "user") {
  620. const reopenNote =
  621. count > 0
  622. ? ""
  623. : ` Only run \`lavish-axi ${file} --reopen\` if the user explicitly asks for further review or something genuinely important needs their visual attention.`;
  624. return `${failureNote}${layoutNote}${whiteboardNote}${attachmentNote}This was the last feedback before the user ended the session. Stop polling ${file} and do not reopen it - deliver any remaining updates directly in this conversation instead.${reopenNote}`;
  625. }
  626. return `${failureNote}${layoutNote}${whiteboardNote}${attachmentNote}This was the last feedback before the Lavish Editor session ended. Stop polling ${file}. Deliver any remaining updates directly in this conversation, or run \`lavish-axi ${file}\` to open a fresh session if the user needs further visual review.`;
  627. }
  628. const prefix =
  629. count > 0 ? artifactFailuresPrefix(file, artifactFailures) : `Apply the requested changes to ${file}. `;
  630. return `${prefix}${layoutNote}${whiteboardNote}${attachmentNote}Do not respond to the user just yet. If you are continuing to wait for feedback, run \`lavish-axi poll ${file} --agent-reply "<message for the user>"\` without --timeout-ms to reply and keep polling. If instead you are handing back a result without starting another long-poll, run \`lavish-axi reply ${file} --agent-reply "<message for the user>"\` to post it and receive an acceptance receipt. ${POLL_AGENT_REPLY_RULE} ${POLL_AGENT_REPLY_NEXT_POINTER} The poll waits silently until the user sends more feedback, ends the session, or leaves every review window disconnected past the reconnect grace period - never kill it. ${pollExecutionGuidance({ agent })}`;
  631. }
  632. // The narrow fatal path. Ordinary layout findings never reach the poll: they wait in the user's
  633. // Layout issues inbox. Only failures that make the review itself unusable - the artifact document
  634. // not being servable, or one of its own local assets failing to load - arrive without user action.
  635. function artifactFailuresPrefix(file, artifactFailures) {
  636. const count = artifactFailures.length;
  637. const plural = count === 1 ? "" : "s";
  638. const details = artifactFailures
  639. .map((failure) => `${failure.kind}: ${failure.detail}`)
  640. .slice(0, 5)
  641. .join("; ");
  642. return `${count} fatal artifact failure${plural} detected - the review surface could not be used (${details}). Repair ${file} so it renders with all of its local assets, then re-check in the browser. Lavish live-reloads the artifact automatically after you save, so you do not need to re-run \`lavish-axi ${file}\` for this. `;
  643. }
  644. function createEndedNextStep(file, endedBy) {
  645. if (endedBy === "user") {
  646. return `The user ended this Lavish Editor session. Stop polling ${file} - do not run \`lavish-axi ${file}\` to reopen it. Deliver any remaining updates directly in this conversation instead. Only reopen with \`lavish-axi ${file} --reopen\` if the user explicitly asks for further review or something genuinely important needs their visual attention.`;
  647. }
  648. return `This Lavish Editor session for ${file} has ended. Stop polling. Deliver any remaining updates directly in this conversation, or run \`lavish-axi ${file}\` to open a fresh session if the user needs further visual review.`;
  649. }
  650. async function endCommand(args) {
  651. const file = firstPositionalArg(args);
  652. if (!file) {
  653. throw new AxiError("HTML file path is required", "VALIDATION_ERROR", ["Run `lavish-axi end <html-file>`"]);
  654. }
  655. const absolute = await canonicalFile(file);
  656. const baseUrl = await ensureServer();
  657. const response = await postJson(`${baseUrl}/api/end`, { file: absolute });
  658. return { session: { file: absolute, status: response.status || "ended" } };
  659. }
  660. // Produce a portable copy of an artifact: one HTML file with its LOCAL assets (relative-path
  661. // stylesheets, scripts, images, fonts) inlined as data URIs. Remote CDN/font references are left
  662. // as-is for the browser to load, so the export needs network to render those. Lavish makes no
  663. // outbound requests - export is a pure local file transform, server-independent.
  664. async function exportCommand(args) {
  665. const file = firstPositionalArg(args, ["--out"]);
  666. if (!file) {
  667. throw new AxiError("HTML file path is required", "VALIDATION_ERROR", ["Run `lavish-axi export <html-file>`"]);
  668. }
  669. await assertHtmlFile(file);
  670. const absolute = await canonicalFile(file);
  671. const root = path.dirname(absolute);
  672. const output = path.resolve(flagValue(args, "--out") || path.join(root, exportFileName(absolute)));
  673. const source = await readFile(absolute, "utf8");
  674. const { html, warnings } = await buildSelfContainedHtml(source, {
  675. baseDir: root,
  676. confineDir: root,
  677. resolveAbsolute: resolveDesignAssetPath,
  678. });
  679. await writeFile(output, html);
  680. return createExportOutput({
  681. source: absolute,
  682. output,
  683. html,
  684. warnings,
  685. selfPaintWarning: analyzeSelfPaint(source).painted ? undefined : SELF_PAINT_WARNING,
  686. });
  687. }
  688. export function createExportOutput({ source, output, html, warnings, selfPaintWarning = undefined }) {
  689. const allWarnings = Array.isArray(warnings) ? warnings : [];
  690. const { unresolved, notices } = splitExportWarnings(allWarnings);
  691. const result = {
  692. export: {
  693. source,
  694. output,
  695. bytes: Buffer.byteLength(html),
  696. unresolved_local_assets: unresolved.length,
  697. notices: notices.length,
  698. },
  699. };
  700. if (allWarnings.length) result.warnings = exportWarningSummaries(allWarnings);
  701. if (unresolved.length) result.unresolved_local_assets = exportWarningSummaries(unresolved);
  702. if (notices.length) result.notices = exportWarningSummaries(notices);
  703. if (unresolved.length) {
  704. result.next_step =
  705. "Some LOCAL assets could not be inlined and were left as references (see unresolved_local_assets); they will break once the file is moved. Remote CDN/font references are intentionally left as links and render where there is network access.";
  706. } else if (notices.length) {
  707. result.next_step = `Wrote ${output} with export notices (see notices). Open it directly or host it anywhere - it needs no Lavish server. Local assets are inlined; remote CDN/font references are left as links, so it needs network to render those.`;
  708. } else {
  709. result.next_step = `Wrote ${output}. Open it directly or host it anywhere - it needs no Lavish server. Local assets are inlined; remote CDN/font references are left as links, so it needs network to render those.`;
  710. }
  711. if (selfPaintWarning) {
  712. result.self_paint_warning = selfPaintWarning;
  713. result.next_step = `Fix the unpainted page surface flagged in self_paint_warning and re-run the export before sharing the file - an exported page renders over whatever surface hosts it. ${result.next_step}`;
  714. }
  715. return result;
  716. }
  717. function assetWarningSummaries(warnings) {
  718. return exportWarningSummaries(warnings);
  719. }
  720. // Publish, republish, or unpublish a page on third-party ht-ml.app; `resolveShareRequest` owns
  721. // which of the three the arguments describe. Creating POSTs the local-inlined HTML - built the same
  722. // way as `export`, remote refs left as links - to `/v1/sites`, needs no account or API key, and
  723. // returns the share URL plus the secret update_key. Republishing and unpublishing instead PUT to
  724. // `/v1/sites/{site_id}` authorized by that update_key and mint no new one; unpublish reads no file
  725. // at all and sends a placeholder page. Server-independent.
  726. export async function shareCommand(args) {
  727. const request = resolveShareRequest(args);
  728. if (request.mode === "unpublish") {
  729. const site = await unpublishShareSite(request);
  730. return createShareUnpublishOutput({ site, siteId: request.siteId });
  731. }
  732. await assertHtmlFile(request.file);
  733. const absolute = await canonicalFile(request.file);
  734. const root = path.dirname(absolute);
  735. const source = await readFile(absolute, "utf8");
  736. const { html, warnings } = await buildSelfContainedHtml(source, {
  737. baseDir: root,
  738. confineDir: root,
  739. resolveAbsolute: resolveDesignAssetPath,
  740. });
  741. const selfPaintWarning = analyzeSelfPaint(source).painted ? undefined : SELF_PAINT_WARNING;
  742. if (request.mode === "update") {
  743. const site = await updateShareSite(request, html);
  744. return createShareUpdateOutput({
  745. source: absolute,
  746. site,
  747. warnings,
  748. password: request.generatedPassword ? request.password : undefined,
  749. passwordProtected: Boolean(request.password),
  750. selfPaintWarning,
  751. });
  752. }
  753. const site = await createShareSite(request, html);
  754. return createShareOutput({
  755. source: absolute,
  756. site,
  757. warnings,
  758. passwordProtected: Boolean(request.password),
  759. password: request.generatedPassword ? request.password : undefined,
  760. selfPaintWarning,
  761. });
  762. }
  763. // Every surface that tells the user how to republish prints this one command, because a hint the
  764. // CLI itself rejects is worse than no hint: `--site`/`--update-key` alone parse to a usage error,
  765. // and the HTML file positional is what makes the shape a command that runs.
  766. //
  767. // A suggested command may never carry a password PLACEHOLDER. Every other placeholder here fails
  768. // loudly when an agent substitutes the real values and leaves one literal - `<html-file>` is not a
  769. // file, `<key>` earns a 401 - but any non-empty string is a valid password, so a literal `<pw>`
  770. // would be accepted and would rotate a live page to a secret nobody was told, with no way to clear
  771. // it afterwards. `--private` is safe to name because it takes no value and Lavish reports what it
  772. // minted; an explicit password is described in words instead.
  773. function republishCommand(siteId, { privatePage = false } = {}) {
  774. return `lavish-axi share <html-file> --site ${siteId} --update-key <key>${privatePage ? " --private" : ""}`;
  775. }
  776. function republishPrivateCommand(siteId) {
  777. return republishCommand(siteId, { privatePage: true });
  778. }
  779. function unpublishCommand(siteId) {
  780. return `lavish-axi share --unpublish --site ${siteId} --update-key <key>`;
  781. }
  782. // A 200 the host answered with an unreadable body is not an unknown outcome - the page landed - and
  783. // hedging it away discards the strongest honest report available. Whatever fields did arrive are
  784. // handed over, because a url with no update_key names a live page whose write credential is gone.
  785. function incompletePublishError(request, message, received) {
  786. const url = String(received.url || "").trim();
  787. const updateKey = String(received.updateKey || "").trim();
  788. const siteId = String(received.siteId || "").trim();
  789. const visibility = request.password
  790. ? `behind the password this run sent`
  791. : `PUBLICLY, readable by anyone who has the link`;
  792. const suggestions = [
  793. `ht-ml.app accepted this publish - the page IS live, hosted ${visibility} - but its response was malformed, so Lavish could not read the whole result back. Do not report this as a failed publish.`,
  794. url
  795. ? `Its address is ${url} - give the user that URL.`
  796. : `The response carried no url, so Lavish cannot name the page's address.`,
  797. ];
  798. if (updateKey) {
  799. suggestions.push(
  800. `Its update_key is ${updateKey}${siteId ? ` and its site_id is ${siteId}` : ""} - keep it, because ht-ml.app issues one only once and it is the only credential for changing or unpublishing the page.`,
  801. );
  802. } else {
  803. suggestions.push(
  804. `No update_key reached Lavish, and ht-ml.app issues one only once and has no delete endpoint, so this page can never be republished or unpublished. There is no recovery for it.`,
  805. );
  806. }
  807. suggestions.push(`Re-running this command publishes a SECOND page at a new URL; it does not replace the first.`);
  808. if (request.generatedPassword && request.password) {
  809. suggestions.push(`That page requires the password Lavish generated for it: ${request.password}`);
  810. }
  811. return new AxiError(message, "UNKNOWN", suggestions);
  812. }
  813. // Creating is the highest-consequence instance of the same split, because it is the one write with
  814. // no way back. A 4xx means nothing was published. Anything else can follow a POST the origin
  815. // already committed, and the response that was lost is the ONLY copy of the update_key - issued
  816. // once, and the sole credential for a host with no delete endpoint - so a page that landed this way
  817. // can never be republished or unpublished by anyone. Nothing here may suggest a recovery, because
  818. // there is none: re-running mints a second page rather than replacing the first.
  819. async function createShareSite(request, html) {
  820. try {
  821. return await publishToHtmlApp(html, { password: request.password, token: request.token });
  822. } catch (error) {
  823. if (hostRejectedShareWrite(error)) throw error;
  824. const message = error instanceof Error ? error.message : String(error);
  825. const landed = publishedDespiteError(error);
  826. if (landed) throw incompletePublishError(request, message, landed);
  827. const hosting = request.password
  828. ? `the artifact is now hosted on ht-ml.app behind the password this run sent`
  829. : `the artifact is now hosted PUBLICLY on ht-ml.app, readable by anyone who has the link`;
  830. const suggestions = [
  831. `ht-ml.app may or may not have published this page, so treat the outcome as unknown.`,
  832. `If it landed, ${hosting}, and the response carrying its url, site_id, and update_key was lost.`,
  833. `An update_key is issued once and ht-ml.app has no delete endpoint, so such a page can never be republished or unpublished - there is no recovery for it. Tell the user rather than implying the publish simply failed.`,
  834. `Re-running this command publishes a SECOND page at a new URL; it does not replace or reclaim the first.`,
  835. ];
  836. if (request.generatedPassword && request.password) {
  837. suggestions.push(`If it landed, that page requires the password Lavish generated for it: ${request.password}`);
  838. }
  839. throw new AxiError(message, "UNKNOWN", suggestions);
  840. }
  841. }
  842. // Whether the outcome is unknown is a property of the FAILURE, not of what the request carried: a
  843. // 4xx the host answered means it wrote nothing, while a 5xx or no answer at all can follow a PUT
  844. // the origin already committed, leaving the hosted page showing content Lavish reported as never
  845. // sent. So every indeterminate republish reports that and names a re-run that converges.
  846. // A generated password is an ADDITIONAL layer on that report, not its trigger: it only ever reaches
  847. // the user through the success output, so an indeterminate failure could otherwise leave the page
  848. // rotated to a secret nobody holds. A rejection must never carry it, because it gates nothing.
  849. async function updateShareSite(request, html) {
  850. try {
  851. return await updateHtmlApp(request.siteId, html, {
  852. updateKey: request.updateKey,
  853. password: request.password,
  854. });
  855. } catch (error) {
  856. if (hostRejectedShareWrite(error)) throw error;
  857. const message = error instanceof Error ? error.message : String(error);
  858. const generated = Boolean(request.generatedPassword && request.password);
  859. const retry = generated ? republishPrivateCommand(request.siteId) : republishCommand(request.siteId);
  860. const samePassword = !generated && request.password ? `, passing the same --password value you supplied` : "";
  861. const suggestions = [
  862. `ht-ml.app may or may not have applied this republish, so treat the outcome as unknown: the hosted page may already show the new content.`,
  863. `Re-running \`${retry}\`${samePassword} is safe and converges on the same result either way.`,
  864. ];
  865. if (generated) {
  866. suggestions.push(
  867. `If it landed, the page now requires the password Lavish generated for it: ${request.password} - the re-run above rotates it to a fresh one Lavish reports on success.`,
  868. );
  869. }
  870. throw new AxiError(message, "UNKNOWN", suggestions);
  871. }
  872. }
  873. // ht-ml.app has no delete endpoint, so the closest honest thing is a republish: replace the content
  874. // and lock the URL behind a password nobody is given. The update_key is the way back. The same
  875. // indeterminate-outcome rule as a republish applies - a 5xx or a timeout can follow a PUT the
  876. // origin already committed - so reporting a flat failure would tell the user the page is still
  877. // readable when it may already be the locked placeholder. No password is offered here: the lock
  878. // password is discarded by design, so there is nothing recoverable to hand back.
  879. async function unpublishShareSite(request) {
  880. try {
  881. return await updateHtmlApp(request.siteId, createUnpublishedPageHtml(), {
  882. updateKey: request.updateKey,
  883. password: generateSharePassword(),
  884. });
  885. } catch (error) {
  886. if (hostRejectedShareWrite(error)) throw error;
  887. const message = error instanceof Error ? error.message : String(error);
  888. throw new AxiError(message, "UNKNOWN", [
  889. `ht-ml.app may or may not have applied this unpublish, so treat the outcome as unknown: the page may already be the locked placeholder.`,
  890. `Re-running \`${unpublishCommand(request.siteId)}\` is safe and converges on the same result either way.`,
  891. `The update_key still works, so \`${republishPrivateCommand(request.siteId)}\` brings the page back behind a password you can see.`,
  892. ]);
  893. }
  894. }
  895. // Resolve which of `share`'s three shapes the arguments describe - publish, republish, or
  896. // unpublish - and which password the host should be sent. Pure, so the conflict rules are
  897. // testable without a network call or a file on disk. A password is never accepted from the artifact
  898. // or the browser; this is the only place one is generated for a request, the sole exception being
  899. // `--unpublish`, which mints its own directly because that value is discarded rather than reported.
  900. export function resolveShareRequest(args) {
  901. const unpublish = args.includes("--unpublish");
  902. const generate = args.includes("--private");
  903. const explicitPassword = shareFlagValue(args, "--password");
  904. const siteId = shareFlagValue(args, "--site");
  905. const updateKey = shareFlagValue(args, "--update-key");
  906. const token = shareFlagValue(args, "--token");
  907. const file = firstPositionalArg(args, SHARE_VALUE_FLAGS);
  908. if (generate && explicitPassword) {
  909. throw new AxiError("--private generates a password, so it cannot be combined with --password", "VALIDATION_ERROR", [
  910. "Pass --private to have Lavish mint one, or --password <pw> to choose it yourself",
  911. ]);
  912. }
  913. // A republish authenticates as the page itself: the Authorization header carries the update_key,
  914. // so there is no room for a bearer token and silently accepting one would look like it applied.
  915. if (token && (unpublish || siteId || updateKey)) {
  916. throw new AxiError(
  917. "--token only applies when creating a page: a republish authenticates with the update_key, which is what the Authorization header carries",
  918. "VALIDATION_ERROR",
  919. ["Drop --token and keep --site <site_id> --update-key <key>"],
  920. );
  921. }
  922. if (unpublish) {
  923. if (file) {
  924. throw new AxiError("--unpublish replaces a published page and takes no HTML file", "VALIDATION_ERROR", [
  925. "Run `lavish-axi share --unpublish --site <site_id> --update-key <key>`",
  926. ]);
  927. }
  928. if (generate || explicitPassword) {
  929. throw new AxiError(
  930. "--unpublish locks the page with its own password and takes no password flag",
  931. "VALIDATION_ERROR",
  932. ["Run `lavish-axi share --unpublish --site <site_id> --update-key <key>`"],
  933. );
  934. }
  935. assertSiteCredential(siteId, updateKey);
  936. return {
  937. mode: "unpublish",
  938. file: null,
  939. siteId: assertShareSiteId(siteId),
  940. updateKey,
  941. password: undefined,
  942. generatedPassword: false,
  943. token,
  944. };
  945. }
  946. if (siteId || updateKey) {
  947. assertSiteCredential(siteId, updateKey);
  948. assertShareFile(file);
  949. return {
  950. mode: "update",
  951. file,
  952. siteId: assertShareSiteId(siteId),
  953. updateKey,
  954. ...resolveSharePassword({ generate, explicitPassword }),
  955. token,
  956. };
  957. }
  958. assertShareFile(file);
  959. return {
  960. mode: "create",
  961. file,
  962. siteId: null,
  963. updateKey: null,
  964. ...resolveSharePassword({ generate, explicitPassword }),
  965. token,
  966. };
  967. }
  968. // An absent password preserves whatever the page already has. There is no "clear" value: the host
  969. // accepts an empty password and ignores it, so offering one would report a page as public while it
  970. // is still gated.
  971. function resolveSharePassword({ generate, explicitPassword }) {
  972. if (generate) return { password: generateSharePassword(), generatedPassword: true };
  973. if (explicitPassword) return { password: explicitPassword, generatedPassword: false };
  974. return { password: undefined, generatedPassword: false };
  975. }
  976. function assertSiteCredential(siteId, updateKey) {
  977. if (!siteId) {
  978. throw new AxiError("--site <site_id> is required to change a published page", "VALIDATION_ERROR", [
  979. "The site_id is in the share output from when the page was published",
  980. ]);
  981. }
  982. if (!updateKey) {
  983. throw new AxiError("--update-key <key> is required to change a published page", "VALIDATION_ERROR", [
  984. "The update_key was returned once when the page was published; there is no way to recover it",
  985. ]);
  986. }
  987. }
  988. // Read one of share's value-taking flags. `flagValue` takes the next token unconditionally, which
  989. // every other command tolerates because its blast radius is a bad argument; here an empty unquoted
  990. // shell variable makes `--password $PW --site abc` read "--site" as the password and ROTATE a live
  991. // page to a literal nobody knows, and the host cannot clear a password afterwards. So share refuses
  992. // the shapes that would be guesses rather than values. The `--password=<pw>` form stays permissive
  993. // past the leading `--` because nothing can be swallowed there.
  994. function shareFlagValue(args, flag) {
  995. for (let i = 0; i < args.length; i += 1) {
  996. const arg = args[i];
  997. if (arg === "--") break;
  998. if (arg === flag) return checkedShareFlagValue(flag, args[i + 1], { swallows: true });
  999. if (arg.startsWith(`${flag}=`)) return checkedShareFlagValue(flag, arg.slice(flag.length + 1), {});
  1000. }
  1001. return undefined;
  1002. }
  1003. function checkedShareFlagValue(flag, value, { swallows = false }) {
  1004. const hint =
  1005. flag === "--password"
  1006. ? `Quote the value as ${flag} "<pw>" - an unquoted shell variable that is unset expands to nothing - or pass --private to have Lavish generate one`
  1007. : `Quote the value as ${flag} "<value>"`;
  1008. if (swallows && typeof value === "string" && value.startsWith("--")) {
  1009. throw new AxiError(
  1010. `${flag} was given no value: the next argument ${value} is another flag, so it would have been used as the value`,
  1011. "VALIDATION_ERROR",
  1012. [hint, `Use ${flag}=<value> if the value itself starts with --`],
  1013. );
  1014. }
  1015. const trimmed = String(value ?? "").trim();
  1016. if (!trimmed) {
  1017. const consequence =
  1018. flag === "--password"
  1019. ? ", and publishing a PUBLIC page while you believed it was gated is the worse failure"
  1020. : "";
  1021. throw new AxiError(`${flag} was given an empty value${consequence}`, "VALIDATION_ERROR", [hint]);
  1022. }
  1023. return trimmed;
  1024. }
  1025. // normalizeSiteId is the library-level guard and throws a plain Error for direct callers. At the
  1026. // CLI boundary a bad --site is a usage mistake like any other, and pasting the share URL is the
  1027. // likeliest one, so it gets the same VALIDATION_ERROR shape and a hint about where the id comes
  1028. // from - raised here rather than inside updateHtmlApp, which only runs after the whole artifact
  1029. // has been read and bundled.
  1030. function assertShareSiteId(siteId) {
  1031. try {
  1032. return normalizeSiteId(siteId);
  1033. } catch (error) {
  1034. throw new AxiError(error instanceof Error ? error.message : String(error), "VALIDATION_ERROR", [
  1035. "The site_id is in the share output from when the page was published, and in the browser publish dialog's Site ID row",
  1036. ]);
  1037. }
  1038. }
  1039. function assertShareFile(file) {
  1040. if (!file) {
  1041. throw new AxiError("HTML file path is required", "VALIDATION_ERROR", ["Run `lavish-axi share <html-file>`"]);
  1042. }
  1043. }
  1044. export function createShareOutput({
  1045. source,
  1046. site,
  1047. warnings,
  1048. passwordProtected = false,
  1049. password = undefined,
  1050. selfPaintWarning = undefined,
  1051. }) {
  1052. const allWarnings = Array.isArray(warnings) ? warnings : [];
  1053. const { unresolved, notices } = splitExportWarnings(allWarnings);
  1054. const isPasswordProtected = Boolean(passwordProtected);
  1055. // The host either returned no site_id or returned one `normalizeSiteId` refuses, which is the
  1056. // same thing for the user: `--site` is half the republish credential, so without a usable one
  1057. // the page can never be changed again even though its update_key is in hand. Emitting an empty
  1058. // string beside guidance that says to keep it would hide that until `--site` rejected it.
  1059. const republishableSiteId = String(site.site_id ?? "").trim();
  1060. const result = {
  1061. share: {
  1062. source,
  1063. url: site.url,
  1064. ...(republishableSiteId ? { site_id: republishableSiteId } : {}),
  1065. update_key: site.update_key,
  1066. status: site.status || "active",
  1067. public: !isPasswordProtected,
  1068. visibility: isPasswordProtected ? "private" : "public",
  1069. password_protected: isPasswordProtected,
  1070. ...(password ? { password } : {}),
  1071. unresolved_local_assets: unresolved.length,
  1072. notices: notices.length,
  1073. },
  1074. };
  1075. const passwordNote = isPasswordProtected ? " This page is PASSWORD-PROTECTED; viewers also need the password." : "";
  1076. if (allWarnings.length) result.warnings = exportWarningSummaries(allWarnings);
  1077. if (unresolved.length) result.unresolved_local_assets = assetWarningSummaries(unresolved);
  1078. if (notices.length) result.notices = assetWarningSummaries(notices);
  1079. const noticeNote = notices.length ? " Export notices are available in notices." : "";
  1080. const hostNote =
  1081. "ht-ml.app (https://ht-ml.app), a third-party host not part of Lavish, hosts the page, so it needs no Lavish server.";
  1082. const updateKeyNote = republishableSiteId
  1083. ? "The update_key is a secret shown only once; keep it to republish the page later with --site and --update-key (there is no recovery, and ht-ml.app has no delete). "
  1084. : "The host did not return a site_id Lavish can use, and --site is half the republish credential, so this page can NEVER be republished or unpublished even though its update_key is in hand. Tell the user that now rather than letting them discover it later. ";
  1085. if (unresolved.length) {
  1086. result.next_step =
  1087. `Published ${isPasswordProtected ? "a PASSWORD-PROTECTED page at " : ""}${site.url}, but some LOCAL assets could not be inlined and were left as references (see unresolved_local_assets); inspect the hosted page and fix missing local assets before sharing it.${passwordNote}${noticeNote} ` +
  1088. `Remote CDN/font references are intentionally left as links and render where there is network access. ` +
  1089. updateKeyNote +
  1090. hostNote;
  1091. } else if (isPasswordProtected) {
  1092. result.next_step =
  1093. `Published a PASSWORD-PROTECTED page: ${site.url} - share this URL with the user and provide the password separately; viewers also need the password. ` +
  1094. `${noticeNote ? `${noticeNote} ` : ""}` +
  1095. updateKeyNote +
  1096. hostNote;
  1097. } else {
  1098. result.next_step =
  1099. `Published a PUBLIC page that anyone with the link can view: ${site.url} - share this URL with the user. ` +
  1100. `${noticeNote ? `${noticeNote} ` : ""}` +
  1101. updateKeyNote +
  1102. hostNote;
  1103. }
  1104. if (password) result.next_step = `${generatedPasswordNote(password)} ${result.next_step}`;
  1105. if (selfPaintWarning) {
  1106. result.self_paint_warning = selfPaintWarning;
  1107. result.next_step = `Fix the unpainted page surface flagged in self_paint_warning, then re-run the share command and share only its replacement URL - the hosted page renders over ht-ml.app's own surface. ${result.next_step}`;
  1108. }
  1109. return result;
  1110. }
  1111. // Republish output. Visibility is "unchanged" unless this call set a password, because Lavish
  1112. // persists nothing about a published page and the host never reports its current password. So a
  1113. // plain republish reports what Lavish DID, never what the page IS: it cannot know whether the page
  1114. // is gated, and an authoritative guess either way is one the user would act on.
  1115. export function createShareUpdateOutput({
  1116. source,
  1117. site,
  1118. warnings,
  1119. password = undefined,
  1120. passwordProtected = false,
  1121. selfPaintWarning = undefined,
  1122. }) {
  1123. const allWarnings = Array.isArray(warnings) ? warnings : [];
  1124. const { unresolved, notices } = splitExportWarnings(allWarnings);
  1125. const visibility = passwordProtected ? "private" : "unchanged";
  1126. const url = String(site.url ?? "").trim();
  1127. const result = {
  1128. share: {
  1129. source,
  1130. url,
  1131. site_id: site.site_id,
  1132. status: site.status || "active",
  1133. updated: true,
  1134. visibility,
  1135. ...(password ? { password } : {}),
  1136. unresolved_local_assets: unresolved.length,
  1137. notices: notices.length,
  1138. },
  1139. };
  1140. if (allWarnings.length) result.warnings = exportWarningSummaries(allWarnings);
  1141. if (unresolved.length) result.unresolved_local_assets = assetWarningSummaries(unresolved);
  1142. if (notices.length) result.notices = assetWarningSummaries(notices);
  1143. const noticeNote = notices.length ? " Export notices are available in notices." : "";
  1144. const unresolvedNote = unresolved.length
  1145. ? " Some LOCAL assets could not be inlined and were left as references (see unresolved_local_assets); inspect the hosted page."
  1146. : "";
  1147. const visibilityNote =
  1148. visibility === "private"
  1149. ? " It is PASSWORD-PROTECTED; viewers also need the password. That gate is NOT instant: if the page had been public, it was observed still answering uncredentialed requests from ht-ml.app's CDN cache for minutes afterwards, so do not tell the user it is gated right away; a page that was already private has no such cached copy and leaks nothing."
  1150. : " This republish did not touch the page's password, so whatever it had when it was last published still applies. Lavish stores nothing about a published page, so this output cannot tell you whether that is a password or none - and a page published without one stays readable by anyone who has the link.";
  1151. result.next_step = url
  1152. ? `Republished ${source} to the same URL: ${url} - viewers see the new version immediately and no new link is needed.${visibilityNote}${unresolvedNote}${noticeNote} ` +
  1153. `Keep the same update_key; it is still the only credential for this page.`
  1154. : `Republished ${source} in place as site_id ${site.site_id} - viewers see the new version immediately and no new link is needed, but the host did not report a URL for the page, so use the one from when it was published rather than guessing.${visibilityNote}${unresolvedNote}${noticeNote} ` +
  1155. `Keep the same update_key; it is still the only credential for this page.`;
  1156. if (password) result.next_step = `${generatedPasswordNote(password)} ${result.next_step}`;
  1157. if (selfPaintWarning) {
  1158. result.self_paint_warning = selfPaintWarning;
  1159. result.next_step = `Fix the unpainted page surface flagged in self_paint_warning, then republish - the hosted page renders over ht-ml.app's own surface. ${result.next_step}`;
  1160. }
  1161. return result;
  1162. }
  1163. // Unpublish output. The page is replaced and locked, never removed, and saying otherwise would
  1164. // leave the user believing content is gone from a URL that still resolves.
  1165. // `siteId` is the locally validated id the request was addressed to, and it - never the host's
  1166. // echo - is what the suggested republish command interpolates: that string is text an agent may
  1167. // run, so a host answering with `abc123 --password evil` must not be able to append flags to it.
  1168. export function createShareUnpublishOutput({ site, siteId = undefined }) {
  1169. const url = String(site.url ?? "").trim();
  1170. const commandSiteId = siteId || site.site_id;
  1171. const target = url
  1172. ? `Replaced the page at ${url} with an "unpublished" placeholder`
  1173. : `Replaced the page published as site_id ${site.site_id} with an "unpublished" placeholder (the host did not report a URL for it, so use the one from when it was published rather than guessing)`;
  1174. return {
  1175. share: {
  1176. url,
  1177. site_id: site.site_id,
  1178. status: site.status || "active",
  1179. unpublished: true,
  1180. visibility: "private",
  1181. },
  1182. next_step:
  1183. `${target} and locked it behind a fresh random password that was discarded. The replacement itself is immediate: the previous content is gone from that URL, not merely hidden. ` +
  1184. `The LOCK is what is not instant for a page that was public - its CDN copy was observed serving the new placeholder to uncredentialed requests for minutes afterwards - so the placeholder may be readable without the password until the edge cache turns over. Do not tell the user the URL is unreachable right away. ` +
  1185. `ht-ml.app has NO delete endpoint: the page is not deleted, the URL still resolves, and the host still holds whatever was published. Tell the user that rather than saying it was deleted. ` +
  1186. `The update_key is still the only credential for this page - republish with \`${republishPrivateCommand(commandSiteId)}\` to bring it back, then give the user the new password it returns. ` +
  1187. `ht-ml.app cannot remove a page's password once it has one, so a republished page stays private.`,
  1188. };
  1189. }
  1190. function generatedPasswordNote(password) {
  1191. return (
  1192. `The password is ${password} - Lavish generated it and does not store it anywhere. ` +
  1193. `Give it to the user with the URL and tell them it is a SHARED SECRET: anyone they pass it to can read the page.`
  1194. );
  1195. }
  1196. // Explicitly shut down the running Lavish Editor server. Unlike `end` (which closes a single
  1197. // session), this stops the background process so it stops dangling between sessions.
  1198. export async function stopCommand(args) {
  1199. const port = Number(flagValue(args, "--port") || defaultPort());
  1200. // A server that fell back to loopback answers there rather than at the requested bind host, and
  1201. // a `stop` that only dials the requested host reports "not-running" while leaving it running.
  1202. // A same-port duplicate at another address is this installation's server too, so it stops as well.
  1203. const { baseUrl, duplicates, foreign } = await findRunningServer(port);
  1204. if (foreign) throw otherInstallationError(port, foreign);
  1205. await stopDuplicateServers(duplicates, { reason: "stop" });
  1206. return shutdownServerOnPort(port, { baseUrl, currentVersion: VERSION });
  1207. }
  1208. export async function shutdownServerOnPort(
  1209. port,
  1210. {
  1211. baseUrl = `http://${hostForUrl(clientHost())}:${port}`,
  1212. currentVersion = VERSION,
  1213. fetchHealth: healthFetcher = fetchHealth,
  1214. requestShutdown: shutdownRequester = requestShutdown,
  1215. waitForPortFree: portFreeWaiter = waitForPortFree,
  1216. killServerProcess = killLavishListener,
  1217. processMatchesLavish = listenerMatchesLavish,
  1218. } = {},
  1219. ) {
  1220. const health = await healthFetcher(baseUrl);
  1221. if (!health) {
  1222. return { server: { status: "not-running", port } };
  1223. }
  1224. if (!(await canControlServerOnPort(baseUrl, health, processMatchesLavish))) {
  1225. return { server: { status: "not-lavish", port } };
  1226. }
  1227. await shutdownRequester(baseUrl, { reason: "stop" });
  1228. let freed = await portFreeWaiter(baseUrl, 3000);
  1229. if (!freed && shouldKillProcessOnPort(currentVersion, health)) {
  1230. if (!killServerProcess(baseUrl)) throw unidentifiedListenerError(baseUrl);
  1231. freed = await portFreeWaiter(baseUrl, 3000);
  1232. }
  1233. return { server: { status: freed ? "stopped" : "stopping", port } };
  1234. }
  1235. const LIBRARY_ITEM_LIST_LIMIT = 50;
  1236. async function librariesCommand(args) {
  1237. const dir = excalidrawLibrariesDir(path.dirname(stateFile()));
  1238. const { libraries, skipped } = await loadExcalidrawLibraries(dir);
  1239. return createLibrariesOutput({
  1240. dir: collapseHomeDirectory(dir, os.homedir()),
  1241. libraries,
  1242. skipped,
  1243. search: flagValue(args, "--search") || "",
  1244. library: flagValue(args, "--library") || "",
  1245. });
  1246. }
  1247. /**
  1248. * @param {{ dir: string, libraries: { id: string, items: { ref: string, name: string }[] }[], skipped: { file: string, reason: string }[], search?: string, library?: string }} options
  1249. */
  1250. export function createLibrariesOutput({ dir, libraries, skipped, search = "", library = "" }) {
  1251. /** @type {Record<string, any>} */
  1252. const output = {
  1253. dir,
  1254. libraries: libraries.map((entry) => ({ id: entry.id, items: entry.items.length })),
  1255. };
  1256. if (skipped.length > 0) {
  1257. output.skipped = skipped.map((entry) => ({ file: path.basename(entry.file), reason: entry.reason }));
  1258. }
  1259. if (libraries.length === 0) {
  1260. output.help = [
  1261. `Copy Excalidraw library files (.excalidrawlib, for example from https://libraries.excalidraw.com) into ${dir}; every whiteboard's library panel then lists their items`,
  1262. ];
  1263. return output;
  1264. }
  1265. const terms = search.toLowerCase().split(/\s+/).filter(Boolean);
  1266. if (terms.length > 0 || library) {
  1267. const matches = libraries
  1268. .filter((entry) => !library || entry.id === library.toLowerCase())
  1269. .flatMap((entry) => entry.items)
  1270. .filter((item) => terms.every((term) => item.ref.toLowerCase().includes(term)));
  1271. output.items = matches.slice(0, LIBRARY_ITEM_LIST_LIMIT).map((item) => ({ ref: item.ref }));
  1272. if (matches.length > LIBRARY_ITEM_LIST_LIMIT) output.more_items = matches.length - LIBRARY_ITEM_LIST_LIMIT;
  1273. }
  1274. output.help = [
  1275. output.more_items
  1276. ? "Narrow the list with `lavish-axi libraries --search <text>`"
  1277. : "Run `lavish-axi libraries --search <text>` or `--library <id>` to list item refs",
  1278. "To show an item as a node icon in a whiteboard flowchart, see `whiteboard_tooling.library_icons` in `lavish-axi design`",
  1279. ];
  1280. return output;
  1281. }
  1282. async function playbookCommand(args) {
  1283. return createPlaybookOutput(args);
  1284. }
  1285. async function designCommand() {
  1286. return createDesignOutput();
  1287. }
  1288. async function setupCommand(args) {
  1289. if (args.length !== 1 || (args[0] !== "hooks" && args[0] !== "plugin")) {
  1290. throw new AxiError("Unknown setup action", "VALIDATION_ERROR", [
  1291. "Run `lavish-axi setup hooks`",
  1292. "Run `lavish-axi setup plugin`",
  1293. ]);
  1294. }
  1295. if (args[0] === "plugin") return setupPluginCommand();
  1296. const errors = [];
  1297. installSessionStartHooks({
  1298. marker: "lavish-axi",
  1299. binaryNames: ["lavish-axi"],
  1300. distEntrypoints: ["dist/cli.mjs", "bin/lavish-axi.js"],
  1301. homeDir: resolveHookHomeDir(),
  1302. onError: (message) => errors.push(message),
  1303. });
  1304. installCopilotCliSessionStartHook({
  1305. hookDir: resolveCopilotHookDir(process.env, resolveHookHomeDir()),
  1306. onError: (message) => errors.push(message),
  1307. });
  1308. if (errors.length > 0) {
  1309. throw new AxiError("Failed to install lavish-axi agent hooks", "SERVER_ERROR", errors);
  1310. }
  1311. return {
  1312. hooks: { status: "installed", integrations: "Claude Code, Codex, OpenCode, GitHub Copilot CLI" },
  1313. help: [
  1314. "Restart your agent session to receive lavish-axi ambient context",
  1315. "Run `lavish-axi setup plugin` to also register the Agent Plugin in VS Code, Cursor, and GitHub Copilot CLI",
  1316. ],
  1317. };
  1318. }
  1319. /**
  1320. * Register this installed package as an Agent Plugin in every supported client that is
  1321. * present. The package directory itself is the plugin root, so nothing is downloaded and
  1322. * no marketplace is involved - clients read the same files `npm install` already wrote.
  1323. *
  1324. * Like `setup hooks`, this only ever runs from an explicit user invocation.
  1325. *
  1326. * @returns {Promise<Record<string, unknown>>} structured per-client outcome
  1327. */
  1328. async function setupPluginCommand() {
  1329. const pluginRoot = resolvePluginRoot();
  1330. const manifest = readPluginManifest(pluginRoot);
  1331. if (!manifest) {
  1332. throw new AxiError("No plugin.json found in the lavish-axi package", "SERVER_ERROR", [
  1333. `Expected a manifest at ${path.join(pluginRoot, "plugin.json")}`,
  1334. "Reinstall lavish-axi, or run `npm run build:plugin` when working from a source checkout",
  1335. ]);
  1336. }
  1337. const clients = [
  1338. registerVsCodePlugin(pluginRoot, manifest.name),
  1339. registerCursorPlugin(pluginRoot, manifest.name),
  1340. registerCopilotPlugin(pluginRoot, manifest.name),
  1341. ];
  1342. const help = ["Restart or reload each client so it discovers the plugin"];
  1343. if (clients.some((client) => client.status === "absent")) {
  1344. help.push("Absent clients are skipped; re-run `lavish-axi setup plugin` after installing one");
  1345. }
  1346. if (clients.some((client) => client.status === "manual")) {
  1347. help.push(`Register the plugin root manually where noted: ${pluginRoot}`);
  1348. }
  1349. return { plugin: { name: manifest.name, root: collapseHome(pluginRoot) }, clients, help };
  1350. }
  1351. /** @param {string} target absolute path @returns {string} path with $HOME collapsed to ~ */
  1352. function collapseHome(target) {
  1353. const home = resolveHookHomeDir();
  1354. return home && target.startsWith(home) ? `~${target.slice(home.length)}` : target;
  1355. }
  1356. /**
  1357. * @param {string} pluginRoot absolute plugin root
  1358. * @param {string} pluginName manifest name
  1359. * @returns {{ client: string, status: string, detail: string }} outcome row
  1360. */
  1361. function registerVsCodePlugin(pluginRoot, pluginName) {
  1362. const settingsFile = resolveVsCodeSettingsFile(process.env, resolveHookHomeDir());
  1363. const settingsDir = path.dirname(settingsFile);
  1364. const hasSettingsFile = existsSync(settingsFile);
  1365. if (!hasSettingsFile && !existsSync(settingsDir)) {
  1366. return { client: "vscode", status: "absent", detail: "no VS Code user configuration found" };
  1367. }
  1368. let settings = {};
  1369. if (hasSettingsFile) {
  1370. try {
  1371. settings = JSON.parse(readFileSync(settingsFile, "utf8"));
  1372. } catch {
  1373. // VS Code settings may legally contain comments or trailing commas. Rewriting a file
  1374. // we cannot faithfully parse would destroy the user's configuration, so we bail out
  1375. // and tell them the one line to add instead.
  1376. return {
  1377. client: "vscode",
  1378. status: "manual",
  1379. detail: `add "chat.pluginLocations": {"${pluginRoot}": true} to ${collapseHome(settingsFile)}`,
  1380. };
  1381. }
  1382. }
  1383. const [updated, changed] = computeVsCodePluginLocationsUpdate(settings, pluginRoot, pluginName);
  1384. if (!changed) return { client: "vscode", status: "current", detail: collapseHome(settingsFile) };
  1385. try {
  1386. const writeTarget = hasSettingsFile ? realpathSync(settingsFile) : settingsFile;
  1387. writeTextFileAtomically(writeTarget, `${JSON.stringify(updated, null, 2)}\n`);
  1388. } catch (error) {
  1389. return { client: "vscode", status: "failed", detail: String(error instanceof Error ? error.message : error) };
  1390. }
  1391. return { client: "vscode", status: "registered", detail: collapseHome(settingsFile) };
  1392. }
  1393. /**
  1394. * @param {string} pluginRoot absolute plugin root
  1395. * @param {string} pluginName manifest name
  1396. * @returns {{ client: string, status: string, detail: string }} outcome row
  1397. */
  1398. function registerCursorPlugin(pluginRoot, pluginName) {
  1399. const cursorDir = path.join(resolveHookHomeDir(), ".cursor");
  1400. if (!existsSync(cursorDir)) {
  1401. return { client: "cursor", status: "absent", detail: "no ~/.cursor directory found" };
  1402. }
  1403. try {
  1404. const { status, target, reason } = linkCursorLocalPlugin(
  1405. resolveCursorLocalPluginsDir(resolveHookHomeDir()),
  1406. pluginRoot,
  1407. pluginName,
  1408. );
  1409. if (status === "occupied") {
  1410. return { client: "cursor", status: "manual", detail: `${collapseHome(target)} exists and is not a symlink` };
  1411. }
  1412. if (status === "unsupported") {
  1413. // Windows without Developer Mode is the common case. Say what to do instead of
  1414. // leaking a bare EPERM, and leave the other clients registered.
  1415. return {
  1416. client: "cursor",
  1417. status: "manual",
  1418. detail: `cannot link ${collapseHome(target)} (${reason}); link it to ${pluginRoot} manually, or enable Developer Mode on Windows`,
  1419. };
  1420. }
  1421. return {
  1422. client: "cursor",
  1423. status: status === "current" ? "current" : "registered",
  1424. detail: collapseHome(target),
  1425. };
  1426. } catch (error) {
  1427. return { client: "cursor", status: "failed", detail: String(error instanceof Error ? error.message : error) };
  1428. }
  1429. }
  1430. /**
  1431. * @param {string} pluginRoot absolute plugin root
  1432. * @param {string} pluginName manifest name
  1433. * @returns {{ client: string, status: string, detail: string }} outcome row
  1434. */
  1435. function registerCopilotPlugin(pluginRoot, pluginName) {
  1436. const listed = spawnPluginClientSync("copilot", ["plugins", "list", "--scope", "user", "--kind", "plugin", "--json"]);
  1437. if (listed.error) {
  1438. return { client: "copilot", status: "absent", detail: "copilot CLI not found on PATH" };
  1439. }
  1440. if (listed.status !== 0) {
  1441. const detail = String(listed.stderr || listed.stdout || `exit ${listed.status}`).trim();
  1442. return {
  1443. client: "copilot",
  1444. status: "manual",
  1445. detail: `could not verify installed plugins: ${detail.split("\n")[0]}`,
  1446. };
  1447. }
  1448. const records = parseCopilotPluginRecords(listed.stdout);
  1449. if (!records) {
  1450. return { client: "copilot", status: "manual", detail: "could not parse installed plugin records" };
  1451. }
  1452. const existing = records.find((record) => record.name === pluginName && (!record.kind || record.kind === "plugin"));
  1453. if (existing) {
  1454. const source = copilotPluginSourcePath(existing) || installedCopilotPluginSourcePath(pluginName);
  1455. if (!source) {
  1456. return { client: "copilot", status: "manual", detail: "could not verify the installed plugin source" };
  1457. }
  1458. if (sameResolvedPath(source, pluginRoot)) {
  1459. return { client: "copilot", status: "current", detail: collapseHome(pluginRoot) };
  1460. }
  1461. }
  1462. const installed = spawnPluginClientSync("copilot", ["plugin", "install", pluginRoot]);
  1463. if (installed.status !== 0) {
  1464. const detail = String(installed.stderr || installed.stdout || `exit ${installed.status}`).trim();
  1465. return { client: "copilot", status: "failed", detail: detail.split("\n")[0] };
  1466. }
  1467. return { client: "copilot", status: "registered", detail: "copilot plugin install" };
  1468. }
  1469. /** @param {unknown} output @returns {Record<string, any>[] | null} */
  1470. function parseCopilotPluginRecords(output) {
  1471. try {
  1472. const parsed = JSON.parse(String(output));
  1473. const records = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.plugins) ? parsed.plugins : parsed?.items;
  1474. return Array.isArray(records) && records.every((record) => record && typeof record === "object") ? records : null;
  1475. } catch {
  1476. return null;
  1477. }
  1478. }
  1479. /** @param {string} pluginName @returns {string | null} */
  1480. function installedCopilotPluginSourcePath(pluginName) {
  1481. const configDir = process.env.COPILOT_HOME || path.join(resolveHookHomeDir(), ".copilot");
  1482. try {
  1483. const config = JSON.parse(readFileSync(path.join(configDir, "config.json"), "utf8"));
  1484. const record = Array.isArray(config.installedPlugins)
  1485. ? config.installedPlugins.find((candidate) => candidate?.name === pluginName)
  1486. : null;
  1487. return record ? copilotPluginSourcePath(record) : null;
  1488. } catch {
  1489. return null;
  1490. }
  1491. }
  1492. /** @param {Record<string, any>} record @returns {string | null} */
  1493. function copilotPluginSourcePath(record) {
  1494. const candidates = [
  1495. record.sourcePath,
  1496. record.source_path,
  1497. record.pluginRoot,
  1498. record.plugin_root,
  1499. record.path,
  1500. record.source?.path,
  1501. ];
  1502. for (const candidate of candidates) {
  1503. if (typeof candidate !== "string") continue;
  1504. if (candidate.startsWith("file:")) {
  1505. try {
  1506. return fileURLToPath(candidate);
  1507. } catch {
  1508. continue;
  1509. }
  1510. }
  1511. if (path.isAbsolute(candidate)) return candidate;
  1512. }
  1513. return null;
  1514. }
  1515. /** @param {string} left @param {string} right @returns {boolean} */
  1516. function sameResolvedPath(left, right) {
  1517. try {
  1518. return realpathSync(left) === realpathSync(right);
  1519. } catch {
  1520. return path.resolve(left) === path.resolve(right);
  1521. }
  1522. }
  1523. export function resolveHookHomeDir(env = process.env, fallback = os.homedir()) {
  1524. return env.HOME || fallback;
  1525. }
  1526. export function resolveCopilotHookDir(env = process.env, homeDir = resolveHookHomeDir(env)) {
  1527. return path.join(env.COPILOT_HOME || path.join(homeDir, ".copilot"), "hooks");
  1528. }
  1529. export function createCopilotCliAmbientContextScript(command = "lavish-axi") {
  1530. return [
  1531. 'const { spawnSync } = require("node:child_process");',
  1532. `const command = ${JSON.stringify(command)};`,
  1533. 'const result = spawnSync(command, [], { encoding: "utf8", shell: true });',
  1534. 'const detail = result.error ? result.error.message : (result.stderr || result.stdout || "exit " + (result.status ?? "unknown"));',
  1535. "const text = String(result.status === 0 ? result.stdout : detail).trim();",
  1536. 'if (!text) { console.log("{}"); process.exit(0); }',
  1537. 'const prefix = result.status === 0 ? "## AXI ambient context: lavish-axi\\n" : "## AXI ambient context: lavish-axi\\nerror: lavish-axi ambient context failed: ";',
  1538. "console.log(JSON.stringify({ additionalContext: prefix + text }));",
  1539. ].join(" ");
  1540. }
  1541. export function createCopilotCliSessionStartHook(command = "lavish-axi", timeoutSec = 10) {
  1542. const script = createCopilotCliAmbientContextScript(command);
  1543. return {
  1544. type: "command",
  1545. bash: `node -e ${quoteForPosixShell(script)}`,
  1546. powershell: `node -e ${quoteForPowerShell(script)}`,
  1547. timeoutSec,
  1548. };
  1549. }
  1550. export function computeCopilotCliHookUpdate(settings, hook = createCopilotCliSessionStartHook()) {
  1551. const updated = structuredClone(settings && typeof settings === "object" ? settings : {});
  1552. let changed = false;
  1553. if (updated.version !== 1) {
  1554. updated.version = 1;
  1555. changed = true;
  1556. }
  1557. if (!updated.hooks || typeof updated.hooks !== "object" || Array.isArray(updated.hooks)) {
  1558. updated.hooks = {};
  1559. changed = true;
  1560. }
  1561. const current = Array.isArray(updated.hooks.sessionStart) ? updated.hooks.sessionStart : [];
  1562. const unmanaged = current.filter((entry) => !isManagedCopilotCliHook(entry));
  1563. const next = [...unmanaged, hook];
  1564. if (!deepEqual(current, next)) {
  1565. updated.hooks.sessionStart = next;
  1566. changed = true;
  1567. }
  1568. return [changed ? updated : settings, changed];
  1569. }
  1570. export function installCopilotCliSessionStartHook({
  1571. hookDir = resolveCopilotHookDir(),
  1572. command = "lavish-axi",
  1573. timeoutSec = 10,
  1574. onError = undefined,
  1575. } = {}) {
  1576. const target = path.join(hookDir, "lavish-axi.json");
  1577. try {
  1578. mkdirSync(path.dirname(target), { recursive: true });
  1579. const current = existsSync(target) ? JSON.parse(readFileSync(target, "utf8")) : {};
  1580. const [updated, changed] = computeCopilotCliHookUpdate(
  1581. current,
  1582. createCopilotCliSessionStartHook(command, timeoutSec),
  1583. );
  1584. if (changed) {
  1585. writeFileSync(target, `${JSON.stringify(updated, null, 2)}\n`, "utf8");
  1586. }
  1587. } catch (error) {
  1588. const message = error instanceof Error ? error.message : String(error);
  1589. onError?.(`${target}: ${message}`);
  1590. }
  1591. }
  1592. function isManagedCopilotCliHook(entry) {
  1593. return (
  1594. entry &&
  1595. typeof entry === "object" &&
  1596. (typeof entry.bash === "string" || typeof entry.powershell === "string" || typeof entry.command === "string") &&
  1597. [entry.bash, entry.powershell, entry.command].some(
  1598. (value) => typeof value === "string" && value.includes("lavish-axi"),
  1599. )
  1600. );
  1601. }
  1602. function quoteForPosixShell(value) {
  1603. return `'${value.replaceAll("'", "'\\''")}'`;
  1604. }
  1605. function quoteForPowerShell(value) {
  1606. return `'${value.replaceAll("'", "''")}'`;
  1607. }
  1608. function deepEqual(a, b) {
  1609. return JSON.stringify(a) === JSON.stringify(b);
  1610. }
  1611. async function serverCommand(args) {
  1612. const port = Number(flagValue(args, "--port") || defaultPort());
  1613. const debug = args.includes("--verbose") || process.env.LAVISH_AXI_DEBUG === "1";
  1614. const server = await serve({
  1615. port,
  1616. stateFile: stateFile(),
  1617. version: VERSION,
  1618. debug,
  1619. extraListenHosts: flagValues(args, "--also-listen"),
  1620. });
  1621. await server.done;
  1622. return "";
  1623. }
  1624. async function visibleSessions() {
  1625. const store = new SessionStore(stateFile());
  1626. const sessions = (await store.listSessions()).filter((session) => session.status !== "ended");
  1627. const { health } = await findRunningServer(defaultPort());
  1628. const listeners = new Map(
  1629. Array.isArray(health?.listeners)
  1630. ? health.listeners
  1631. .filter((listener) => listener && typeof listener.key === "string")
  1632. .map((listener) => [listener.key, listener.label || "agent-listener"])
  1633. : [],
  1634. );
  1635. return sessions.map((session) => ({ ...session, listener: listeners.get(session.key) || "none" }));
  1636. }
  1637. async function assertHtmlFile(file) {
  1638. if (!isHtmlPath(file)) {
  1639. throw new AxiError("Lavish Editor expects an HTML file", "VALIDATION_ERROR", ["Run `lavish-axi <html-file>`"]);
  1640. }
  1641. try {
  1642. await access(file);
  1643. } catch {
  1644. throw new AxiError(`File not found: ${file}`, "NOT_FOUND", [
  1645. "Create the HTML artifact first, then run `lavish-axi <html-file>`",
  1646. ]);
  1647. }
  1648. }
  1649. const HEALTH_PROBE_TIMEOUT_MS = 500;
  1650. const DEFAULT_HEALTH_TIMEOUT_MS = 2000;
  1651. const MAX_HEALTH_BODY_BYTES = 256 * 1024;
  1652. // A reconcile asks the server to re-detect Tailscale and retry any unbound address before
  1653. // answering, which can take longer than a plain health read.
  1654. const HEALTH_RECONCILE_TIMEOUT_MS = 3000;
  1655. // Every address a Lavish server on this port could be answering at, in preference order: the host
  1656. // this CLI is configured for, loopback, then every other local interface address. Agents on one
  1657. // machine do not share LAVISH_AXI_HOST, and a CLI that only dialed its own host (plus loopback)
  1658. // concluded nothing was running while a server pinned to the tailnet address held the port, then
  1659. // spawned a second daemon beside it on the same port and the same state file.
  1660. function serverCandidateHosts() {
  1661. const hosts = [clientHost(), LOOPBACK_HOST];
  1662. for (const address of localInterfaceAddresses()) {
  1663. if (!hosts.includes(address)) hosts.push(address);
  1664. }
  1665. return hosts;
  1666. }
  1667. function serverBaseUrl(host, port) {
  1668. return `http://${hostForUrl(host)}:${port}`;
  1669. }
  1670. // A server is this installation's when it reports our state file. One from before `state_id`
  1671. // existed (0.1.77 and older) cannot say, so it counts as ours only at an address this CLI controls -
  1672. // its configured host or loopback - where replacing it is the upgrade path; anywhere else it may
  1673. // belong to another installation and is never adopted or stopped.
  1674. function isOwnedServer(entry, controlHosts) {
  1675. if (entry.health.app !== "lavish-axi") return false;
  1676. if (typeof entry.health.state_id === "string") return entry.health.state_id === stateId();
  1677. return controlHosts.has(entry.host);
  1678. }
  1679. // Another installation's Lavish server at an address this CLI controls is never used, replaced, or
  1680. // stopped: its sessions and state file are not ours.
  1681. function otherInstallationError(port, foreign) {
  1682. const dir = typeof foreign.health.state_dir === "string" ? foreign.health.state_dir : "an unknown state directory";
  1683. return new AxiError(
  1684. `Port ${port} is served by another Lavish installation at ${foreign.host} (state directory ${dir})`,
  1685. "SERVER_ERROR",
  1686. [`Set LAVISH_AXI_PORT to another port, or set LAVISH_AXI_STATE_DIR to ${dir} to use that installation`],
  1687. );
  1688. }
  1689. // Returns where a Lavish server actually answered, plus any OTHER Lavish daemon of this
  1690. // installation found on the same port at an address the chosen one does not serve. Every candidate
  1691. // is probed in parallel and each probe is bounded, so a hanging or foreign address cannot mask
  1692. // loopback, and a response whose app is lavish-axi wins over a foreign /health. When nothing
  1693. // answers, the primary URL is still returned so callers have something to spawn against and report.
  1694. async function findRunningServer(port, { reconcileNetwork = false } = {}) {
  1695. const controlHosts = new Set([clientHost(), LOOPBACK_HOST]);
  1696. const probed = await Promise.all(
  1697. serverCandidateHosts().map(async (host) => {
  1698. const baseUrl = serverBaseUrl(host, port);
  1699. const health = await probeHealth(baseUrl, { reconcileNetwork: false, timeoutMs: HEALTH_PROBE_TIMEOUT_MS });
  1700. return health ? { host, baseUrl, health } : null;
  1701. }),
  1702. );
  1703. const found = probed.filter((entry) => entry !== null);
  1704. const owned = found.filter((entry) => isOwnedServer(entry, controlHosts));
  1705. const foreign =
  1706. found.find(
  1707. (entry) =>
  1708. controlHosts.has(entry.host) && entry.health.app === "lavish-axi" && !isOwnedServer(entry, controlHosts),
  1709. ) ?? null;
  1710. const chosen = owned[0];
  1711. if (!chosen) {
  1712. const other = found.find((entry) => controlHosts.has(entry.host));
  1713. return other
  1714. ? { baseUrl: other.baseUrl, health: other.health, duplicates: [], foreign }
  1715. : { baseUrl: serverBaseUrl(clientHost(), port), health: null, duplicates: [], foreign };
  1716. }
  1717. let health = chosen.health;
  1718. if (reconcileNetwork) {
  1719. health =
  1720. (await probeHealth(chosen.baseUrl, { reconcileNetwork: true, timeoutMs: HEALTH_RECONCILE_TIMEOUT_MS })) ?? health;
  1721. }
  1722. return { baseUrl: chosen.baseUrl, health, duplicates: ownedDuplicates(owned, chosen), foreign };
  1723. }
  1724. // Other Lavish daemons of this installation on the same port. An address the chosen server itself
  1725. // reports as bound, or a matching process identity through a proxy, is not a duplicate. A server
  1726. // too old to report its addresses is about to be replaced by version, so every other address is
  1727. // retired with it: an old daemon left holding loopback would otherwise make the upgraded server
  1728. // refuse to start.
  1729. function ownedDuplicates(owned, chosen) {
  1730. const covered = new Set([chosen.host, ...(Array.isArray(chosen.health.hosts) ? chosen.health.hosts : [])]);
  1731. const chosenId = chosen.health.process_id;
  1732. const duplicates = [];
  1733. for (const entry of owned) {
  1734. const processId = entry.health.process_id;
  1735. if (
  1736. entry === chosen ||
  1737. covered.has(entry.host) ||
  1738. (typeof processId === "string" && processId !== "" && processId === chosenId)
  1739. )
  1740. continue;
  1741. duplicates.push(entry);
  1742. for (const host of Array.isArray(entry.health.hosts) ? entry.health.hosts : [entry.host]) covered.add(host);
  1743. }
  1744. return duplicates;
  1745. }
  1746. // Duplicates are retired over their own /shutdown, never by process name or port-wide signal, so
  1747. // nothing but an identified Lavish server of this installation is ever stopped.
  1748. async function stopDuplicateServers(duplicates, { reloadKey = "", reason = "" } = {}) {
  1749. for (const duplicate of duplicates) {
  1750. await requestShutdown(duplicate.baseUrl, {
  1751. reloadKey,
  1752. reason: reason || serverReplacementReason(VERSION, duplicate.health),
  1753. });
  1754. await waitForPortFree(duplicate.baseUrl, 3000);
  1755. }
  1756. }
  1757. // Keep the running server, retiring any same-port duplicate first. Only duplicates whose addresses
  1758. // the kept server already requests reach here (`hostsToServe`), and the reconcile afterwards makes
  1759. // it bind an address the duplicate was holding right away, instead of on its next background retry.
  1760. async function adoptServer(baseUrl, duplicates, reloadKey) {
  1761. if (duplicates.length === 0) return baseUrl;
  1762. await stopDuplicateServers(duplicates, { reloadKey });
  1763. await probeHealth(baseUrl, { reconcileNetwork: true, timeoutMs: HEALTH_RECONCILE_TIMEOUT_MS });
  1764. return baseUrl;
  1765. }
  1766. // The concrete addresses this CLI's own LAVISH_AXI_HOST needs a server to serve. Without an explicit
  1767. // host any running server will do: loopback is always served, and Tailscale is the server's to
  1768. // detect. A name that does not resolve right now is still required as the name, so the server is
  1769. // asked to serve it, retries it, and reports it as network_warning instead of it being dropped.
  1770. async function requiredServerHosts(env = process.env) {
  1771. const envHost = env.LAVISH_AXI_HOST?.trim();
  1772. if (!envHost || isWildcardHost(envHost)) return [];
  1773. return resolveConcreteListenHosts([clientHost(env)], { keepUnresolved: true });
  1774. }
  1775. // Which required addresses a running server was never asked to serve. An address it was asked for
  1776. // but has not bound yet is NOT missing: that server is already retrying it, and a replacement could
  1777. // not bind it either. A server too old to report its requested addresses is judged by version.
  1778. export function missingServerHosts(healthBody, requiredHosts) {
  1779. if (!healthBody || !Array.isArray(healthBody.requested_hosts)) return [];
  1780. return requiredHosts.filter((host) => !healthBody.requested_hosts.includes(host));
  1781. }
  1782. // Every address the replaced servers were asked to serve, so a replacement - for an upgrade, a
  1783. // changed network, or a missing host - never drops another agent's address and its review links.
  1784. // This CLI's own hosts come from its environment. An address that is no longer on this machine (a
  1785. // Tailscale IP from a network that went away) is left out, so the replacement does not retry it
  1786. // forever; one still on a local interface is kept even when the network around it changed.
  1787. export function inheritedListenHosts(
  1788. healthBodies,
  1789. requiredHosts,
  1790. inherited = [],
  1791. localAddresses = localInterfaceAddresses(),
  1792. ) {
  1793. const hosts = [...inherited];
  1794. for (const health of healthBodies) {
  1795. if (!health || !Array.isArray(health.requested_hosts)) continue;
  1796. for (const host of health.requested_hosts) {
  1797. if (host === LOOPBACK_HOST || requiredHosts.includes(host)) continue;
  1798. if (isIP(host) && !localAddresses.includes(host)) continue;
  1799. if (!hosts.includes(host)) hosts.push(host);
  1800. }
  1801. }
  1802. return hosts;
  1803. }
  1804. // Every address a kept server has to be asked to serve: this CLI's own, and every address a
  1805. // same-port duplicate serves, so retiring that duplicate never takes its review links with it.
  1806. function hostsToServe(requiredHosts, duplicates) {
  1807. return inheritedListenHosts(
  1808. duplicates.map((duplicate) => duplicate.health),
  1809. [],
  1810. requiredHosts,
  1811. );
  1812. }
  1813. async function probeHealth(baseUrl, { reconcileNetwork, timeoutMs }) {
  1814. const health = await fetchHealth(baseUrl, { reconcileNetwork, timeoutMs });
  1815. return health && typeof health === "object" ? health : null;
  1816. }
  1817. // `reloadKey` names the session this invocation is about to open. A version-driven replacement
  1818. // reloads that chrome only; every other open review page is told it is outdated and left alone.
  1819. async function ensureServer({ forceRestart = false, reloadKey = "" } = {}) {
  1820. const port = defaultPort();
  1821. const requiredHosts = await requiredServerHosts();
  1822. const { baseUrl, health: existing, duplicates, foreign } = await findRunningServer(port, { reconcileNetwork: true });
  1823. if (foreign) throw otherInstallationError(port, foreign);
  1824. const missingHosts =
  1825. existing?.app === "lavish-axi" ? missingServerHosts(existing, hostsToServe(requiredHosts, duplicates)) : [];
  1826. if (existing && !shouldRestartServer(VERSION, existing, forceRestart) && missingHosts.length === 0) {
  1827. return adoptServer(baseUrl, duplicates, reloadKey);
  1828. }
  1829. let alsoListen = inheritedListenHosts([existing, ...duplicates.map((duplicate) => duplicate.health)], requiredHosts);
  1830. let unidentified = "";
  1831. if (existing) {
  1832. if (!(await canControlServerOnPort(baseUrl, existing, listenerMatchesLavish))) {
  1833. throw new AxiError(`Port ${port} is occupied by a non-Lavish server`, "SERVER_ERROR", [
  1834. `Stop the process using port ${port}, or set LAVISH_AXI_PORT to another port`,
  1835. ]);
  1836. }
  1837. await stopDuplicateServers(duplicates, { reloadKey });
  1838. // Stale server from an older release is squatting on the port. Ask it to shut down
  1839. // gracefully so the upgraded client doesn't keep handing users an old chrome.
  1840. await requestShutdown(baseUrl, { reloadKey, reason: serverReplacementReason(VERSION, existing, forceRestart) });
  1841. const freed = await waitForPortFree(baseUrl, 2000);
  1842. if (!freed) {
  1843. // Pre-handshake servers (any release older than this change) don't expose /shutdown
  1844. // so the POST 404'd. Fall back to SIGTERM by PID so the very first upgrade still
  1845. // works, then keep waiting.
  1846. if (shouldKillProcessOnPort(VERSION, existing)) {
  1847. if (killLavishListener(baseUrl)) await waitForPortFree(baseUrl, 3000);
  1848. else unidentified = baseUrl;
  1849. }
  1850. }
  1851. }
  1852. await startServer(port, { alsoListen });
  1853. const replacedForNetwork =
  1854. Boolean(existing) &&
  1855. existing.app === "lavish-axi" &&
  1856. existing.network_stale === true &&
  1857. !forceRestart &&
  1858. typeof existing.version === "string" &&
  1859. !isServerOlderThanCli(VERSION, existing.version);
  1860. let networkRestarted = replacedForNetwork;
  1861. let raceRestarted = false;
  1862. let deadline = Date.now() + 5000;
  1863. while (Date.now() < deadline) {
  1864. const {
  1865. baseUrl: liveUrl,
  1866. health,
  1867. duplicates: liveDuplicates,
  1868. foreign: liveForeign,
  1869. } = await findRunningServer(port, { reconcileNetwork: true });
  1870. if (liveForeign) throw otherInstallationError(port, liveForeign);
  1871. const liveMissing =
  1872. health?.app === "lavish-axi" ? missingServerHosts(health, hostsToServe(requiredHosts, liveDuplicates)) : [];
  1873. // Once is the bound: every replacement carries the hosts of the server it replaces, so two CLIs
  1874. // that each need their own address converge on one server instead of replacing each other.
  1875. if (health && !shouldRestartServer(VERSION, health)) {
  1876. if (liveMissing.length === 0) return adoptServer(liveUrl, liveDuplicates, reloadKey);
  1877. if (raceRestarted) throw missingHostsError(port, liveMissing);
  1878. }
  1879. // Another daemon won the port while ours was starting (ours exits when a Lavish server already
  1880. // owns loopback) - an older release, or one missing an address this CLI needs. Retire it and
  1881. // start once more rather than wait it out.
  1882. if (health?.app === "lavish-axi" && health.network_stale !== true && !raceRestarted) {
  1883. raceRestarted = true;
  1884. alsoListen = inheritedListenHosts(
  1885. [health, ...liveDuplicates.map((duplicate) => duplicate.health)],
  1886. requiredHosts,
  1887. alsoListen,
  1888. );
  1889. await stopDuplicateServers(liveDuplicates, { reloadKey });
  1890. await requestShutdown(liveUrl, { reloadKey, reason: serverReplacementReason(VERSION, health) });
  1891. if (!(await waitForPortFree(liveUrl, 3000))) break;
  1892. await startServer(port, { alsoListen });
  1893. deadline = Date.now() + 5000;
  1894. continue;
  1895. }
  1896. if (health?.network_stale === true && health.app === "lavish-axi") {
  1897. if (networkRestarted) {
  1898. if (liveMissing.length > 0) throw missingHostsError(port, liveMissing);
  1899. return adoptServer(liveUrl, liveDuplicates, reloadKey);
  1900. }
  1901. alsoListen = inheritedListenHosts([health], requiredHosts, alsoListen);
  1902. await requestShutdown(liveUrl, { reloadKey, reason: "" });
  1903. if (!(await waitForPortFree(liveUrl, 3000))) break;
  1904. await startServer(port, { alsoListen });
  1905. networkRestarted = true;
  1906. deadline = Date.now() + 5000;
  1907. continue;
  1908. }
  1909. await delay(100);
  1910. }
  1911. if (unidentified) throw unidentifiedListenerError(unidentified);
  1912. throw new AxiError("Lavish Editor server did not start", "SERVER_ERROR", [
  1913. `Run \`lavish-axi server --port ${port}\` to inspect server startup`,
  1914. ]);
  1915. }
  1916. function missingHostsError(port, missingHosts) {
  1917. return new AxiError(
  1918. `The Lavish server on port ${port} does not serve ${missingHosts.join(", ")}, and replacing it did not stick`,
  1919. "SERVER_ERROR",
  1920. ["Run `lavish-axi stop`, then retry"],
  1921. );
  1922. }
  1923. // Pure helper so the upgrade-detection logic is unit-testable without spinning up HTTP.
  1924. // Returns true when the running server is a different (or pre-handshake) version than
  1925. // what this CLI was built with - i.e. the user just upgraded and the stale server needs
  1926. // to step aside.
  1927. export function shouldRestartServer(currentVersion, healthBody, forceRestart = false) {
  1928. if (!healthBody || typeof healthBody !== "object") return false;
  1929. if (forceRestart && healthBody.app === "lavish-axi") return true;
  1930. if (healthBody.network_stale === true && healthBody.app === "lavish-axi") return true;
  1931. if (typeof healthBody.version !== "string" || healthBody.version === "") return true;
  1932. return isServerOlderThanCli(currentVersion, healthBody.version);
  1933. }
  1934. // A running server newer than this CLI is adopted, never replaced: two installed versions on one
  1935. // machine would otherwise restart each other's server in turn. Numeric, so 0.1.9 is older than
  1936. // 0.1.10. A version that does not parse falls back to "different means replace".
  1937. function isServerOlderThanCli(currentVersion, runningVersion) {
  1938. if (runningVersion === currentVersion) return false;
  1939. const current = parseReleaseVersion(currentVersion);
  1940. const running = parseReleaseVersion(runningVersion);
  1941. if (!current || !running) return true;
  1942. for (let index = 0; index < 3; index += 1) {
  1943. if (running[index] !== current[index]) return running[index] < current[index];
  1944. }
  1945. return false;
  1946. }
  1947. function parseReleaseVersion(version) {
  1948. const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(version));
  1949. return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
  1950. }
  1951. // Which branch of `shouldRestartServer` actually fired, because that is what the other open
  1952. // review pages are told. A local-build force replaces a server of the SAME version, so calling it
  1953. // an upgrade would be false on both counts; only a version this CLI does not match is one.
  1954. export function serverReplacementReason(currentVersion, healthBody, forceRestart = false) {
  1955. if (!shouldRestartServer(currentVersion, healthBody, forceRestart)) return "";
  1956. const runningVersion = healthBody.version;
  1957. if (
  1958. typeof runningVersion !== "string" ||
  1959. runningVersion === "" ||
  1960. isServerOlderThanCli(currentVersion, runningVersion)
  1961. ) {
  1962. return "upgrade";
  1963. }
  1964. return forceRestart ? "local-build" : "";
  1965. }
  1966. export function shouldForceRestartForLocalBuild(executablePath, sourceServerExists = localSourceServerExists()) {
  1967. const localBuildEntry = fileURLToPath(new URL("../dist/cli.mjs", import.meta.url));
  1968. return sourceServerExists && path.resolve(executablePath) === path.resolve(localBuildEntry);
  1969. }
  1970. function localSourceServerExists() {
  1971. return existsSync(fileURLToPath(new URL("../src/server.js", import.meta.url)));
  1972. }
  1973. export function shouldKillProcessOnPort(currentVersion, healthBody) {
  1974. if (!healthBody || typeof healthBody !== "object") return false;
  1975. if (typeof healthBody.version !== "string" || healthBody.version === "") return true;
  1976. if (healthBody.app !== "lavish-axi") return false;
  1977. return isServerOlderThanCli(currentVersion, healthBody.version);
  1978. }
  1979. async function canControlServerOnPort(baseUrl, healthBody, processMatchesLavish) {
  1980. if (!healthBody || typeof healthBody !== "object") return false;
  1981. if (healthBody.app === "lavish-axi") return true;
  1982. if (typeof healthBody.version === "string" && healthBody.version !== "") return false;
  1983. return processMatchesLavish(baseUrl);
  1984. }
  1985. /**
  1986. * @param {string} baseUrl
  1987. * @param {{ reconcileNetwork?: boolean, timeoutMs?: number }} [options]
  1988. */
  1989. // Plain node:http with the socket destroyed on every exit path, not fetch: an aborted fetch leaves
  1990. // its TCP connect running, and discovery dials every local address - including a Tailscale IPv6
  1991. // address that silently drops connections to itself - so each CLI invocation lingered for the OS
  1992. // connect timeout (~10s) after printing its result.
  1993. function fetchHealth(baseUrl, { reconcileNetwork = false, timeoutMs = DEFAULT_HEALTH_TIMEOUT_MS } = {}) {
  1994. return new Promise((resolve) => {
  1995. let settled = false;
  1996. /** @type {import("node:http").ClientRequest | null} */
  1997. let request = null;
  1998. const finish = (value) => {
  1999. if (settled) return;
  2000. settled = true;
  2001. clearTimeout(timer);
  2002. request?.destroy();
  2003. resolve(value);
  2004. };
  2005. const abort = () => finish(null);
  2006. const timer = setTimeout(abort, timeoutMs);
  2007. try {
  2008. const url = new URL(`${baseUrl}/health${reconcileNetwork ? "?reconcile_network=1" : ""}`);
  2009. request = httpGet(url, { agent: false }, (response) => {
  2010. let body = "";
  2011. response.setEncoding("utf8");
  2012. response.on("data", (chunk) => {
  2013. body += chunk;
  2014. if (body.length > MAX_HEALTH_BODY_BYTES) finish(null);
  2015. });
  2016. response.on("end", () => {
  2017. if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 300) {
  2018. finish(null);
  2019. return;
  2020. }
  2021. try {
  2022. finish(JSON.parse(body));
  2023. } catch {
  2024. finish(null);
  2025. }
  2026. });
  2027. response.on("error", abort);
  2028. });
  2029. request.on("error", abort);
  2030. } catch {
  2031. abort();
  2032. }
  2033. });
  2034. }
  2035. // `reason` is what every other open review page is told: this CLI has exactly two callers, and
  2036. // each knows which of them it is.
  2037. async function requestShutdown(baseUrl, { reloadKey = "", reason = "" } = {}) {
  2038. const body = {};
  2039. if (reloadKey) body.reload_key = reloadKey;
  2040. if (reason) body.reason = reason;
  2041. try {
  2042. await fetch(`${baseUrl}/shutdown`, {
  2043. method: "POST",
  2044. headers: { "content-type": "application/json" },
  2045. body: JSON.stringify(body),
  2046. });
  2047. } catch {
  2048. // Best effort. If the server died before answering, the port will free up on its own.
  2049. }
  2050. }
  2051. async function waitForPortFree(baseUrl, timeoutMs) {
  2052. const deadline = Date.now() + timeoutMs;
  2053. while (Date.now() < deadline) {
  2054. if (!(await fetchHealth(baseUrl))) return true;
  2055. await delay(100);
  2056. }
  2057. return false;
  2058. }
  2059. // PIDs listening on exactly this server's address and port whose command is Lavish. Other
  2060. // processes can share the port at other addresses, so nothing is identified by port alone.
  2061. // macOS/Linux only (lsof) - lavish-axi isn't shipped for Windows today.
  2062. function lavishListenerPids(baseUrl) {
  2063. const { hostname, port } = new URL(baseUrl);
  2064. try {
  2065. const listing = spawnSync("lsof", ["-t", `-iTCP@${hostname}:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" });
  2066. if (listing.status !== 0) return [];
  2067. const pids = [];
  2068. for (const line of listing.stdout.split("\n")) {
  2069. const pid = Number(line.trim());
  2070. if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) continue;
  2071. const command = spawnSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
  2072. if (command.status === 0 && /lavish-axi/.test(command.stdout)) pids.push(pid);
  2073. }
  2074. return pids;
  2075. } catch {
  2076. return [];
  2077. }
  2078. }
  2079. function listenerMatchesLavish(baseUrl) {
  2080. return lavishListenerPids(baseUrl).length > 0;
  2081. }
  2082. // Last-resort fallback for the bootstrap upgrade case: a pre-handshake server is squatting on the
  2083. // port and doesn't expose /shutdown, so its PID is resolved and SIGTERM'd. Reports whether a Lavish
  2084. // process was found to signal.
  2085. function killLavishListener(baseUrl) {
  2086. const pids = lavishListenerPids(baseUrl);
  2087. for (const pid of pids) {
  2088. try {
  2089. process.kill(pid, "SIGTERM");
  2090. } catch {
  2091. // Process already gone or permission denied - either way nothing we can do.
  2092. }
  2093. }
  2094. return pids.length > 0;
  2095. }
  2096. function unidentifiedListenerError(baseUrl) {
  2097. const { host } = new URL(baseUrl);
  2098. return new AxiError(
  2099. `The server at ${host} did not shut down, and no Lavish process listening there could be identified`,
  2100. "SERVER_ERROR",
  2101. [`Stop the process listening on ${host} yourself, or set LAVISH_AXI_PORT to another port`],
  2102. );
  2103. }
  2104. async function startServer(port, { alsoListen = [] } = {}) {
  2105. await ensureStateDir();
  2106. const entry = resolveServerEntry();
  2107. let logFd = null;
  2108. try {
  2109. logFd = openSync(serverLogFile(), "a");
  2110. } catch {
  2111. // If logging cannot be initialized, keep the server behavior unchanged.
  2112. }
  2113. try {
  2114. const args = [entry, "server", "--port", String(port)];
  2115. for (const host of alsoListen) args.push("--also-listen", host);
  2116. const child = spawn(process.execPath, args, createServerSpawnOptions(logFd));
  2117. child.unref();
  2118. } finally {
  2119. if (logFd !== null) closeSync(logFd);
  2120. }
  2121. }
  2122. // The detached server child must stamp stdio before evaluating the CLI. In source layout that
  2123. // is `../bin/lavish-axi-server.js`. In the published bundle only `dist/` ships, so the sibling
  2124. // `server.mjs` bootstrap is the entry. Ordinary user-facing commands still use `bin/lavish-axi.js`
  2125. // / `dist/cli.mjs`.
  2126. function resolveServerEntry() {
  2127. const sourceEntry = fileURLToPath(new URL("../bin/lavish-axi-server.js", import.meta.url));
  2128. if (existsSync(sourceEntry)) return sourceEntry;
  2129. return fileURLToPath(new URL("./server.mjs", import.meta.url));
  2130. }
  2131. /**
  2132. * @param {number | null} logFd
  2133. * @returns {import("node:child_process").SpawnOptions}
  2134. */
  2135. export function createServerSpawnOptions(logFd = null) {
  2136. const stdio = /** @type {import("node:child_process").StdioOptions} */ (
  2137. logFd === null ? "ignore" : ["ignore", logFd, logFd]
  2138. );
  2139. // The server is shared machine-wide, so it must not pin the first caller's folder: tools that
  2140. // reap processes by working directory when deleting a worktree would stop every open session.
  2141. // The state dir is passed absolute so a relative LAVISH_AXI_STATE_DIR is not re-resolved
  2142. // against that new cwd.
  2143. const dir = path.resolve(stateDir());
  2144. return {
  2145. detached: true,
  2146. stdio,
  2147. cwd: dir,
  2148. env: { ...process.env, LAVISH_AXI_STATE_DIR: dir, LAVISH_AXI_NO_OPEN: "1" },
  2149. };
  2150. }
  2151. /**
  2152. * @param {string} url
  2153. * @param {{ retries?: number, retryDelayMs?: number, onResponse?: ((response: Response) => void) | null, method?: string, headers?: Record<string, string>, body?: string }} [options]
  2154. */
  2155. export async function fetchJson(
  2156. url,
  2157. { retries = 0, retryDelayMs = 250, onResponse = null, method = "GET", headers, body } = {},
  2158. ) {
  2159. let response;
  2160. for (let attempt = 0; attempt <= retries; attempt += 1) {
  2161. try {
  2162. response = await fetch(url, {
  2163. method,
  2164. ...(headers ? { headers } : {}),
  2165. ...(body === undefined ? {} : { body }),
  2166. });
  2167. break;
  2168. } catch (error) {
  2169. if (error instanceof AxiError) throw error;
  2170. if (attempt >= retries) throw serverConnectionError();
  2171. await delay(retryDelayMs);
  2172. }
  2173. }
  2174. if (!response) throw serverConnectionError();
  2175. if (!response.ok) {
  2176. let payload = null;
  2177. try {
  2178. payload = await response.json();
  2179. } catch {
  2180. // Keep the generic transport error when the server did not send JSON.
  2181. }
  2182. if (payload?.code) {
  2183. const holder = payload.code.startsWith("LISTENER_") && payload.holder;
  2184. const holderDetail =
  2185. holder && typeof holder.label === "string" && Number.isFinite(holder.age_ms)
  2186. ? ` (current listener: ${holder.label}; active for ${Math.max(0, holder.age_ms)}ms)`
  2187. : "";
  2188. const error = new AxiError(
  2189. `${payload.error || `Lavish Editor request failed: ${response.status}`}${holderDetail}`,
  2190. payload.code,
  2191. ["Use --takeover only when you intend to displace the current listener"],
  2192. );
  2193. if (holder) Object.assign(error, { holder });
  2194. throw error;
  2195. }
  2196. throw new AxiError(`Lavish Editor request failed: ${response.status}`, "SERVER_ERROR");
  2197. }
  2198. onResponse?.(response);
  2199. try {
  2200. return await response.json();
  2201. } catch {
  2202. throw pollResponseInterruptedError();
  2203. }
  2204. }
  2205. async function postJson(url, body) {
  2206. let response;
  2207. try {
  2208. response = await fetch(url, {
  2209. method: "POST",
  2210. headers: { "content-type": "application/json" },
  2211. body: JSON.stringify(body),
  2212. });
  2213. } catch {
  2214. throw serverConnectionError();
  2215. }
  2216. if (!response.ok) {
  2217. throw new AxiError(`Lavish Editor request failed: ${response.status}`, "SERVER_ERROR");
  2218. }
  2219. return response.json();
  2220. }
  2221. const AGENT_REPLY_RECEIPT_TIMEOUT_MS = 10_000;
  2222. /**
  2223. * @param {string} url
  2224. * @param {string} text
  2225. * @param {string} file
  2226. * @param {{ timeoutMs?: number }} [options]
  2227. */
  2228. export async function postAgentReply(url, text, file, { timeoutMs = AGENT_REPLY_RECEIPT_TIMEOUT_MS } = {}) {
  2229. const signal = AbortSignal.timeout(timeoutMs);
  2230. let response;
  2231. try {
  2232. response = await fetch(url, {
  2233. method: "POST",
  2234. headers: { "content-type": "application/json" },
  2235. body: JSON.stringify({ text }),
  2236. signal,
  2237. });
  2238. } catch {
  2239. if (signal.aborted) throw agentReplyReceiptTimeoutError(file, timeoutMs);
  2240. throw new AxiError("Lavish Editor server connection failed", "SERVER_ERROR", [
  2241. "Run `lavish-axi server --verbose` or inspect `~/.lavish-axi/server.log` (`LAVISH_AXI_STATE_DIR/server.log` when set) for server startup or crash diagnostics",
  2242. `Re-run \`lavish-axi reply ${file} --agent-reply "<message>"\` after the server is reachable`,
  2243. ]);
  2244. }
  2245. let payload = null;
  2246. try {
  2247. payload = await response.json();
  2248. } catch {
  2249. if (signal.aborted) throw agentReplyReceiptTimeoutError(file, timeoutMs);
  2250. }
  2251. if (response.status === 404) {
  2252. throw new AxiError("No active Lavish Editor session for this file", "NOT_FOUND", [
  2253. `Run \`lavish-axi ${file}\` first`,
  2254. ]);
  2255. }
  2256. if (response.status === 409 && payload?.status === "ended") {
  2257. throw new AxiError("Lavish Editor session has ended; reply was not sent", "SESSION_ENDED", [
  2258. createEndedNextStep(file, payload.ended_by),
  2259. ]);
  2260. }
  2261. if (!response.ok || payload?.status !== "sent") {
  2262. throw new AxiError(`Lavish Editor did not accept the agent reply (${response.status})`, "SERVER_ERROR", [
  2263. `Confirm the session is open with \`lavish-axi ${file}\`, then re-run \`lavish-axi reply ${file}\``,
  2264. ]);
  2265. }
  2266. return payload;
  2267. }
  2268. function agentReplyReceiptTimeoutError(file, timeoutMs) {
  2269. return new AxiError(
  2270. `Lavish Editor did not confirm the agent reply within ${timeoutMs}ms, so acceptance is unknown`,
  2271. "SERVER_ERROR",
  2272. [
  2273. "Run `lavish-axi server --verbose` or inspect `~/.lavish-axi/server.log` (`LAVISH_AXI_STATE_DIR/server.log` when set) for server diagnostics",
  2274. `Check the Lavish Editor conversation for the reply before re-running \`lavish-axi reply ${file}\`, so it is not posted twice`,
  2275. ],
  2276. );
  2277. }
  2278. function serverConnectionError() {
  2279. return new AxiError("Lavish Editor server connection failed", "SERVER_ERROR", [
  2280. "Run `lavish-axi server --verbose` or inspect `~/.lavish-axi/server.log` (`LAVISH_AXI_STATE_DIR/server.log` when set) for server startup or crash diagnostics",
  2281. "Re-run the last `lavish-axi poll <html-file>` command after the server is healthy",
  2282. ]);
  2283. }
  2284. function pollResponseInterruptedError() {
  2285. return new AxiError("Lavish Editor poll response was interrupted", "SERVER_ERROR", [
  2286. "Run `lavish-axi server --verbose` or inspect `~/.lavish-axi/server.log` (`LAVISH_AXI_STATE_DIR/server.log` when set) for server startup or crash diagnostics",
  2287. "Re-run the last `lavish-axi poll <html-file>` command after the server is healthy",
  2288. ]);
  2289. }
  2290. function firstPositionalArg(args, valueFlags = []) {
  2291. const flags = new Set(valueFlags);
  2292. let positionalMode = false;
  2293. for (let i = 0; i < args.length; i += 1) {
  2294. const arg = args[i];
  2295. if (!positionalMode && arg === "--") {
  2296. positionalMode = true;
  2297. continue;
  2298. }
  2299. if (!positionalMode && isValueFlagToken(arg, flags)) {
  2300. if (!arg.includes("=")) i += 1;
  2301. continue;
  2302. }
  2303. if (!positionalMode && arg.startsWith("-")) {
  2304. continue;
  2305. }
  2306. return arg;
  2307. }
  2308. return null;
  2309. }
  2310. function flagValue(args, flag) {
  2311. for (let i = 0; i < args.length; i += 1) {
  2312. const arg = args[i];
  2313. if (arg === "--") return null;
  2314. if (arg === flag) return args[i + 1] || null;
  2315. if (arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1) || null;
  2316. }
  2317. return null;
  2318. }
  2319. function flagValues(args, flag) {
  2320. const values = [];
  2321. for (let i = 0; i < args.length; i += 1) {
  2322. const arg = args[i];
  2323. if (arg === "--") break;
  2324. if (arg === flag && args[i + 1]) {
  2325. values.push(args[i + 1]);
  2326. i += 1;
  2327. } else if (arg.startsWith(`${flag}=`) && arg.length > flag.length + 1) {
  2328. values.push(arg.slice(flag.length + 1));
  2329. }
  2330. }
  2331. return values;
  2332. }
  2333. function inspectValueFlag(args, flag) {
  2334. for (let i = 0; i < args.length; i += 1) {
  2335. const arg = args[i];
  2336. if (arg === "--") return { present: false };
  2337. if (arg === flag) {
  2338. return { present: true, value: i + 1 < args.length ? args[i + 1] : null, swallows: true };
  2339. }
  2340. if (arg.startsWith(`${flag}=`)) {
  2341. return { present: true, value: arg.slice(flag.length + 1), swallows: false };
  2342. }
  2343. }
  2344. return { present: false };
  2345. }
  2346. const AGENT_REPLY_FILE_HINT = "Pass --agent-reply-file <path>, or --agent-reply-file - to read stdin";
  2347. function agentReplyTooLargeError(suggestion) {
  2348. return new AxiError(`Agent reply exceeds the ${AGENT_REPLY_LIMIT_LABEL}`, "VALIDATION_ERROR", [
  2349. suggestion || "Shorten the reply, then retry the same poll command",
  2350. ]);
  2351. }
  2352. /**
  2353. * @param {import("node:stream").Readable} stream
  2354. */
  2355. async function readAgentReplyStream(stream, tooLargeHelp) {
  2356. const chunks = [];
  2357. let bytes = 0;
  2358. for await (const value of stream) {
  2359. const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
  2360. bytes += chunk.length;
  2361. if (bytes > AGENT_REPLY_INPUT_LIMIT_BYTES) {
  2362. stream.destroy();
  2363. throw agentReplyTooLargeError(tooLargeHelp);
  2364. }
  2365. chunks.push(chunk);
  2366. }
  2367. const text = Buffer.concat(chunks, bytes).toString("utf8");
  2368. if (Buffer.byteLength(JSON.stringify({ agent_reply: text })) > AGENT_REPLY_JSON_LIMIT_BYTES) {
  2369. throw agentReplyTooLargeError(tooLargeHelp);
  2370. }
  2371. return text;
  2372. }
  2373. /**
  2374. * Resolve the agent-reply body from `--agent-reply` or `--agent-reply-file`.
  2375. * File/stdin is the path for a longer Markdown body so newlines survive quoting.
  2376. *
  2377. * @param {string[]} args
  2378. * @param {{
  2379. * createReadStreamFn?: typeof createReadStream,
  2380. * stdin?: import("node:stream").Readable,
  2381. * stdinIsTTY?: boolean,
  2382. * tooLargeHelp?: string,
  2383. * }} [io]
  2384. * @returns {Promise<string | null>}
  2385. */
  2386. export async function resolveAgentReply(
  2387. args,
  2388. {
  2389. createReadStreamFn = createReadStream,
  2390. stdin = process.stdin,
  2391. stdinIsTTY = process.stdin.isTTY === true,
  2392. tooLargeHelp = undefined,
  2393. } = {},
  2394. ) {
  2395. const inline = inspectValueFlag(args, "--agent-reply");
  2396. const fromFile = inspectValueFlag(args, "--agent-reply-file");
  2397. if (inline.present && fromFile.present) {
  2398. throw new AxiError("--agent-reply and --agent-reply-file cannot be combined", "VALIDATION_ERROR", [
  2399. "Pass --agent-reply for a concise quoted reply, or --agent-reply-file <path> (`-` for stdin) when a longer Markdown body is necessary",
  2400. ]);
  2401. }
  2402. if (fromFile.present) {
  2403. return readAgentReplyFile(fromFile, { createReadStreamFn, stdin, stdinIsTTY, tooLargeHelp });
  2404. }
  2405. if (!inline.present) return null;
  2406. return inline.value || null;
  2407. }
  2408. /**
  2409. * @param {{ present: boolean, value?: string | null, swallows?: boolean }} fromFile
  2410. * @param {{
  2411. * createReadStreamFn: typeof createReadStream,
  2412. * stdin: import("node:stream").Readable,
  2413. * stdinIsTTY: boolean,
  2414. * tooLargeHelp?: string,
  2415. * }} io
  2416. */
  2417. async function readAgentReplyFile(fromFile, { createReadStreamFn, stdin, stdinIsTTY, tooLargeHelp }) {
  2418. if (fromFile.swallows && typeof fromFile.value === "string" && fromFile.value.startsWith("--")) {
  2419. throw new AxiError(
  2420. `--agent-reply-file was given no value: the next argument ${fromFile.value} is another flag, so it would have been used as the path`,
  2421. "VALIDATION_ERROR",
  2422. [AGENT_REPLY_FILE_HINT, "Use --agent-reply-file=<path> if the path itself starts with --"],
  2423. );
  2424. }
  2425. const spec = fromFile.value;
  2426. if (spec == null || !String(spec).trim()) {
  2427. throw new AxiError("--agent-reply-file was given an empty value", "VALIDATION_ERROR", [AGENT_REPLY_FILE_HINT]);
  2428. }
  2429. let text;
  2430. if (spec === "-") {
  2431. if (stdinIsTTY) {
  2432. throw new AxiError("--agent-reply-file - cannot read stdin from a terminal", "VALIDATION_ERROR", [
  2433. "Pipe a Markdown body into stdin, or pass --agent-reply-file <path>",
  2434. ]);
  2435. }
  2436. try {
  2437. text = await readAgentReplyStream(stdin, tooLargeHelp);
  2438. } catch (error) {
  2439. if (error instanceof AxiError) throw error;
  2440. const detail = error instanceof Error ? error.message : String(error);
  2441. throw new AxiError(`Cannot read --agent-reply-file stdin: ${detail}`, "VALIDATION_ERROR", [
  2442. "Pipe a Markdown body into stdin, or pass --agent-reply-file <path>",
  2443. ]);
  2444. }
  2445. } else {
  2446. try {
  2447. text = await readAgentReplyStream(createReadStreamFn(spec), tooLargeHelp);
  2448. } catch (error) {
  2449. if (error instanceof AxiError) throw error;
  2450. const detail = error instanceof Error ? error.message : String(error);
  2451. throw new AxiError(`Cannot read --agent-reply-file ${spec}: ${detail}`, "VALIDATION_ERROR", [
  2452. "Pass a UTF-8 Markdown file, or `-` to read stdin",
  2453. ]);
  2454. }
  2455. }
  2456. if (!String(text || "").trim()) {
  2457. throw new AxiError("--agent-reply-file was empty", "VALIDATION_ERROR", [
  2458. 'Write Markdown into the file, or pass --agent-reply "<message>" for a concise reply',
  2459. ]);
  2460. }
  2461. return String(text);
  2462. }
  2463. function isValueFlagToken(arg, flags) {
  2464. for (const flag of flags) {
  2465. if (arg === flag || arg.startsWith(`${flag}=`)) return true;
  2466. }
  2467. return false;
  2468. }
  2469. function delay(ms) {
  2470. return new Promise((resolve) => setTimeout(resolve, ms));
  2471. }
  2472. export function getCommandHelp(command, { agent = "generic" } = {}) {
  2473. return createCommandHelp({ agent })[command] || null;
  2474. }
  2475. function createTopLevelHelp({ agent = "generic" } = {}) {
  2476. return `lavish-axi - Lavish Editor AXI\n\nUsage:\n lavish-axi\n lavish-axi <html-file> [--no-open] [--no-gate] [--reopen]\n lavish-axi poll <html-file> [--owner <label>] [--takeover] [--agent-reply "..."] [--agent-reply-file <path>]\n lavish-axi reply <html-file> (--agent-reply "..." | --agent-reply-file <path>)\n lavish-axi end <html-file>\n lavish-axi export <html-file> [--out <path>]\n lavish-axi share <html-file> [--private | --password <pw>] [--token <t>]\n lavish-axi share <html-file> --site <site_id> --update-key <key> [--private | --password <pw>]\n lavish-axi share --unpublish --site <site_id> --update-key <key>\n lavish-axi stop\n lavish-axi playbook [playbook_id]\n lavish-axi design\n lavish-axi libraries [--search <text>] [--library <id>]\n lavish-axi setup hooks\n lavish-axi setup plugin\n\n${DESIGN_SYSTEM_HINT}\n\nNote: poll long-polls until the user sends feedback, ends the session, or leaves every review window disconnected past the reconnect grace period, staying silent while it waits - never kill it. Layout issues the browser detects are passive: they collect in the user's Layout issues inbox in the Lavish top bar and reach the agent only when the user selects them and queues the fixes, as an ordinary tag "layout-warnings" prompt. Do not pass --timeout-ms during normal agent use; it is for tests and debugging only. ${pollExecutionGuidance({ agent })} ${POLL_SEND_AND_END_RULE} Use \`lavish-axi reply\` when handing a result back without waiting for more feedback: it exits 0 only after the server accepts the reply, so the board stops showing Working. \`poll --agent-reply\` posts a reply and then keeps waiting.\n\n`;
  2477. }
  2478. function createCommandHelp({ agent = "generic" } = {}) {
  2479. return {
  2480. open: `Usage: lavish-axi <html-file> [--no-open] [--no-gate] [--reopen]\n\nOpen or resume a Lavish Editor review session for an HTML artifact. Use --no-open when you need to ensure the server/session exists without opening another browser window. Use --no-gate to skip the open-time layout curtain for this browser open. If the user explicitly ended the session from the browser, this refuses to reopen it and returns guidance instead - pass --reopen to force it open when the user asks for further review or something important needs their visual attention. Sessions ended by the agent (\`lavish-axi end\`) reopen normally without the flag.\n`,
  2481. poll: `Usage: lavish-axi poll <html-file> [--owner <label>] [--takeover] [--agent-reply "..."] [--agent-reply-file <path>]\n\nThis command exclusively long-polls for queued user prompts. Pass --owner <label> to make the active listener visible in session listings; --takeover displaces an existing listener, which receives LISTENER_REPLACED. A second poll without --takeover fails with LISTENER_ACTIVE instead of silently returning waiting.\n\nThis command long-polls indefinitely for queued user prompts. It stays silent while it waits - that is normal, never kill it. Browser-detected layout issues do NOT return this poll: they are filed passively in the user's Layout issues inbox and arrive as an ordinary tag "layout-warnings" prompt only after the user selects them and queues the fixes. Warning lifecycle: an issue stays unresolved and counted while queued, becomes recurring if a newer artifact revision still shows it, and is resolved only after a newer artifact load plus a complete diagnostic pass at the same viewport no longer detects it. A failed or incomplete pass preserves it as unverified rather than clearing it. The only response that arrives without user action is artifact_failures - a fatal failure that made the review surface itself unusable. Do not pass --timeout-ms during normal agent use; it is for tests and debugging only. In a Herdr-managed pane, set LAVISH_AXI_HERDR_CHIME=1 to request attention when the poll has entered its waiting state; unset it or use any other value to keep the current silent behavior. Notification failures never interrupt the poll. ${pollExecutionGuidance({ agent })} Use --agent-reply after applying prior feedback to display a concise response in Lavish Editor before waiting again. When you are handing a result back and are not about to long-poll, run \`lavish-axi reply <html-file> --agent-reply "..."\` instead: that command exits 0 only after the server accepts the reply, so the board stops showing Working without this poll staying open. ${POLL_AGENT_REPLY_RULE} ${POLL_AGENT_REPLY_HELP_POINTER} Do not combine --agent-reply with --agent-reply-file.\n\nExamples:\n lavish-axi poll report.html --agent-reply "Renamed the payment step."\n lavish-axi poll report.html --agent-reply-file reply.md\n lavish-axi poll report.html --agent-reply-file -\n\n${POLL_SEND_AND_END_RULE}\n`,
  2482. reply: `Usage: lavish-axi reply <html-file> (--agent-reply "..." | --agent-reply-file <path>)\n\nPost an agent reply to the open Lavish Editor session and exit once the server confirms it was accepted. Exit 0 only when the server answers that the reply was sent, which is when the board stops showing Working. If that answer does not arrive within ${AGENT_REPLY_RECEIPT_TIMEOUT_MS / 1000} seconds, exit non-zero with a timeout error. Use this when you are handing a result back and are not about to wait for more feedback. A reply also marks every note the poll delivered to you as Done in the reviewer's panel, so reply once you have handled them.\n\nUse \`lavish-axi poll <html-file> --agent-reply "..."\` instead when the reply should be followed by a long-poll. That command posts the reply and then keeps waiting, so it does not exit when the reply is accepted.\n\nPass exactly one of --agent-reply or --agent-reply-file. ${POLL_AGENT_REPLY_RULE} ${POLL_AGENT_REPLY_HELP_POINTER} Do not combine the two flags. An empty reply is refused.\n\nExamples:\n lavish-axi reply report.html --agent-reply "Renamed the payment step."\n lavish-axi reply report.html --agent-reply-file reply.md\n lavish-axi reply report.html --agent-reply-file -\n`,
  2483. end: `Usage: lavish-axi end <html-file>\n\nEnd a Lavish Editor session as the agent. A session ended this way still reopens normally on the next \`lavish-axi <html-file>\`, unlike a user ending it from the browser, which requires --reopen.\n`,
  2484. export: `Usage: lavish-axi export <html-file> [--out <path>]\n\nWrite a portable copy of an artifact: one HTML file with its LOCAL assets inlined (relative-path stylesheets, scripts, images, and fonts become inline <style>/<script> blocks and data URIs). Remote CDN/font references (https URLs) are left as links for the browser to load, so the file needs network to render those. Lavish makes no outbound requests - it only reads local files, confined to the artifact's directory. Defaults to writing <name>.export.html next to the source; pass --out to choose a path. The Lavish annotation SDK is never included in an export.\n`,
  2485. share: `Usage:\n lavish-axi share <html-file> [--private | --password <pw>] [--token <t>]\n lavish-axi share <html-file> --site <site_id> --update-key <key> [--private | --password <pw>]\n lavish-axi share --unpublish --site <site_id> --update-key <key>\n\nPublish the artifact on ht-ml.app (https://ht-ml.app), a third-party hosting service not part of Lavish, and print a visitable URL. Shares are PUBLIC by default: anyone with the link can open the page, and it may be indexed or scraped. Pass --private to publish a PRIVATE page behind a generated password, returned once in the output - give it to the user with the URL and tell them it is a shared secret. Pass --password <pw> instead when the user chose the password; it is never echoed back. Builds the same local-inlined HTML as 'export' (local assets inlined; remote CDN/font URLs left as links and are not blocked by CSP on ht-ml.app, but still load over the viewer's network), then POSTs it to ht-ml.app's /v1 API. Creating a site needs no account or API key. The response includes the url plus a secret update_key (shown once) for changing the page later.\n\n--site <site_id> with --update-key <key> republishes an existing page in place: same URL, new HTML. On a republish the password is left alone unless you pass --private (rotate to a new generated one) or --password <pw> (set one). There is no way to make a private page public again: ht-ml.app accepts a request to clear a password and silently ignores it, so Lavish does not offer one rather than reporting a page as public while it is still gated. Locking a page that was PUBLIC is also not instant at ht-ml.app's CDN: it was observed still answering uncredentialed requests for minutes after the password was set, so do not tell the user a newly gated page is unreachable right away (a page that was already private has no such cached copy).\n\n--unpublish takes the same credentials and no file. ht-ml.app has NO delete endpoint, so this replaces the page with a short placeholder and locks it behind a random password that is immediately discarded; the URL still resolves and the host still holds what was published. Say that to the user rather than calling it deleted. The update_key still works, so republishing with --private brings the page back behind a new password.\n\nA value flag given an empty or whitespace-only value is REFUSED rather than acted on: an unquoted shell variable that is unset makes \`--password $PW\` an empty password, which the host treats as none and would publish a PUBLIC page while you believed it was gated. Quote the value, or pass --private to have Lavish generate one.\n\nSet LAVISH_AXI_HTML_APP_TOKEN (or pass --token) to attach an optional bearer token when CREATING a page; it is never required. A republish (--site/--update-key) or --unpublish rejects --token, because the update_key is what the Authorization header carries there. The annotation SDK is never included.\n`,
  2486. stop: `Usage: lavish-axi stop [--port <port>]\n\nShut down the background Lavish Editor server. The server also stops itself when no browser or poll has been connected for a while (LAVISH_AXI_IDLE_TIMEOUT_MS, default 30m) and immediately when the last session ends with nothing connected.\n`,
  2487. playbook: `Usage: lavish-axi playbook [playbook_id]\n\nList focused artifact guidance playbooks, or show one playbook by ID. Known IDs: diagram, table, comparison, plan, code, input, explanation, slides.\n\n${PLAYBOOK_ROUTER_HELP}\n\nExamples:\n lavish-axi playbook\n lavish-axi playbook diagram\n lavish-axi playbook input\n`,
  2488. libraries: `Usage: lavish-axi libraries [--search <text>] [--library <id>]\n\nList the Excalidraw libraries (.excalidrawlib files) the user copied into ~/.lavish-axi/excalidraw-libraries, or LAVISH_AXI_STATE_DIR/excalidraw-libraries when set. Their items appear in every whiteboard's library panel. --search lists item refs whose ref contains every search word; --library lists one library's item refs. Lavish only reads this directory and never downloads libraries.\n\nExamples:\n lavish-axi libraries\n lavish-axi libraries --search lambda\n lavish-axi libraries --library aws-architecture-icons\n`,
  2489. design: `Usage: lavish-axi design\n\nShow a copy-pasteable CDN snippet for Tailwind CSS browser runtime v4 + DaisyUI v5 + themes, the whiteboard (Mermaid) opt-in snippet, a content-to-playbook router, an optional layout safety CSS snippet, plus technical reference for DaisyUI components. ${PLAYBOOK_ROUTER_HELP} Lavish artifacts stay portable HTML. This CDN snippet is the design fallback, not the default: inspect the subject project before falling back, and paste the layout safety CSS only when useful for dense nested grid/flex layouts, badges, wide fonts, or local media. ${DESIGN_PRIORITY_RULE}\n`,
  2490. setup: `Usage: lavish-axi setup hooks\n lavish-axi setup plugin\n\nhooks: install or repair agent SessionStart hooks for lavish-axi ambient context in Claude Code, Codex, OpenCode, and GitHub Copilot CLI. Restart your agent session afterward to receive the context. This is the primary integration - it carries live session state.\n\nplugin: register the installed lavish-axi package as an Agent Plugin (agent-plugins.org) in VS Code, Cursor, and GitHub Copilot CLI. The installed package directory is itself the plugin root, so nothing is downloaded and no marketplace is involved. Reload each client afterward. Codex users should use \`setup hooks\` instead.\n\nBoth actions are explicit opt-in, idempotent, and repair a stale path after a reinstall.\n`,
  2491. server: `Usage: lavish-axi server [--port 4387] [--verbose] [--also-listen <host>...]\n\nRun the local Lavish Editor server. Pass --verbose (or set LAVISH_AXI_DEBUG=1) to log session and watcher events to stderr. Detached server output is appended to ~/.lavish-axi/server.log, or LAVISH_AXI_STATE_DIR/server.log when set, for startup and crash diagnostics.\n\nBy default Lavish binds to 127.0.0.1 and, when Tailscale is running, this machine's Tailscale IPv4. Any explicit LAVISH_AXI_HOST overrides automatic Tailscale binding; wildcard values such as 0.0.0.0 or :: are restricted to loopback. An explicit non-wildcard LAVISH_AXI_HOST sets the bind address, and the server also listens on 127.0.0.1 so every local CLI finds it; --also-listen adds further concrete addresses (the CLI passes it when it replaces a server, to keep every address the old one served). An address that cannot be bound is retried in the background and reported as network_warning. Binding beyond loopback exposes an unauthenticated server that can read and serve arbitrary local files to anything that can reach it, so only do so on a trusted network. With automatic binding enabled, a successfully bound Tailscale listener uses its MagicDNS name in generated session links; otherwise LAVISH_AXI_LINK_HOST can set the link hostname. See README's Allowed hosts section for Host allowlisting and LAVISH_AXI_ALLOWED_HOSTS. LAVISH_AXI_NO_OPEN=1 (or --no-open) suppresses the local browser launch.\n`,
  2492. };
  2493. }
  2494. export { createDesignOutput };

Version history

  • v0.1.9711/14/2026

  • v0.1.9610/30/2026

  • v0.1.9510/29/2026

  • v0.1.9410/28/2026

  • v0.1.9310/26/2026

  • v0.1.9210/24/2026

  • v0.1.9010/19/2026

  • v0.1.8910/18/2026

  • v0.1.8410/7/2026

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.