From bc723b51bf83d0197fe9625626211b2763b1afb8 Mon Sep 17 00:00:00 2001
From: Zak El Fassi
Date: Thu, 11 Jun 2026 14:09:51 -0700
Subject: [PATCH 01/14] chore: add apache-2.0 license and governance docs
---
.github/ISSUE_TEMPLATE/bug_report.yml | 53 ++++++
.github/ISSUE_TEMPLATE/config.yml | 8 +
.github/ISSUE_TEMPLATE/feature_request.yml | 34 ++++
.github/PULL_REQUEST_TEMPLATE.md | 16 ++
CODE_OF_CONDUCT.md | 85 +++++++++
CONTRIBUTING.md | 74 ++++++++
LICENSE | 202 +++++++++++++++++++++
SECURITY.md | 26 +++
package.json | 1 +
9 files changed, 499 insertions(+)
create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml
create mode 100644 .github/ISSUE_TEMPLATE/config.yml
create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml
create mode 100644 .github/PULL_REQUEST_TEMPLATE.md
create mode 100644 CODE_OF_CONDUCT.md
create mode 100644 CONTRIBUTING.md
create mode 100644 LICENSE
create mode 100644 SECURITY.md
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..a2604c4
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,53 @@
+name: Bug report
+description: Something broke — a bad export, a validator miss, a crashed command
+labels: [bug]
+body:
+ - type: dropdown
+ id: surface
+ attributes:
+ label: Surface
+ description: Where did the problem show up?
+ options:
+ - htmlify skill (SKILL.md flow)
+ - deckify skill (SKILL.md flow)
+ - htmlify-answer CLI
+ - --validate CLI
+ - Pi / Oh-My-Pi extension
+ - Claude Code hook / plugin
+ - Generated artifact (HTML output)
+ - Other
+ validations:
+ required: true
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: What happened?
+ description: What did you do, what did you expect, what happened instead?
+ placeholder: Ran `htmlify-answer --validate deck.html --profile deck` and ...
+ validations:
+ required: true
+ - type: textarea
+ id: repro
+ attributes:
+ label: Reproduction
+ description: Smallest input that reproduces it (command, snippet, or a minimal HTML file).
+ render: shell
+ - type: input
+ id: version
+ attributes:
+ label: Version
+ placeholder: e.g. @zakelfassi/htmlify 1.0.0, or a commit SHA
+ validations:
+ required: true
+ - type: input
+ id: environment
+ attributes:
+ label: Environment
+ placeholder: e.g. Node 22.4 / macOS 15 / Claude Code 2.x
+ - type: checkboxes
+ id: security
+ attributes:
+ label: Security check
+ options:
+ - label: This is not a security vulnerability (those go to SECURITY.md, not public issues)
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..4c067c0
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,8 @@
+blank_issues_enabled: true
+contact_links:
+ - name: Security vulnerability
+ url: https://github.com/zakelfassi/htmlify/security/advisories/new
+ about: Report security issues privately — never in a public issue.
+ - name: Live gallery
+ url: https://zakelfassi.github.io/htmlify/
+ about: See what the skills produce before filing.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..07527ba
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,34 @@
+name: Feature request
+description: A new artifact mode, validator check, integration, or improvement
+labels: [enhancement]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem
+ description: What are you trying to do that htmlify/deckify doesn't handle well today?
+ validations:
+ required: true
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Proposed solution
+ description: What would you like to happen? Sketch the SKILL.md rule, CLI flag, or artifact behavior.
+ validations:
+ required: true
+ - type: dropdown
+ id: area
+ attributes:
+ label: Area
+ options:
+ - htmlify skill / artifact modes
+ - deckify skill / deck modes
+ - Validator / CLI
+ - Agent integrations (hooks, plugin)
+ - Visual identity / theme
+ - Docs / gallery
+ - Other
+ - type: textarea
+ id: alternatives
+ attributes:
+ label: Alternatives considered
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..2b5a82b
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,16 @@
+## What
+
+
+
+## Type
+
+
+
+## Checklist
+
+- [ ] `pnpm lint && pnpm typecheck && pnpm test` is green locally
+- [ ] Conventional commit message(s), one logical change per commit
+- [ ] No breaking change to the compatibility contracts (`_internals`, CLI flags/exit codes, hook path, `pi`/`omp` entry points, `skills/` paths) — or it's marked `feat!:` with a `BREAKING CHANGE:` footer and a migration note
+- [ ] Validator changes come with pass **and** fail fixtures under `test/fixtures/`
+- [ ] Theme or example changes were eyeballed in light mode, dark mode, and print preview
+- [ ] Committed examples still pass `node bin/htmlify-answer.js --validate`
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..454995e
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,85 @@
+
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address, without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at zakelfassi@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of actions.
+
+**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
+
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..f809bd2
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,74 @@
+# Contributing to htmlify
+
+Thanks for your interest in improving htmlify and deckify. This guide covers the workflow, conventions, and quality bar for contributions.
+
+## Quick start
+
+```bash
+git clone https://github.com/zakelfassi/htmlify.git
+cd htmlify
+corepack enable # provisions the pinned pnpm version
+pnpm install
+pnpm test
+```
+
+Requirements: Node.js 20 or newer, pnpm (managed via Corepack — never npm or yarn).
+
+## Development workflow
+
+| Command | What it does |
+| --- | --- |
+| `pnpm test` | Runs the full test suite (`node --test`) |
+| `pnpm lint` | Checks formatting and lint rules (Biome) |
+| `pnpm lint:fix` | Applies safe formatting/lint fixes |
+| `pnpm typecheck` | Type-checks the JSDoc annotations (`tsc --noEmit`) |
+
+All three checks run in CI and must pass before merge.
+
+### Project shape
+
+- `src/` — the runtime, plain CommonJS with JSDoc types. Zero runtime dependencies is a hard constraint: what ships is what you read.
+- `index.js` — thin façade exposing the Pi/OMP extension factory and `_internals`. Do not add logic here.
+- `bin/htmlify-answer.js` — the CLI (export + `--validate`).
+- `hooks/` — agent lifecycle hooks (Claude Code Stop hook). Paths here are a public contract; do not move or rename them.
+- `skills/htmlify/`, `skills/deckify/` — the agent skills (SKILL.md + references). These are product surface, not docs: changes to operating rules or validation steps are behavior changes.
+- `examples/` — committed gallery artifacts. Every file must pass `node bin/htmlify-answer.js --validate` with its profile; CI enforces this.
+
+### Compatibility contracts
+
+Treat these as semver-relevant public API:
+
+- `package.json` `main`, `bin`, `pi.extensions`, `omp.extensions`
+- every name exported on `index.js` `_internals`
+- CLI flags and exit codes of `htmlify-answer`
+- the hook script path `hooks/claude-code-stop-htmlify.js` and its env vars (`HTMLIFY_MIN_CHARS`, `HTMLIFY_EXPORT_ROOT`, `HTMLIFY_SKIP_OPEN`)
+- skill directory paths `skills/htmlify` and `skills/deckify`
+
+## Commit conventions
+
+This repo uses [Conventional Commits](https://www.conventionalcommits.org/); [release-please](https://github.com/googleapis/release-please) turns them into versions and the CHANGELOG.
+
+- `feat:` new capability (minor bump)
+- `fix:` bug fix (patch bump)
+- `feat!:` / `BREAKING CHANGE:` footer — breaking change (major bump)
+- `docs:`, `chore:`, `refactor:`, `test:`, `ci:` — no release impact
+
+Keep commits to one logical change. No `Co-Authored-By` or tool-attribution trailers.
+
+## Pull requests
+
+1. Branch from `main`.
+2. Make sure `pnpm lint && pnpm typecheck && pnpm test` is green locally.
+3. If you touched validation logic, add fixtures under `test/fixtures/` covering both the pass and fail paths.
+4. If you changed an example artifact or the document theme, open the artifact in a browser and check light mode, dark mode (`prefers-color-scheme`), and print preview.
+5. Fill in the PR template — especially the compatibility-contract checklist.
+
+Small, focused PRs review faster than large ones. For anything architectural, open an issue first to discuss.
+
+## Reporting bugs and requesting features
+
+Use the [issue forms](https://github.com/zakelfassi/htmlify/issues/new/choose). For security issues, **do not open a public issue** — see [SECURITY.md](SECURITY.md).
+
+## License
+
+By contributing, you agree that your contributions are licensed under the [Apache License 2.0](LICENSE).
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..06c431d
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,26 @@
+# Security Policy
+
+## Supported versions
+
+| Version | Supported |
+| --- | --- |
+| 1.x | Yes |
+| < 1.0 | No — upgrade to 1.x |
+
+## Reporting a vulnerability
+
+Please report vulnerabilities privately via [GitHub Security Advisories](https://github.com/zakelfassi/htmlify/security/advisories/new) (preferred) or by email to zakelfassi@gmail.com. Do not open a public issue for security reports.
+
+You can expect an acknowledgment within 72 hours and a fix or mitigation plan within 14 days for confirmed issues. Credit is given in the release notes unless you prefer otherwise.
+
+## Threat model and built-in safeguards
+
+htmlify writes HTML files to disk and opens them in your browser, so the main risks are script injection through generated artifacts and untrusted content reaching a rendered page. The runtime defends against this by design:
+
+- **Validation before write.** Rich/model-generated HTML is rejected unless it is a standalone document, and the validator blocks ``;
-}
-
-function injectAnnotationLayer(html, meta) {
- const layer = buildAnnotationLayer(meta);
- const source = String(html || '');
- if (source.includes(TRUSTED_ANNOTATION_MARKER)) return source;
- if (/<\/body\s*>/i.test(source)) return source.replace(/<\/body\s*>/i, `${layer}\n
]/i.test(source)) {
- return source;
- }
-
- return null;
-}
-
-function buildRichHtmlPrompt(lastEligible) {
- return [
- 'Transform the following answer into a standalone, production-quality HTML artifact in the htmlify style.',
- 'Return ONLY a single ```html fenced block and nothing else.',
- 'Requirements:',
- '- Preserve the factual content and conclusions.',
- '- Prefer visual structure over prose walls: use scoreboards, timelines, matrices, diagrams, tabs, accordions, or side-by-side comparisons when they clarify the work.',
- '- Treat HTML as an operator surface: make the result scannable, discussable, and actionable.',
- '- Include the smallest useful artifact shape for the source: brief, deck, implementation map, review packet, report, explainer, or lightweight editor.',
- '- Improve hierarchy, density, labels, and information scent without adding generic SaaS decoration.',
- '- Use inline CSS only. No external assets, scripts, CDNs, or fonts.',
- '- Make it responsive and print-friendly.',
- '- Add simple inline SVG diagrams only if they materially improve comprehension.',
- '- Use semantic sections, accessible contrast, stable spacing, and restrained motion-free presentation.',
- '- Do not mention that this was transformed from another answer.',
- '',
- `Title suggestion: ${lastEligible.title}`,
- '',
- 'Source answer:',
- '```text',
- lastEligible.text,
- '```',
- ].join('\n');
-}
-
-module.exports = function htmlLongAnswerExtension(pi) {
- const state = {
- offerMode: 'ask',
- lastEligible: null,
- lastExport: null,
- pendingRichExport: null,
- lastPromptedSignature: null,
- geminiAvailable: null,
- config: { ...LONG_ANSWER_DEFAULTS },
- };
-
- function rememberFromEntry(entry) {
- if (!entry || entry.type !== 'custom') return;
- if (entry.customType === PREF_ENTRY_TYPE && entry.data && typeof entry.data.offerMode === 'string') {
- state.offerMode = entry.data.offerMode;
- }
- if (entry.customType === SOURCE_ENTRY_TYPE && entry.data && entry.data.text) {
- state.lastEligible = entry.data;
- }
- if (entry.customType === EXPORT_ENTRY_TYPE && entry.data && entry.data.path) {
- state.lastExport = entry.data;
- }
- }
-
- function hydrateLastEligibleFromBranch(branch) {
- if (!Array.isArray(branch) || state.lastEligible) return;
- for (let index = branch.length - 1; index >= 0; index -= 1) {
- const info = extractMessageInfo(branch[index]);
- if (info && info.text) {
- state.lastEligible = buildSourceRecord(info.text);
- return;
- }
- }
- }
-
- async function restoreSessionState(ctx) {
- try {
- const branch =
- ctx && ctx.sessionManager && typeof ctx.sessionManager.getBranch === 'function'
- ? ctx.sessionManager.getBranch()
- : [];
- if (!Array.isArray(branch)) return;
- for (const entry of branch) rememberFromEntry(entry);
- hydrateLastEligibleFromBranch(branch);
- } catch (_) {
- // Best effort only.
- }
- }
-
- async function appendCustomEntry(type, data) {
- if (typeof pi.appendEntry !== 'function') return;
- try {
- await pi.appendEntry(type, data);
- } catch (_) {
- // Do not fail the user flow on persistence issues.
- }
- }
-
- async function setOfferMode(mode) {
- state.offerMode = mode;
- await appendCustomEntry(PREF_ENTRY_TYPE, { offerMode: mode, savedAt: Date.now() });
- }
-
- async function rememberEligibleSource(source) {
- state.lastEligible = source;
- const { text: _text, ...persistedSource } = source;
- await appendCustomEntry(SOURCE_ENTRY_TYPE, persistedSource);
- }
-
- async function rememberExport(meta) {
- state.lastExport = meta;
- await appendCustomEntry(EXPORT_ENTRY_TYPE, meta);
- }
-
- function notify(ctx, message, level) {
- if (!ctx || !ctx.ui || typeof ctx.ui.notify !== 'function') return;
- try {
- const result = ctx.ui.notify(message, level || 'info');
- if (result && typeof result.then === 'function') {
- result.catch(() => {});
- }
- } catch (_) {
- // Ignore UI failures.
- }
- }
-
- function notifyCommandError(ctx, error) {
- notify(
- ctx,
- `${PRODUCT_NAME} command error: ${error && error.message ? error.message : String(error)} [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'error'
- );
- }
-
- async function isGeminiCliAvailable() {
- if (typeof state.geminiAvailable === 'boolean') return state.geminiAvailable;
- try {
- await execFileAsync('gemini', ['--help'], { timeout: 3000, maxBuffer: 512 * 1024 });
- state.geminiAvailable = true;
- } catch (_) {
- state.geminiAvailable = false;
- }
- return state.geminiAvailable;
- }
-
- async function openArtifact(filePath) {
- if (process.env.HTMLIFY_SKIP_OPEN === '1' || process.env.PI_HTML_LONG_ANSWER_SKIP_OPEN === '1') return false;
- const command = process.platform === 'darwin' ? '/usr/bin/open' : process.platform === 'linux' ? 'xdg-open' : null;
- const executable = await resolveOpenCommand(command);
- if (!executable) return false;
-
- return new Promise((resolve) => {
- let child;
- let settled = false;
- let timer;
-
- const settle = (opened) => {
- if (settled) return;
- settled = true;
- if (timer) clearTimeout(timer);
- resolve(opened);
- };
-
- try {
- child = spawn(executable, [filePath], {
- detached: true,
- stdio: 'ignore',
- });
- } catch (_) {
- settle(false);
- return;
- }
-
- child.once('error', () => settle(false));
- child.once('exit', (code) => settle(code === 0));
- child.unref();
- timer = setTimeout(() => settle(true), OPEN_FAILURE_WINDOW_MS);
- });
- }
-
- async function maybeOpenArtifact(ctx, filePath, mode) {
- const opened = await openArtifact(filePath);
- if (!opened) return false;
- notify(
- ctx,
- `${mode === 'local' ? 'Opened local HTML export' : 'Opened designed HTML export'} in your default browser. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'info'
- );
- return true;
- }
-
- function buildSourceRecord(text) {
- const title = deriveTitle(text);
- return {
- id: sha(text),
- title,
- text,
- recordedAt: Date.now(),
- stats: {
- characters: text.length,
- lines: countLines(text),
- paragraphs: countParagraphs(text),
- words: wordCount(text),
- },
- };
- }
-
- async function exportLocalHtml(ctx, source, mode) {
- const bodyHtml = renderMarkdownish(source.text);
- const filePath = await writeHtmlArtifact({
- title: source.title,
- bodyHtml,
- sourceText: source.text,
- mode: mode || 'local',
- });
- const meta = {
- path: filePath,
- mode: mode || 'local',
- title: source.title,
- sourceId: source.id,
- exportedAt: Date.now(),
- };
- await rememberExport(meta);
- await notify(
- ctx,
- `HTML export written to ${filePath}. Use /html-last rich or /htmlify rich for a more designed HTML pass. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'info'
- );
- await maybeOpenArtifact(ctx, filePath, 'local');
- return meta;
- }
-
- async function exportRichHtmlResult(ctx, source, htmlText) {
- const filePath = await writeRichHtmlArtifact({
- title: source.title,
- htmlText,
- sourceId: source.id,
- });
- const meta = {
- path: filePath,
- mode: 'llm-enhanced',
- title: source.title,
- sourceId: source.id,
- exportedAt: Date.now(),
- };
- await rememberExport(meta);
- await notify(ctx, `Designed HTML export written to ${filePath}. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`, 'info');
- await maybeOpenArtifact(ctx, filePath, 'designed');
- return meta;
- }
-
- function normalizeChoice(result, options) {
- if (typeof result === 'string') return result;
- if (typeof result === 'number') {
- if (Array.isArray(options) && options[result]) return options[result].value;
- return ['local', 'rich', 'inline', 'never'][result] || null;
- }
- if (result && typeof result === 'object') {
- return result.value || result.id || result.key || result.choice || null;
- }
- return null;
- }
-
- async function promptWithSelect(ui, summary) {
- const geminiAvailable = await isGeminiCliAvailable();
- const options = [
- { label: 'Designed HTML with Gemini CLI', value: 'rich-gemini' },
- { label: 'Designed HTML with current Pi model', value: 'rich-pi' },
- { label: 'Quick local HTML', value: 'local' },
- { label: 'Keep inline', value: 'inline' },
- { label: 'Stop asking this session', value: 'never' },
- ];
- if (!geminiAvailable) {
- options.shift();
- }
-
- const prompt = `Long answer detected: ${summary}`;
- try {
- const result = await ui.select(prompt, options);
- return normalizeChoice(result, options) || null;
- } catch (_) {
- return null;
- }
- }
-
- async function promptUserForExport(ctx, source) {
- if (!ctx || !ctx.ui || state.offerMode === 'never') return 'inline';
- const summary = [
- `${source.stats.words} words`,
- `${source.stats.paragraphs} paragraphs`,
- `${source.stats.lines} lines`,
- ].join(' · ');
-
- if (typeof ctx.ui.select === 'function') {
- const selected = await promptWithSelect(ctx.ui, summary);
- if (selected) return selected;
- }
-
- return 'inline';
- }
-
- async function queueRichExport(source, ctx, renderer) {
- if (renderer === 'gemini') {
- await notify(ctx, 'Generating designed HTML with Gemini CLI…', 'info');
- try {
- const html = await runGeminiRichExport(source);
- await exportRichHtmlResult(ctx, source, html);
- } catch (error) {
- await notify(
- ctx,
- `Gemini designed HTML failed: ${error && error.message ? error.message : String(error)}. Falling back to quick local HTML. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'warning'
- );
- await exportLocalHtml(ctx, source, 'local');
- }
- return;
- }
-
- state.pendingRichExport = {
- requestedAt: Date.now(),
- source,
- };
- await notify(ctx, 'Queued richer HTML generation as a follow-up turn.', 'info');
- if (typeof pi.sendUserMessage === 'function') {
- await pi.sendUserMessage(buildRichHtmlPrompt(source), { deliverAs: 'followUp' });
- return;
- }
- if (typeof pi.sendMessage === 'function') {
- await pi.sendMessage(buildRichHtmlPrompt(source), { deliverAs: 'followUp', triggerTurn: true });
- return;
- }
- throw new Error('No runtime message API is available for richer HTML generation.');
- }
-
- async function runGeminiRichExport(source) {
- const { stdout } = await execFileAsync(
- 'gemini',
- ['--prompt', buildRichHtmlPrompt(source), '--output-format', 'text'],
- {
- timeout: 120000,
- maxBuffer: 8 * 1024 * 1024,
- }
- );
-
- const output = String(stdout || '').trim();
- if (!output) {
- throw new Error('Gemini CLI returned no output.');
- }
-
- const html = extractHtmlDocument(output);
- if (!html) {
- throw new Error('Gemini CLI did not return HTML output.');
- }
-
- return html;
- }
-
- async function chooseCommandExportMode(ctx) {
- if (!ctx || !ctx.ui || typeof ctx.ui.select !== 'function') {
- return 'local';
- }
-
- const geminiAvailable = await isGeminiCliAvailable();
- const options = [
- { label: 'Designed HTML with Gemini CLI', value: 'rich-gemini' },
- { label: 'Designed HTML with current Pi model', value: 'rich-pi' },
- { label: 'Quick local HTML', value: 'local' },
- ];
- if (!geminiAvailable) {
- options.shift();
- }
-
- try {
- const result = await ctx.ui.select('Choose HTML render mode', options);
- return normalizeChoice(result, options) || 'local';
- } catch (_) {
- return 'local';
- }
- }
-
- async function handleChoice(choice, ctx, source) {
- if (choice === 'never') {
- await setOfferMode('never');
- await notify(ctx, 'htmlify prompting disabled for this session.', 'info');
- return;
- }
- if (choice === 'inline' || !choice) return;
- if (choice === 'local') {
- await exportLocalHtml(ctx, source, 'local');
- return;
- }
- if (choice === 'rich') {
- await queueRichExport(source, ctx, 'pi');
- return;
- }
- if (choice === 'rich-gemini') {
- await queueRichExport(source, ctx, 'gemini');
- return;
- }
- if (choice === 'rich-pi') {
- await queueRichExport(source, ctx, 'pi');
- }
- }
-
- async function maybeHandlePendingRichExport(event, ctx) {
- if (!state.pendingRichExport) return false;
- const info = extractMessageInfo(event);
- if (!info) return false;
-
- const htmlDocument = extractHtmlDocument(info.text);
- if (htmlDocument) {
- try {
- await exportRichHtmlResult(ctx, state.pendingRichExport.source, htmlDocument);
- } catch (error) {
- await notify(
- ctx,
- `Richer HTML pass was unsafe or invalid: ${error && error.message ? error.message : String(error)}. Wrote a fallback HTML export instead. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'warning'
- );
- await exportLocalHtml(ctx, state.pendingRichExport.source, 'llm-enhanced-fallback');
- }
- } else {
- await exportLocalHtml(
- ctx,
- {
- ...state.pendingRichExport.source,
- text: info.text,
- },
- 'llm-enhanced-fallback'
- );
- await notify(ctx, 'Richer HTML pass returned plain text; wrote a fallback HTML export instead.', 'warning');
- }
- state.pendingRichExport = null;
- return true;
- }
-
- async function handleAssistantMessage(event, ctx) {
- if (await maybeHandlePendingRichExport(event, ctx)) return;
-
- const info = extractMessageInfo(event);
- if (!info) return;
-
- const source = buildSourceRecord(info.text);
- const signature = source.id;
- if (signature === state.lastPromptedSignature) return;
-
- await rememberEligibleSource(source);
-
- if (!isLongAnswer(info.text, state.config)) return;
-
- state.lastPromptedSignature = signature;
- // Avoid notifying from message_end: in OMP this can replace the just-finished assistant text.
- // The answer is already captured; /html-last remains available when the user wants the export.
- }
-
- async function exportLatestFromCommand(args, ctx) {
- if (!state.lastEligible || !state.lastEligible.text) {
- try {
- const branch =
- ctx && ctx.sessionManager && typeof ctx.sessionManager.getBranch === 'function'
- ? ctx.sessionManager.getBranch()
- : [];
- hydrateLastEligibleFromBranch(branch);
- } catch (_) {
- // Ignore branch hydration failures here; warning below handles the miss.
- }
- }
-
- if (!state.lastEligible || !state.lastEligible.text) {
- notify(
- ctx,
- `No eligible assistant answer has been captured yet in this session. Ask for a long answer first, then run /html-last or /htmlify. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'warning'
- );
- return;
- }
-
- const forcedMode = resolveForcedExportMode(args);
- let mode = forcedMode || 'local';
- if (mode === 'choose') {
- mode = hasSelectableUi(ctx) ? await chooseCommandExportMode(ctx) : 'local';
- }
-
- if (mode === 'rich-gemini') {
- await queueRichExport(state.lastEligible, ctx, 'gemini');
- return;
- }
- if (mode === 'rich-pi') {
- await queueRichExport(state.lastEligible, ctx, 'pi');
- return;
- }
-
- await exportLocalHtml(ctx, state.lastEligible, 'local');
- }
-
- async function readCommentBundle(args) {
- const raw = typeof args === 'string' ? args.trim() : parseArgs(args).join(' ').trim();
- if (!raw) throw new Error('Pass a comments JSON file path or pasted JSON after /html-comments.');
- if (/^\{[\s\S]*\}$/.test(raw)) return JSON.parse(raw);
- const filePath = path.resolve(raw);
- const text = await fs.readFile(filePath, 'utf8');
- return JSON.parse(text);
- }
-
- async function importCommentsFromCommand(args, ctx) {
- if (!state.lastEligible || !state.lastEligible.text) {
- try {
- const branch =
- ctx && ctx.sessionManager && typeof ctx.sessionManager.getBranch === 'function'
- ? ctx.sessionManager.getBranch()
- : [];
- hydrateLastEligibleFromBranch(branch);
- } catch (_) {
- // Warning below handles the miss.
- }
- }
- const expectedSourceId = state.lastEligible && state.lastEligible.id;
- const bundle = validateCommentBundle(await readCommentBundle(args), expectedSourceId);
- const prompt = buildCommentsPrompt(bundle);
- await appendCustomEntry(COMMENT_ENTRY_TYPE, { ...bundle, importedAt: Date.now() });
- if (typeof pi.sendUserMessage === 'function') {
- await pi.sendUserMessage(prompt, { deliverAs: 'followUp' });
- notify(
- ctx,
- `Queued ${bundle.comments.length} HTML comment${bundle.comments.length === 1 ? '' : 's'} for the agent. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'info'
- );
- return;
- }
- if (typeof pi.sendMessage === 'function') {
- await pi.sendMessage(prompt, { deliverAs: 'followUp', triggerTurn: true });
- notify(
- ctx,
- `Queued ${bundle.comments.length} HTML comment${bundle.comments.length === 1 ? '' : 's'} for the agent. [${PRODUCT_NAME} ${EXTENSION_VERSION}]`,
- 'info'
- );
- return;
- }
- notify(ctx, prompt, 'info');
- }
-
- if (typeof pi.setLabel === 'function') {
- try {
- pi.setLabel(`${PRODUCT_NAME} ${EXTENSION_VERSION}`);
- } catch (_) {
- // Some hosts reject action methods during extension loading.
- }
- }
-
- const restoreHandler = async (_event, ctx) => {
- await restoreSessionState(ctx);
- };
-
- if (typeof pi.on === 'function') {
- pi.on('session_start', restoreHandler);
- pi.on('session_branch', restoreHandler);
- pi.on('session_tree', restoreHandler);
- pi.on('input', async (event, ctx) => {
- const parsedInput = parseHtmlCommandInput(event && event.text);
- if (!parsedInput) return undefined;
-
- try {
- if (parsedInput.command === 'version') {
- notify(ctx, `${PRODUCT_NAME} ${EXTENSION_VERSION}`, 'info');
- } else if (parsedInput.command === 'comments') {
- await importCommentsFromCommand(parsedInput.args, ctx);
- } else {
- await exportLatestFromCommand(parsedInput.args, ctx);
- }
- } catch (error) {
- notifyCommandError(ctx, error);
- }
-
- return { handled: true, action: 'handled' };
- });
- pi.on('message_end', async (event, ctx) => {
- try {
- await handleAssistantMessage(event, ctx);
- } catch (error) {
- await notify(
- ctx,
- `${PRODUCT_NAME} extension error: ${error && error.message ? error.message : String(error)}`,
- 'error'
- );
- }
- });
- }
-
- if (typeof pi.registerCommand === 'function') {
- const exportCommand = {
- description:
- 'Export the latest eligible assistant answer as HTML. Use `choose`, `gemini`, `pi`, or `local` to force a render path.',
- handler: (args, ctx) => {
- void exportLatestFromCommand(args, ctx).catch((error) => {
- notifyCommandError(ctx, error);
- });
- },
- };
-
- pi.registerCommand('html-last', {
- ...exportCommand,
- });
- pi.registerCommand('htmlify', { ...exportCommand });
- pi.registerCommand('htmlify-last', { ...exportCommand });
-
- const commentsCommand = {
- description: 'Import downloaded HTML comments JSON and send the review prompt back to the agent.',
- handler: (args, ctx) => {
- void importCommentsFromCommand(args, ctx).catch((error) => {
- notifyCommandError(ctx, error);
- });
- },
- };
-
- pi.registerCommand('html-comments', { ...commentsCommand });
- pi.registerCommand('htmlify-comments', { ...commentsCommand });
-
- const versionCommand = {
- description: 'Show the loaded htmlify extension version.',
- handler: (_args, ctx) => {
- notify(ctx, `${PRODUCT_NAME} ${EXTENSION_VERSION}`, 'info');
- },
- };
-
- pi.registerCommand('html-last-version', { ...versionCommand });
- pi.registerCommand('htmlify-version', { ...versionCommand });
- }
-};
+const createExtension = require('./src/extension');
+const { buildLocalHtmlDocument } = require('./src/document');
+const { formatInline, renderMarkdownish } = require('./src/markdown');
+const { getExportRoot, writeHtmlArtifact, writeRichHtmlArtifact } = require('./src/artifacts');
+const { validateRichHtmlDocument } = require('./src/validate');
+const { addCommentableAttributes, buildAnnotationLayer, injectAnnotationLayer } = require('./src/annotation');
+const { validateCommentBundle, buildCommentsPrompt } = require('./src/comments');
+const { extractHtmlDocument } = require('./src/extension/messages');
+const { parseArgs, parseHtmlCommandInput, resolveForcedExportMode, hasSelectableUi } = require('./src/extension/parse');
+const { resolveOpenCommand } = require('./src/extension/open');
+const { buildRichHtmlPrompt } = require('./src/extension/prompts');
+
+module.exports = createExtension;
module.exports._internals = {
buildLocalHtmlDocument,
diff --git a/src/annotation.js b/src/annotation.js
new file mode 100644
index 0000000..4924c3a
--- /dev/null
+++ b/src/annotation.js
@@ -0,0 +1,155 @@
+const { COMMENT_BUNDLE_VERSION, TRUSTED_ANNOTATION_MARKER } = require('./constants');
+
+function addCommentableAttributes(html) {
+ let index = 0;
+ return String(html || '').replace(
+ /<(p|h[1-6]|li|pre|table|aside|blockquote)\b(?![^>]*\bdata-commentable=)([^>]*)>/gi,
+ (match, tag, attrs) => {
+ index += 1;
+ return `<${tag}${attrs} data-commentable="true" data-block-id="b-${index}">`;
+ }
+ );
+}
+
+function buildAnnotationLayer(meta) {
+ const sourceId = String(meta && meta.sourceId ? meta.sourceId : '');
+ const title = String(meta && meta.title ? meta.title : 'HTML Export');
+ return `${TRUSTED_ANNOTATION_MARKER}
+
+
+
+`;
+}
+
+function injectAnnotationLayer(html, meta) {
+ const layer = buildAnnotationLayer(meta);
+ const source = String(html || '');
+ if (source.includes(TRUSTED_ANNOTATION_MARKER)) return source;
+ if (/<\/body\s*>/i.test(source)) return source.replace(/<\/body\s*>/i, `${layer}\n
+
+
+
+
htmlify export
+
${escapeHtml(title)}
+ ${meta.excerpt ? `
${escapeHtml(meta.excerpt)}
` : ''}
+
+
+
+
+
+`);
- return `${source}\n${layer}`;
-}
-
-function validateCommentBundle(bundle, expectedSourceId) {
- if (!bundle || typeof bundle !== 'object') throw new Error('Comment bundle must be a JSON object.');
- if (bundle.version !== COMMENT_BUNDLE_VERSION)
- throw new Error(`Comment bundle version must be ${COMMENT_BUNDLE_VERSION}.`);
- if (!Array.isArray(bundle.comments)) throw new Error('Comment bundle must include a comments array.');
- if (expectedSourceId && bundle.sourceId && bundle.sourceId !== expectedSourceId) {
- throw new Error('Comment bundle source does not match the last captured answer.');
- }
- return {
- version: COMMENT_BUNDLE_VERSION,
- sourceId: String(bundle.sourceId || ''),
- title: String(bundle.title || 'HTML Export').slice(0, 160),
- exportUrl: String(bundle.exportUrl || ''),
- comments: bundle.comments.map((comment, index) => {
- if (!comment || typeof comment !== 'object') throw new Error(`Comment ${index + 1} must be an object.`);
- const selectedText = String(comment.selectedText || '').trim();
- const body = String(comment.comment || '').trim();
- if (!selectedText || !body) throw new Error(`Comment ${index + 1} must include selectedText and comment.`);
- return {
- id: String(comment.id || `comment-${index + 1}`).slice(0, 80),
- blockId: String(comment.blockId || '').slice(0, 80),
- selectedText: selectedText.slice(0, 4000),
- prefix: String(comment.prefix || '').slice(0, 1000),
- suffix: String(comment.suffix || '').slice(0, 1000),
- comment: body.slice(0, 4000),
- createdAt: String(comment.createdAt || ''),
- };
- }),
- };
-}
-
-function buildCommentsPrompt(bundle) {
- const lines = [
- 'I reviewed the HTML export and left comments.',
- '',
- `Source: ${bundle.title}`,
- `Source ID: ${bundle.sourceId || 'unknown'}`,
- bundle.exportUrl ? `Export: ${bundle.exportUrl}` : '',
- '',
- ].filter((line, index) => line || index < 4);
- bundle.comments.forEach((comment, index) => {
- lines.push(
- `## Comment ${index + 1}`,
- '',
- 'Selected text:',
- `> ${comment.selectedText.replace(/\n/g, '\n> ')}`,
- '',
- 'Nearby context:',
- `> ${comment.prefix} [${comment.selectedText}] ${comment.suffix}`.trim(),
- '',
- 'Comment:',
- comment.comment,
- ''
- );
- });
- return lines.join('\n');
-}
-
-function isLongAnswer(text, config) {
- const source = String(text || '').trim();
- if (!source) return false;
- return (
- source.length >= config.minChars ||
- countLines(source) >= config.minLines ||
- countParagraphs(source) >= config.minParagraphs
- );
-}
-
-function parseArgs(rawArgs) {
- if (Array.isArray(rawArgs)) return rawArgs.map((item) => String(item));
- if (typeof rawArgs === 'string') return rawArgs.trim().split(/\s+/).filter(Boolean);
- if (rawArgs && typeof rawArgs === 'object' && Array.isArray(rawArgs.args)) {
- return rawArgs.args.map((item) => String(item));
- }
- return [];
-}
-
-function parseHtmlCommandInput(text) {
- const source = typeof text === 'string' ? text.trim() : '';
- if (/^\/(?:html-last-version|htmlify-version)\s*$/i.test(source)) {
- return { command: 'version', args: '' };
- }
-
- let match = /^\/(?:html-last|htmlify|htmlify-last)(?:\s+([\s\S]*))?$/i.exec(source);
- if (match) return { command: 'export', args: match[1] || '' };
-
- match = /^\/(?:html-comments|htmlify-comments)(?:\s+([\s\S]*))?$/i.exec(source);
- if (match) return { command: 'comments', args: match[1] || '' };
-
- return null;
-}
-
-async function resolveOpenCommand(command) {
- if (!command) return null;
- if (path.isAbsolute(command)) {
- try {
- await fs.access(command, fs.constants.X_OK);
- return command;
- } catch (_) {
- return null;
- }
- }
-
- const searchPath = String(process.env.PATH || '')
- .split(path.delimiter)
- .filter(Boolean);
- for (const directory of searchPath) {
- const candidate = path.join(directory, command);
- try {
- await fs.access(candidate, fs.constants.X_OK);
- return candidate;
- } catch (_) {
- // Keep searching PATH.
- }
- }
- return null;
-}
-
-function resolveForcedExportMode(rawArgs) {
- const parsedArgs = parseArgs(rawArgs);
- if (parsedArgs.some((arg) => /^(choose|choices|chooser|menu)$/i.test(arg))) return 'choose';
- if (parsedArgs.some((arg) => /^(gemini)$/i.test(arg))) return 'rich-gemini';
- if (parsedArgs.some((arg) => /^(pi|claude|current)$/i.test(arg))) return 'rich-pi';
- if (parsedArgs.some((arg) => /^(local|quick)$/i.test(arg))) return 'local';
- if (parsedArgs.some((arg) => /^(rich|enhanced|designed)$/i.test(arg))) return 'rich-pi';
- return null;
-}
-
-function hasSelectableUi(ctx) {
- return Boolean(ctx && ctx.ui && typeof ctx.ui.select === 'function');
-}
-
-function extractHtmlDocument(text) {
- const source = String(text || '').trim();
- if (!source) return null;
-
- const fenced = source.match(/```html\s*([\s\S]*?)```/i);
- if (fenced && fenced[1] && fenced[1].trim()) return fenced[1].trim();
-
- if (/]/i.test(source) || /
`);
+ return `${source}\n${layer}`;
+}
+
+module.exports = {
+ addCommentableAttributes,
+ buildAnnotationLayer,
+ injectAnnotationLayer,
+};
diff --git a/src/artifacts.js b/src/artifacts.js
new file mode 100644
index 0000000..27fd634
--- /dev/null
+++ b/src/artifacts.js
@@ -0,0 +1,58 @@
+const fs = require('fs/promises');
+const path = require('path');
+
+const { DEFAULT_EXPORT_ROOT } = require('./constants');
+const { sha, slugify, wordCount } = require('./text');
+const { deriveExcerpt, buildOutlineHtml, buildLocalHtmlDocument } = require('./document');
+const { addCommentableAttributes, injectAnnotationLayer } = require('./annotation');
+const { validateRichHtmlDocument } = require('./validate');
+
+async function ensureDir(dir) {
+ await fs.mkdir(dir, { recursive: true });
+}
+
+function getExportRoot() {
+ return process.env.HTMLIFY_EXPORT_ROOT || process.env.PI_HTML_LONG_ANSWER_EXPORT_ROOT || DEFAULT_EXPORT_ROOT;
+}
+
+async function writeHtmlArtifact({ title, bodyHtml, sourceText, mode }) {
+ const exportRoot = getExportRoot();
+ await ensureDir(exportRoot);
+ const now = new Date();
+ const iso = now.toISOString().replace(/[:.]/g, '-');
+ const fileName = `${iso}-${slugify(title)}-${mode}.html`;
+ const filePath = path.join(exportRoot, fileName);
+ const sourceId = sha(sourceText);
+ const annotatedBodyHtml = addCommentableAttributes(bodyHtml);
+ const html = buildLocalHtmlDocument(title, annotatedBodyHtml, {
+ exportedAt: now.toISOString(),
+ words: wordCount(sourceText),
+ characters: String(sourceText || '').length,
+ mode,
+ excerpt: deriveExcerpt(sourceText),
+ outlineHtml: buildOutlineHtml(sourceText),
+ sourceId,
+ });
+ await fs.writeFile(filePath, injectAnnotationLayer(html, { sourceId, title }), 'utf8');
+ return filePath;
+}
+
+async function writeRichHtmlArtifact({ title, htmlText, sourceId }) {
+ const html = validateRichHtmlDocument(htmlText);
+ const exportRoot = getExportRoot();
+ await ensureDir(exportRoot);
+ const now = new Date();
+ const iso = now.toISOString().replace(/[:.]/g, '-');
+ const fileName = `${iso}-${slugify(title)}-llm-enhanced.html`;
+ const filePath = path.join(exportRoot, fileName);
+ const annotatedHtml = addCommentableAttributes(html);
+ await fs.writeFile(filePath, injectAnnotationLayer(annotatedHtml, { sourceId, title }), 'utf8');
+ return filePath;
+}
+
+module.exports = {
+ ensureDir,
+ getExportRoot,
+ writeHtmlArtifact,
+ writeRichHtmlArtifact,
+};
diff --git a/src/comments.js b/src/comments.js
new file mode 100644
index 0000000..8214d91
--- /dev/null
+++ b/src/comments.js
@@ -0,0 +1,64 @@
+const { COMMENT_BUNDLE_VERSION } = require('./constants');
+
+function validateCommentBundle(bundle, expectedSourceId) {
+ if (!bundle || typeof bundle !== 'object') throw new Error('Comment bundle must be a JSON object.');
+ if (bundle.version !== COMMENT_BUNDLE_VERSION)
+ throw new Error(`Comment bundle version must be ${COMMENT_BUNDLE_VERSION}.`);
+ if (!Array.isArray(bundle.comments)) throw new Error('Comment bundle must include a comments array.');
+ if (expectedSourceId && bundle.sourceId && bundle.sourceId !== expectedSourceId) {
+ throw new Error('Comment bundle source does not match the last captured answer.');
+ }
+ return {
+ version: COMMENT_BUNDLE_VERSION,
+ sourceId: String(bundle.sourceId || ''),
+ title: String(bundle.title || 'HTML Export').slice(0, 160),
+ exportUrl: String(bundle.exportUrl || ''),
+ comments: bundle.comments.map((comment, index) => {
+ if (!comment || typeof comment !== 'object') throw new Error(`Comment ${index + 1} must be an object.`);
+ const selectedText = String(comment.selectedText || '').trim();
+ const body = String(comment.comment || '').trim();
+ if (!selectedText || !body) throw new Error(`Comment ${index + 1} must include selectedText and comment.`);
+ return {
+ id: String(comment.id || `comment-${index + 1}`).slice(0, 80),
+ blockId: String(comment.blockId || '').slice(0, 80),
+ selectedText: selectedText.slice(0, 4000),
+ prefix: String(comment.prefix || '').slice(0, 1000),
+ suffix: String(comment.suffix || '').slice(0, 1000),
+ comment: body.slice(0, 4000),
+ createdAt: String(comment.createdAt || ''),
+ };
+ }),
+ };
+}
+
+function buildCommentsPrompt(bundle) {
+ const lines = [
+ 'I reviewed the HTML export and left comments.',
+ '',
+ `Source: ${bundle.title}`,
+ `Source ID: ${bundle.sourceId || 'unknown'}`,
+ bundle.exportUrl ? `Export: ${bundle.exportUrl}` : '',
+ '',
+ ].filter((line, index) => line || index < 4);
+ bundle.comments.forEach((comment, index) => {
+ lines.push(
+ `## Comment ${index + 1}`,
+ '',
+ 'Selected text:',
+ `> ${comment.selectedText.replace(/\n/g, '\n> ')}`,
+ '',
+ 'Nearby context:',
+ `> ${comment.prefix} [${comment.selectedText}] ${comment.suffix}`.trim(),
+ '',
+ 'Comment:',
+ comment.comment,
+ ''
+ );
+ });
+ return lines.join('\n');
+}
+
+module.exports = {
+ validateCommentBundle,
+ buildCommentsPrompt,
+};
diff --git a/src/constants.js b/src/constants.js
new file mode 100644
index 0000000..9d37245
--- /dev/null
+++ b/src/constants.js
@@ -0,0 +1,55 @@
+const path = require('path');
+const os = require('os');
+
+const packageJson = require('../package.json');
+
+const EXTENSION_VERSION = packageJson.version;
+const PRODUCT_NAME = 'htmlify';
+
+const DEFAULT_EXPORT_ROOT = path.join(os.tmpdir(), 'htmlify-exports');
+// Keep legacy custom entry types so existing Pi/OMP sessions can restore pre-rename exports.
+const PREF_ENTRY_TYPE = 'html-long-answer-pref';
+const SOURCE_ENTRY_TYPE = 'html-long-answer-source';
+const EXPORT_ENTRY_TYPE = 'html-long-answer-export';
+const COMMENT_ENTRY_TYPE = 'html-long-answer-comments';
+const COMMENT_BUNDLE_VERSION = 1;
+const LONG_ANSWER_DEFAULTS = {
+ minChars: 1800,
+ minLines: 24,
+ minParagraphs: 6,
+};
+const MAX_RICH_HTML_CHARS = 512 * 1024;
+const MAX_RICH_HTML_TAGS = 2500;
+const BLOCKED_RICH_TAGS =
+ /<\s*\/?\s*(?:script|iframe|object|embed|link|base|form|input|button|textarea|select|option)\b/i;
+const BLOCKED_META_REFRESH = /<\s*meta\b[^>]*http-equiv\s*=\s*(['"]?)refresh\1/i;
+const EVENT_HANDLER_ATTR = /\s+on[a-z]+\s*=/i;
+const JAVASCRIPT_URL_ATTR = /\s(?:href|src|xlink:href|action|formaction)\s*=\s*(['"]?)\s*javascript:/i;
+const EXTERNAL_ASSET_ATTR =
+ /(?:\s(?:src|poster)\s*=\s*(['"]?)\s*(?:https?:)?\/\/|\ssrcset\s*=\s*(['"]?)[^'">]*(?:https?:)?\/\/|<\s*(?:image|use|feimage)\b[^>]*\s(?:href|xlink:href)\s*=\s*(['"]?)\s*(?:https?:)?\/\/)/i;
+const EXTERNAL_CSS_URL = /(?:url\(\s*(['"]?)\s*(?:https?:)?\/\/|@import\s+(?:url\(\s*)?(['"]?)\s*(?:https?:)?\/\/)/i;
+const OPEN_FAILURE_WINDOW_MS = 1000;
+
+const TRUSTED_ANNOTATION_MARKER = '';
+
+module.exports = {
+ EXTENSION_VERSION,
+ PRODUCT_NAME,
+ DEFAULT_EXPORT_ROOT,
+ PREF_ENTRY_TYPE,
+ SOURCE_ENTRY_TYPE,
+ EXPORT_ENTRY_TYPE,
+ COMMENT_ENTRY_TYPE,
+ COMMENT_BUNDLE_VERSION,
+ LONG_ANSWER_DEFAULTS,
+ MAX_RICH_HTML_CHARS,
+ MAX_RICH_HTML_TAGS,
+ BLOCKED_RICH_TAGS,
+ BLOCKED_META_REFRESH,
+ EVENT_HANDLER_ATTR,
+ JAVASCRIPT_URL_ATTR,
+ EXTERNAL_ASSET_ATTR,
+ EXTERNAL_CSS_URL,
+ OPEN_FAILURE_WINDOW_MS,
+ TRUSTED_ANNOTATION_MARKER,
+};
diff --git a/src/document.js b/src/document.js
new file mode 100644
index 0000000..9754751
--- /dev/null
+++ b/src/document.js
@@ -0,0 +1,236 @@
+const { escapeHtml } = require('./text');
+const { formatInline } = require('./markdown');
+
+function deriveTitle(text) {
+ const source = String(text || '').trim();
+ if (!source) return 'HTML Export';
+ const firstHeading = source.split('\n').find((line) => /^#{1,6}\s+/.test(line.trim()));
+ if (firstHeading)
+ return firstHeading
+ .replace(/^#{1,6}\s+/, '')
+ .trim()
+ .slice(0, 80);
+ const firstSentence = source.replace(/\s+/g, ' ').split(/(?<=[.!?])\s+/)[0] || source;
+ return firstSentence.slice(0, 80);
+}
+
+function deriveExcerpt(text) {
+ const lines = String(text || '').split(/\r?\n/);
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ if (/^#{1,6}\s+/.test(trimmed)) continue;
+ if (/^(?:[-*]|\d+\.)\s+/.test(trimmed)) continue;
+ return trimmed.slice(0, 240);
+ }
+ return String(text || '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, 240);
+}
+
+function buildOutlineHtml(text) {
+ const headings = [];
+ const lines = String(text || '').split(/\r?\n/);
+ for (const line of lines) {
+ const trimmed = line.trim();
+ const match = trimmed.match(/^(#{1,6})\s+(.*)$/);
+ if (match) headings.push({ level: match[1].length, label: match[2].trim() });
+ }
+ if (!headings.length) return '';
+ return `
Outline
${headings.map((item) => `- ${formatInline(item.label)}
`).join('')}
`;
+}
+
+function buildLocalHtmlDocument(title, body, meta) {
+ const exportedAt = new Date(meta.exportedAt).toLocaleString();
+ return `
+
+
+
+
+
${escapeHtml(title)}
+
+
+
+
HTML comments
+Select text in the export, then add a comment. Copy Markdown for the agent or download JSON.
+ +