@phnx-labs/artifacts-cli 0.4.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +125 -10
  3. package/dist/cli.d.ts +1 -6
  4. package/dist/cli.js +93 -85
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/auth.d.ts +5 -0
  7. package/dist/commands/auth.js +112 -0
  8. package/dist/commands/auth.js.map +1 -0
  9. package/dist/commands/favorite.d.ts +9 -0
  10. package/dist/commands/favorite.js +59 -0
  11. package/dist/commands/favorite.js.map +1 -0
  12. package/dist/commands/share.d.ts +297 -14
  13. package/dist/commands/share.js +1351 -71
  14. package/dist/commands/share.js.map +1 -1
  15. package/dist/lib/browser-detect.d.ts +28 -0
  16. package/dist/lib/browser-detect.js +126 -0
  17. package/dist/lib/browser-detect.js.map +1 -0
  18. package/dist/lib/config.d.ts +14 -0
  19. package/dist/lib/config.js +8 -0
  20. package/dist/lib/config.js.map +1 -1
  21. package/dist/lib/embedded-html.d.ts +1 -1
  22. package/dist/lib/embedded-html.js +12 -0
  23. package/dist/lib/embedded-html.js.map +1 -1
  24. package/dist/lib/excerpt.d.ts +48 -0
  25. package/dist/lib/excerpt.js +167 -0
  26. package/dist/lib/excerpt.js.map +1 -0
  27. package/dist/lib/favorites.d.ts +73 -0
  28. package/dist/lib/favorites.js +180 -0
  29. package/dist/lib/favorites.js.map +1 -0
  30. package/dist/lib/format.d.ts +2 -0
  31. package/dist/lib/format.js +14 -0
  32. package/dist/lib/format.js.map +1 -0
  33. package/dist/lib/github.d.ts +14 -0
  34. package/dist/lib/github.js +36 -0
  35. package/dist/lib/github.js.map +1 -0
  36. package/dist/lib/header-actions.d.ts +44 -0
  37. package/dist/lib/header-actions.js +181 -0
  38. package/dist/lib/header-actions.js.map +1 -0
  39. package/dist/lib/identity/client.d.ts +49 -0
  40. package/dist/lib/identity/client.js +97 -0
  41. package/dist/lib/identity/client.js.map +1 -0
  42. package/dist/lib/identity/index.d.ts +60 -0
  43. package/dist/lib/identity/index.js +69 -0
  44. package/dist/lib/identity/index.js.map +1 -0
  45. package/dist/lib/link-previews.d.ts +67 -0
  46. package/dist/lib/link-previews.js +427 -0
  47. package/dist/lib/link-previews.js.map +1 -0
  48. package/dist/lib/links.d.ts +2 -0
  49. package/dist/lib/links.js +21 -2
  50. package/dist/lib/links.js.map +1 -1
  51. package/dist/lib/math.d.ts +31 -0
  52. package/dist/lib/math.js +122 -0
  53. package/dist/lib/math.js.map +1 -0
  54. package/dist/lib/metadata-menu.d.ts +15 -0
  55. package/dist/lib/metadata-menu.js +23 -0
  56. package/dist/lib/metadata-menu.js.map +1 -1
  57. package/dist/lib/open.d.ts +6 -0
  58. package/dist/lib/open.js +54 -0
  59. package/dist/lib/open.js.map +1 -0
  60. package/dist/lib/render.d.ts +3 -0
  61. package/dist/lib/render.js +158 -35
  62. package/dist/lib/render.js.map +1 -1
  63. package/dist/lib/revisions.d.ts +17 -0
  64. package/dist/lib/revisions.js +6 -1
  65. package/dist/lib/revisions.js.map +1 -1
  66. package/dist/lib/share/analytics.d.ts +13 -0
  67. package/dist/lib/share/analytics.js +46 -0
  68. package/dist/lib/share/analytics.js.map +1 -0
  69. package/dist/lib/share/backend.d.ts +105 -0
  70. package/dist/lib/share/backend.js +161 -0
  71. package/dist/lib/share/backend.js.map +1 -0
  72. package/dist/lib/share/capture.d.ts +31 -0
  73. package/dist/lib/share/capture.js +175 -0
  74. package/dist/lib/share/capture.js.map +1 -0
  75. package/dist/lib/share/config.d.ts +82 -0
  76. package/dist/lib/share/config.js +181 -0
  77. package/dist/lib/share/config.js.map +1 -0
  78. package/dist/lib/share/delete.d.ts +122 -0
  79. package/dist/lib/share/delete.js +174 -0
  80. package/dist/lib/share/delete.js.map +1 -0
  81. package/dist/lib/share/html.d.ts +22 -0
  82. package/dist/lib/share/html.js +89 -0
  83. package/dist/lib/share/html.js.map +1 -0
  84. package/dist/lib/share/http-error.d.ts +52 -0
  85. package/dist/lib/share/http-error.js +66 -0
  86. package/dist/lib/share/http-error.js.map +1 -0
  87. package/dist/lib/share/og.d.ts +25 -0
  88. package/dist/lib/share/og.js +85 -0
  89. package/dist/lib/share/og.js.map +1 -0
  90. package/dist/lib/share/provision.d.ts +99 -0
  91. package/dist/lib/share/provision.js +271 -0
  92. package/dist/lib/share/provision.js.map +1 -0
  93. package/dist/lib/share/publish.d.ts +393 -0
  94. package/dist/lib/share/publish.js +829 -0
  95. package/dist/lib/share/publish.js.map +1 -0
  96. package/dist/lib/share/qr.d.ts +36 -0
  97. package/dist/lib/share/qr.js +102 -0
  98. package/dist/lib/share/qr.js.map +1 -0
  99. package/dist/lib/share/storage-policy.d.ts +9 -0
  100. package/dist/lib/share/storage-policy.js +43 -0
  101. package/dist/lib/share/storage-policy.js.map +1 -0
  102. package/dist/lib/share/visibility.d.ts +92 -0
  103. package/dist/lib/share/visibility.js +108 -0
  104. package/dist/lib/share/visibility.js.map +1 -0
  105. package/dist/lib/share/worker-template.d.ts +29 -0
  106. package/dist/lib/share/worker-template.js +2154 -0
  107. package/dist/lib/share/worker-template.js.map +1 -0
  108. package/dist/lib/status-list.d.ts +49 -0
  109. package/dist/lib/status-list.js +153 -0
  110. package/dist/lib/status-list.js.map +1 -0
  111. package/dist/lib/validate.js +122 -8
  112. package/dist/lib/validate.js.map +1 -1
  113. package/package.json +12 -3
  114. package/dist/lib/share-provision.d.ts +0 -31
  115. package/dist/lib/share-provision.js +0 -83
  116. package/dist/lib/share-provision.js.map +0 -1
  117. package/dist/lib/share-worker.d.ts +0 -1
  118. package/dist/lib/share-worker.js +0 -66
  119. package/dist/lib/share-worker.js.map +0 -1
  120. package/dist/lib/share.d.ts +0 -39
  121. package/dist/lib/share.js +0 -159
  122. package/dist/lib/share.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,131 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - **Every table warns, files are links, and the `excerpt` fence shows file
6
+ evidence.** `artifacts check` no longer asks a plan for a table; it warns on
7
+ every table with the row and sentence-cell counts and names the visual to
8
+ draw instead (a fenced `bar-chart`, an SVG timeline, matrix, or flow, stat
9
+ tiles, panels), since only the artifact critic's recorded acceptance should
10
+ keep one. A bare `path.ext:NNN` outside a link warns. A new fenced `excerpt`
11
+ block renders a file card: the cited lines with real numbers, the highlighted
12
+ range, the path linked to the commit, and a note. Only a git-tracked file in a
13
+ checkout can be cited, and a file in another checkout only with a `repo=`
14
+ that matches its origin; the checker errors on a missing path or range, an
15
+ untracked or ignored file, a path outside any checkout, or an unnamed
16
+ sibling checkout.
17
+ - **Math.** `$…$` and `\(…\)` inline, `$$…$$` and `\[…\]` display, rendered
18
+ with KaTeX at build time (HTML plus MathML, no script). The KaTeX stylesheet
19
+ and its woff2 fonts are inlined only on pages that contain math, so the
20
+ page stays one self-contained file and every other page is unchanged.
21
+ Inline `$` follows the pandoc rule, so `$5 and $10` is prose; `\$` is a
22
+ literal dollar; math inside code is never touched. KaTeX markup is produced
23
+ after the body sanitizer from placeholders the tokenizer emits, and TeX can
24
+ never inject markup or URLs (`\href` is off).
25
+ - **Citation chips and link previews.** A numbered citation — `[[1]](url)`
26
+ or `[1](url)` — now renders as a pill naming the host with the number as a
27
+ superscript (`arxiv.org¹`) instead of a bare `[1]`. Every outbound pill also
28
+ gets a click preview: at render time the target's title, description, site
29
+ name, and social image URL are fetched once (5s timeout, 512 KB cap, six at
30
+ a time, cached for a week under the artifact history root) and embedded as
31
+ JSON outside the body, so the body revision never changes because a page
32
+ title changed upstream. Clicking a pill opens the card; its "Open" link, or a
33
+ modifier-click on the pill, goes to the page. Pills whose target could not be
34
+ fetched behave exactly as before. Only public hosts are fetched, checked on every redirect
35
+ hop, so an unattended render never pulls a loopback or private-network page
36
+ into an artifact; `ARTIFACTS_LINK_PREVIEWS_ALLOW_PRIVATE=1` lifts that for
37
+ intranet documentation. `--no-link-previews` or
38
+ `ARTIFACTS_NO_LINK_PREVIEWS=1` skips the network entirely.
39
+ - **Status lists.** Lines that open with a status emoji — `✅`, `❌`, `⚠️`,
40
+ `➡️` (and `✔`, `❎`, `✖`, `❗`, `▶`) — render as a list with a coloured state
41
+ icon per line instead of collapsing into one run-on paragraph, whether bare
42
+ or as the items of a bullet list. A line shaped `**Label** - description`
43
+ stacks the label over its description. A bullet list with any non-status
44
+ item, and status lines inside a fence, are left exactly as written.
45
+ - **Syntax highlighting in fenced code.** A fence tagged with a language
46
+ highlight.js's common bundle knows (TypeScript, JavaScript, Bash, JSON, YAML,
47
+ Python, Go, Rust, SQL, HTML/XML, CSS, Markdown, and about thirty more) now
48
+ renders with token colouring on the fixed dark code surface, in both themes,
49
+ with no CDN and no script. Fences with no language, or an unknown one, and
50
+ `diff` fences are rendered exactly as before; nothing is auto-detected.
51
+ - **Operator-configured unlimited share storage.** Setup/update can persist exact
52
+ Phoenix email/domain allowlists that bypass aggregate storage and page-count
53
+ limits while retaining body-size and publish-rate caps. Existing usage remains
54
+ accounted for; missing or unknown ledger plans keep free limits.
55
+
56
+ - **Footer "Created" stamp.** The header only ever shows the latest timestamp,
57
+ so an updated document hid when it was created. The page footer now carries
58
+ the created instant on the right — revision 1's stored time when saved
59
+ history exists, else the frontmatter `created:` stamp, and nothing when no
60
+ created instant was honestly recorded. It relativizes live like the header
61
+ stamp ("Created 2 hours ago") and prints.
62
+ - **Footer QR on shared pages.** `artifacts share` embeds a small QR of the
63
+ exact share URL — including the `?k=` viewer key on `--protected` publishes —
64
+ at the right of the page footer, so a desktop reader can hand the page to a
65
+ phone. The code is a self-contained SVG data URL on a fixed white card
66
+ (scannable in both themes, no CDN, no script), replaced rather than stacked
67
+ on re-publish, and never added to local renders. Opt out with `--no-qr` (or
68
+ the `qr: false` publish option).
69
+ - **Share and Favorite actions in the reader header.** Every rendered artifact's
70
+ header now carries a Share button (owner-only first — `--visibility me`) and a
71
+ Favorite star. Served by `artifacts render --open`, they act through the
72
+ loopback server (`POST /artifacts/share`, `POST /artifacts/favorite`) and
73
+ report the result in place; elsewhere they copy the exact CLI command
74
+ (`artifacts share <id> --visibility me`, `artifacts favorite <id>`), and on an
75
+ already-published page Share becomes a plain copy-link. Commands address the
76
+ artifact by its store id, so no local path enters reader-facing HTML.
77
+ `artifacts share` now accepts a 64-hex artifact id and uploads the latest
78
+ hash-verified snapshot for it.
79
+ - **`artifacts favorite` and `artifacts list`.** A favorites store
80
+ (`favorites.json` beside the revision history, same `ARTIFACTS_HISTORY_DIR`
81
+ override) backs `artifacts favorite <source.md|artifact-id>` (toggle, or
82
+ `--on`/`--off`) and `artifacts list [--favorites] [--json]`, which enumerates
83
+ every artifact the device knows with title, source, and saved dates.
84
+
85
+ ## 0.5.0 - 2026-09-06
86
+
87
+ - **Sharing moved in, whole (PHNX-3992).** `artifacts share` was a BYO-only
88
+ uploader; it is now the single home for artifact sharing, with the mature
89
+ managed stack relocated here from agents-cli.
90
+
91
+ - `artifacts auth login` signs this machine in to Phoenix ID with the RFC 8628
92
+ device-code flow. Signed in, `artifacts share <file>` publishes to
93
+ `share.getrush.ai/<handle>/<slug>` with no Cloudflare account, bucket, or
94
+ write token; the handle is your email local-part, first-writer-claimed, and
95
+ `--handle` picks a different one. `artifacts auth whoami` / `logout` round
96
+ it out. Signed out, the existing BYO path is unchanged.
97
+ - **Visibility.** `--visibility public|unlisted|private|me|org`, with
98
+ `--unlisted` (alias `--private`) and `--protected` as direct flags. Public is
99
+ the default: listed in your gallery with an Open Graph cover, so the link
100
+ unfurls into a preview card. `me`/`org` are login-gated by the Worker;
101
+ `unlisted` is an unauthenticated capability URL and now says so loudly before
102
+ publishing; `--protected` is real read-auth — a secret `?k=` key, `404`
103
+ without it. Hidden pages get no cover, and `--no-cover` opts out anywhere.
104
+ - **Managing what you published.** `share list` (with `--scope`/`--all` and
105
+ agent/session/label/meta filters), `share revisions`, `share edit`,
106
+ `share visibility` (in place, same URL, no revision), `share open` (opens
107
+ your page signed in as the owner, so the visibility chip is live), and
108
+ `artifacts unshare` / `share delete`, which take down the cover and retained
109
+ revisions too and verify a `404` before reporting success.
110
+ - **Provenance and safety on every publish.** Agent, session, host, repo, and
111
+ date are captured from the environment when genuinely present and never
112
+ invented; a label is derived from the HTML `<title>`, frontmatter title, or
113
+ filename. The pre-publish scan refuses emails and credential-shaped strings
114
+ in the body, the label, and every `--meta` value unless `--force` is passed.
115
+ Links expire in 30 days by default; `--expire never` opts out.
116
+ - **The Worker.** `src/lib/share/worker-template.ts` — visibility enforcement,
117
+ the gallery and its JSON listing, revision retention, server-side OG card
118
+ rendering, Phoenix bearer verification, per-account quotas — now lives here
119
+ and is deployed by `artifacts share setup` / `artifacts share update`
120
+ (`--check` answers "is a deploy due?" as JSON with no Cloudflare credentials).
121
+ It replaces the BYO-only `src/lib/share-worker.ts`, which is deleted.
122
+ - **The release deploys it.** `scripts/release.sh` runs the template check
123
+ against the just-published version after `npm publish` and redeploys the
124
+ managed Worker when the shipped template changed, so the deployed Worker
125
+ never drifts from the released source. `--deploy-worker=auto|on|off`.
126
+ - `artifacts render --publish` calls the publish path in process instead of
127
+ shelling out to `agents artifacts share`, so rendering no longer depends on
128
+ another CLI being installed.
129
+
5
130
  - Compact reader freshness uses "min/mins" and "just now" below a minute.
6
131
  Device/session copy icons appear only on hover or keyboard focus, without
7
132
  shifting the label or changing full-value copying (PHNX-3978).
package/README.md CHANGED
@@ -28,7 +28,8 @@ Write the Markdown, run one command:
28
28
  artifacts new plan --out plan.md # scaffold; provenance auto-fills
29
29
  $EDITOR plan.md # kind + title; plans also need surface
30
30
  artifacts render plan.md --open # writes, serves on 127.0.0.1, watches, opens
31
- artifacts share plan.md # publish a shareable link
31
+ artifacts auth login # once per machine, for the managed endpoint
32
+ artifacts share plan.md # publish a public link with a preview card
32
33
  ```
33
34
 
34
35
  That is the whole surface. Two more when you want them:
@@ -47,6 +48,15 @@ version, and session. Clicking the short session copies the complete UUID.
47
48
  There is no origin dropdown or visible table of missing fields. Clipboard failure
48
49
  exposes selectable text instead of claiming success. Resume remains in Details.
49
50
 
51
+ The header also carries **Share** and **Favorite** actions. Share is owner-only
52
+ first (`artifacts share <id> --visibility me`): served by `render --open` it
53
+ publishes through the loopback server and copies the resulting link; on a plain
54
+ file:// page it copies the exact command to run; on an already-published page it
55
+ degrades to copying the page's own URL instead of re-sharing. Favorite toggles the
56
+ star through the same loopback channel (persisted to the local store and reflected
57
+ after reload), or copies `artifacts favorite <id>` where no server is present.
58
+ Both address the artifact by its store id, so no local path enters the page.
59
+
50
60
  New scaffolds preserve `sessionId`, `harnessVersion`, `hostPlatform`, and
51
61
  `hostArch`, and `hostAddress` when this device has an exact-match Tailscale entry
52
62
  in the local Agents device registry. No DNS lookup or guessed address is used.
@@ -83,6 +93,12 @@ Snapshots retain previous content until explicitly removed; they are not pruned
83
93
  automatically. They are never embedded in, or uploaded alongside, the current HTML.
84
94
  The shared page carries only revision numbers/times and local open commands.
85
95
 
96
+ Favorites live beside the history in `favorites.json` under the same directory.
97
+ `artifacts favorite <source.md|artifact-id>` toggles the star (the header star on a
98
+ served page writes here too), and `artifacts list [--favorites] [--json]` enumerates
99
+ everything the local store knows — id, title, source path, first/last saved dates,
100
+ favorite marker.
101
+
86
102
  Validation/storage failures do not replace the previous output. Concurrent renders
87
103
  serialize their history writes, and repeated unchanged renders reuse the revision.
88
104
  Direct `renderMarkdown()` previews without an output path and imported raw HTML
@@ -170,16 +186,22 @@ offline brand mark; other hosts try a remote favicon and drop it if load fails.
170
186
 
171
187
  ## Commands
172
188
 
173
- Six commands. Everything else is a flag on one of them.
189
+ Ten commands (`share` spans three rows). Everything else is a flag or subcommand on one of them.
174
190
 
175
191
  | Command | Purpose |
176
192
  | --- | --- |
177
193
  | `artifacts new <plan\|report\|visual\|worksheet\|design> [--out file] [--project name] [--blank] [--stdout]` | Scaffolds an artifact and pre-fills detectable provenance. When the target lands under a committed `.agents/artifacts/` tree it pre-fills anonymized provenance instead (`human: author`, `host: fleet-worker`, no session id) — that directory is published. `project` is detected only when cwd is genuinely inside the project's own checkout (a known `~/.agents/projects/` entry or the git remote's repo name); inside the durable artifact home (`~/.agents/artifacts/`) detection stays empty rather than inventing a name — pass `--project` or fill the frontmatter, and `artifacts check` warns until you do. `--blank` leaves every field empty (an explicit `--project` still pins the project); `--stdout` prints the skeleton without writing; `design` writes a starter `DESIGN.md`; `worksheet` generates a `worksheet_id`. |
178
194
  | `artifacts check file.md` | Validates frontmatter metadata, required sections, asset paths, and embedded HTML/SVG safety. |
179
- | `artifacts render file.md [--out file] [--open] [--no-serve] [--publish]` | Renders Markdown to self-contained HTML next to the source. Local by default: `--publish` additionally publishes it to a durable **private** managed URL and prints the URL plus a terminal QR (every render used to publish, which filled the managed quota with intermediate iterations; `ARTIFACTS_NO_PUBLISH=1` still overrides `--publish`, and the `--open` watch loop re-renders on save but never publishes). `--open` serves on 127.0.0.1, watches the Markdown, and shows it in your browser; `--no-serve` keeps file:// behavior. Embeds the Markdown source for recovery. |
195
+ | `artifacts render file.md [--out file] [--open] [--no-serve] [--publish] [--no-link-previews]` | Renders Markdown to self-contained HTML next to the source. Local by default: `--publish` additionally publishes it to a durable **private** managed URL and prints the URL plus a terminal QR (every render used to publish, which filled the managed quota with intermediate iterations; `ARTIFACTS_NO_PUBLISH=1` still overrides `--publish`, and the `--open` watch loop re-renders on save but never publishes). `--open` serves on 127.0.0.1, watches the Markdown, and shows it in your browser; `--no-serve` keeps file:// behavior. Embeds the Markdown source for recovery. |
180
196
  | `artifacts answers <ws.md> [--from file.json] [--json] [--pending]` | Reads or merges a `worksheet`'s answers. No flag prints a filled/pending table; `--json` emits `id → {label, value, state}`; `--pending` filters to pending fields or worksheets; `--from` merges an exported answers file back into the `.md` (id-matched, dirty-only, atomic). A directory scans for worksheets and lists per-file pending counts. |
181
197
  | `artifacts notes <file.md\|file.html> [--from sidecar.json] [--json]` | Reads the adjacent `<basename>.notes.json` review sidecar as a table or JSON, or imports an `artifacts.notes.v1` sidecar. |
182
- | `artifacts share file.md [--slug slug]` | Renders Markdown when needed and publishes through the configured R2/Worker endpoint. The URL slug is derived from the artifact title (filename for title-less files); `--slug` overrides it. Re-sharing the same title updates the same URL. |
198
+ | `artifacts auth <login\|whoami\|logout>` | Signs this machine in to Phoenix ID, which is what lets `artifacts share` publish to the managed endpoint with no Cloudflare setup. Optional — everything else works signed out. |
199
+ | `artifacts share file.md [--slug slug] [--visibility level] [--unlisted] [--protected] [--no-cover] [--no-qr] [--expire spec] [--label text] [--meta k=v] [--json]` | Renders Markdown when needed and publishes it — managed when signed in, otherwise your own R2/Worker. Public by default, with an OG cover. The published page's footer carries a small QR of the exact share URL (including the `?k=` key on `--protected`), so a desktop reader can hand the page to a phone; `--no-qr` skips it. The URL slug is derived from the artifact title (filename for title-less files); `--slug` overrides it. Re-sharing the same title updates the same URL and keeps the replaced version as a revision. See [Sharing](#sharing). |
200
+ | `artifacts share <list\|revisions\|edit\|visibility\|open\|status\|analytics>` | Inspect and manage what you have published: the listing, retained revisions, label/metadata edits, in-place visibility changes, and an owner-authenticated browser open. |
201
+ | `artifacts share <setup\|join\|update>` | Provision your own Cloudflare endpoint, adopt an existing one, or redeploy the current Worker template to one you already have (`--check` answers "is a deploy due?" without credentials). |
202
+ | `artifacts unshare <targets...>` | Alias of `artifacts share delete`. Takes a page down along with its OG cover and retained revisions, and verifies it `404`s before reporting success. |
203
+ | `artifacts favorite <source.md\|artifact-id> [--on\|--off] [--json]` | Toggles an artifact's favorite flag in the local store (the header star on a served page writes the same store). |
204
+ | `artifacts list [--favorites] [--json]` | Lists artifacts known to this device — id, title, source, created/updated dates, favorite marker. `--favorites` filters to starred. |
183
205
 
184
206
  ### Internal commands
185
207
 
@@ -288,6 +310,8 @@ That example is a **90.4% authoring-token reduction** when the alternative is ha
288
310
 
289
311
  Write links as ordinary Markdown. Every outbound `http(s)` link in the body renders as a **link pill**: the source's brand mark (GitHub, Linear, Jira, Notion, GitLab, Bitbucket, Asana, Trello, Slack, Figma) or its favicon, followed by the link text, in a bordered, clickable container. No HTML to hand-write.
290
312
 
313
+ Body links render as pills. A numbered citation (`[[1]](url)`) shows the host with the number as a superscript. Every outbound pill gets a click preview card whose title, description, and site name are fetched once at render time (5s timeout, 512 KB cap, cached for a week in the artifact history directory) and embedded as JSON outside the body, so previews never change the body revision. The card's Open link, or a modifier-click on the pill, goes to the page; a pill whose target could not be fetched opens directly. Only public hosts are fetched, on every redirect hop, so a render never pulls a loopback or private-network page into an artifact; set `ARTIFACTS_LINK_PREVIEWS_ALLOW_PRIVATE=1` for intranet documentation. `--no-link-previews` or `ARTIFACTS_NO_LINK_PREVIEWS=1` skips the fetch for offline renders.
314
+
291
315
  ```markdown
292
316
  See [the merge guard](https://github.com/phnx-labs/agents-cli/pull/1914) for context.
293
317
  Ticket: [RUSH-2513](https://linear.app/phnx/issue/RUSH-2513/version-drift)
@@ -399,20 +423,111 @@ file.md --open` and use the browser's own print dialog.
399
423
 
400
424
  ## Sharing
401
425
 
402
- Sharing uses a Cloudflare Worker in front of R2. The local config lives at `~/.artifacts/config.json`.
426
+ A share is a single object behind a Cloudflare Worker in front of R2. There are
427
+ two ways to reach one, and you pick by signing in or not.
403
428
 
404
- Provision a new endpoint:
429
+ ### Managed — sign in, publish, done
405
430
 
406
431
  ```bash
407
- artifacts share setup --token "$CLOUDFLARE_API_TOKEN" --account "$CLOUDFLARE_ACCOUNT_ID"
432
+ artifacts auth login # device-code sign-in in your browser
433
+ artifacts share plan.md # https://share.getrush.ai/<handle>/<slug>
408
434
  ```
409
435
 
410
- Join an existing endpoint:
436
+ No Cloudflare account, bucket, or write token. The URL namespace is your handle,
437
+ the local-part of the signed-in email (`--handle <name>` publishes under a
438
+ different one; the first account to write a handle claims it). The session lives
439
+ in `~/.artifacts/phoenix-session.json`; `artifacts auth logout` clears this
440
+ machine only, and `PHOENIX_ID_BASE` points the CLI at a different backend.
441
+
442
+ ### Bring your own Cloudflare
411
443
 
412
444
  ```bash
445
+ artifacts share setup --token "$CLOUDFLARE_API_TOKEN" --account "$CLOUDFLARE_ACCOUNT_ID"
413
446
  artifacts share join https://artifacts-share.example.workers.dev --token "$WRITE_TOKEN"
414
447
  ```
415
448
 
416
- The share write token is stored in `~/.artifacts/config.json` for simplicity. For ephemeral agents, set `ARTIFACTS_SHARE_TOKEN` instead.
449
+ `setup` provisions the bucket, its lifecycle rule, and the Worker, then mints a
450
+ write token; `join` adopts an endpoint someone else provisioned. Both persist to
451
+ `~/.artifacts/config.json`. For ephemeral agents, inject `ARTIFACTS_SHARE_TOKEN`
452
+ (or `SHARE_WRITE_TOKEN`) instead of storing one. Signed in and want BYO anyway?
453
+ `ARTIFACTS_SHARE_BACKEND=byo`.
454
+
455
+ ### Visibility
456
+
457
+ A bare `artifacts share <file>` is **public**: listed in your gallery, with an
458
+ Open Graph cover so the link unfurls into a preview card in Slack, iMessage,
459
+ Twitter, and Discord. Narrow it with one flag:
460
+
461
+ | Flag | What the link is |
462
+ | --- | --- |
463
+ | *(none)* | `public` — listed, OG cover, indexable |
464
+ | `--visibility me` | owner-only; anyone else gets a login gate (needs a session) |
465
+ | `--visibility org` | everyone at your signed-in email domain (needs a session) |
466
+ | `--unlisted` (alias `--private`) | a capability URL: hidden from the gallery, `noindex`, **still world-readable by anyone holding it** |
467
+ | `--protected` | token-gated: the URL carries a secret `?k=` key and GET returns `404` without it |
468
+
469
+ `me` and `org` are refused on a BYO endpoint — there is no signed-in owner to
470
+ gate on. `--no-cover` skips the OG image; hidden visibilities never get one.
471
+ Published HTML pages embed a footer QR of the exact share URL by default — on
472
+ `--protected` pages it encodes the full `?k=` URL, since the page `404`s
473
+ without it — and `--no-qr` opts out.
474
+
475
+ Links expire in 30 days by default so an accidental publish decays; `--expire
476
+ never` for a permanent one. Before every publish the file body, the label, and
477
+ every `--meta` value are scanned for email addresses and credential-shaped
478
+ strings, and the publish is refused unless you pass `--force` — all three are
479
+ world-readable on a public page.
480
+
481
+ ### Managing what you published
482
+
483
+ ```bash
484
+ artifacts share list --all # every page, including hidden ones
485
+ artifacts share revisions q3-plan # prior versions kept on republish
486
+ artifacts share edit q3-plan --label "Q3" # retitle without republishing
487
+ artifacts share visibility q3-plan me # re-scope in place, same URL
488
+ artifacts share open q3-plan # open it signed in as the owner
489
+ artifacts unshare q3-plan # take it down, cover and revisions too
490
+ ```
491
+
492
+ Republishing an existing slug keeps the version it replaces as a retained
493
+ revision (`--no-revision` opts out). A takedown is only reported as successful
494
+ once a follow-up GET returns `404` — R2's delete is idempotent, so `{"ok":true}`
495
+ alone proves nothing.
496
+
497
+ ### The Worker
498
+
499
+ **Operator storage policy.** `share setup` and `share update` accept
500
+ `--unlimited-storage '<json>'`, with exact `emails` and `domains` arrays:
501
+
502
+ ```sh
503
+ artifacts share update --unlimited-storage '{"emails":[],"domains":["example.org"]}'
504
+ ```
417
505
 
418
- Published links are public and unlisted. They are not private. Use `--expire 30d` for sensitive artifacts and `artifacts share delete <url|key>` to remove a share.
506
+ The allowlist uses only the email returned by Phoenix authentication or retained
507
+ in a server-signed identity cookie. Entries are trimmed and case-insensitive;
508
+ domains match exactly, with no subdomain, wildcard, Gmail dot, or plus-alias
509
+ expansion. There are no built-in allowed identities. An allowed identity can
510
+ publish beyond the aggregate 200 MiB / 150-page free limits, including when its
511
+ existing usage ledger is full. Accounting continues for pages and retained
512
+ revisions. The 20 MiB request-body cap and 60 publishes per hour still apply.
513
+ Missing/unknown ledger plans remain free; a ledger plan or client identity header
514
+ cannot grant unlimited storage.
515
+
516
+ The operator's endpoint config persists this policy as `share.unlimitedStorage`.
517
+ Every subsequent update reapplies it, including template-current updates, and
518
+ uploads include it in the `SHARE_UNLIMITED_STORAGE` Worker secret binding.
519
+ When the deploying host has no local policy, uploads discover and inherit the
520
+ existing Worker binding. A failed settings read stops the upload, except when
521
+ Cloudflare confirms the Worker does not exist. Pass `'{"emails":[],"domains":[]}'` to revoke all
522
+ exceptions. `--check` reports a supplied policy change without saving or deploying
523
+ it. Missing or malformed Worker bindings grant no exceptions. This policy does
524
+ not change link expiration or the bucket's lifecycle rules.
525
+
526
+ `artifacts share setup` and `artifacts share update` deploy the Worker in
527
+ `src/lib/share/worker-template.ts`, which owns visibility enforcement, the
528
+ gallery, revision retention, OG card rendering, and Phoenix bearer verification.
529
+ `artifacts share status` reports whether your endpoint's deployed template is
530
+ current; `artifacts share update --check --update-json` answers the same
531
+ question as JSON without touching Cloudflare. The release script runs that check
532
+ after publishing and redeploys the managed Worker when the shipped template
533
+ changed, so what is deployed never drifts from what was released.
package/dist/cli.d.ts CHANGED
@@ -1,11 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { type PublishOptions } from './lib/render.js';
3
- export declare function openPath(path: string, deps?: {
4
- tryAgents?: (p: string) => boolean;
5
- osOpen?: (p: string) => void;
6
- /** Override the probe timeout so a test can assert the fallback quickly. */
7
- timeoutMs?: number;
8
- }): void;
3
+ export { openPath } from './lib/open.js';
9
4
  export declare function serveArtifact(source: string, out: string, options?: PublishOptions): Promise<{
10
5
  url: string;
11
6
  close: () => Promise<void>;
package/dist/cli.js CHANGED
@@ -2,20 +2,22 @@
2
2
  import { mkdirSync, readFileSync, watch, writeFileSync } from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { basename, dirname, join, resolve } from 'node:path';
5
- import { spawn, spawnSync } from 'node:child_process';
6
5
  import { createServer } from 'node:http';
7
6
  import { Command, Option } from 'commander';
8
7
  import chalk from 'chalk';
9
8
  import QRCode from 'qrcode';
9
+ import { openPath } from './lib/open.js';
10
10
  import { addNewCommand } from './commands/new.js';
11
11
  import { exportPdf, parsePdfLayout } from './lib/pdf.js';
12
12
  import { compileArtifact, decompileHtml, publishArtifact } from './lib/render.js';
13
13
  import { estimateArtifactTokens } from './lib/tokens.js';
14
14
  import { validateMarkdown } from './lib/validate.js';
15
- import { shareAnalytics, shareDelete, shareJoin, sharePublish, shareSetup, shareStatus } from './commands/share.js';
15
+ import { registerShareCommands, registerUnshareCommand } from './commands/share.js';
16
+ import { registerAuthCommand } from './commands/auth.js';
16
17
  import { answersCommand } from './commands/answers.js';
17
18
  import { notesCommand } from './commands/notes.js';
18
19
  import { historyCommand } from './commands/history.js';
20
+ import { favoriteCommand, listCommand } from './commands/favorite.js';
19
21
  import { notesSidecarPath, parseNotesExport } from './lib/notes.js';
20
22
  const { version } = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '../package.json'), 'utf-8'));
21
23
  const program = new Command();
@@ -46,58 +48,7 @@ function defaultOutFor(input, ext) {
46
48
  return input.replace(/\.[^.]+$/, '') + ext;
47
49
  return join(process.cwd(), '.artifacts', input.replace(/.*\//, '').replace(/\.[^.]+$/, '') + ext);
48
50
  }
49
- /**
50
- * Show a rendered artifact to the human.
51
- *
52
- * Prefers `agents browser show`, which opens the page in the browser profile the
53
- * user configured (`browser.viewer`, defaulting to `browser.profile`) rather than
54
- * whatever the OS handler happens to be. On a machine whose default handler is
55
- * not the browser the user drives, a raw `open` sends every rendered plan to the
56
- * wrong browser — one with none of their logins.
57
- *
58
- * `show`, not `navigate`: navigate binds an agent task, and the abandoned-task
59
- * reaper closes a task's tabs when that agent exits, which would close a document
60
- * the user is still reading.
61
- *
62
- * Falls back to the OS handler whenever agents-cli is absent or declines — this
63
- * package does not depend on it, and rendering must never fail because a
64
- * companion tool is missing.
65
- */
66
- /** How long to wait for `agents browser show` before falling back to the OS
67
- * handler. The daemon-absent path already bounds itself to roughly half a
68
- * second, so this budget is only ever spent in the pathological hung-daemon
69
- * case — during which the terminal is silent, which is why it is not longer. */
70
- const AGENTS_SHOW_TIMEOUT_MS = 5_000;
71
- export function openPath(path, deps = {}) {
72
- const tryAgents = deps.tryAgents ??
73
- ((p) => {
74
- const r = spawnSync('agents', ['browser', 'show', p], {
75
- stdio: 'ignore',
76
- // Bounded, because this call is synchronous and nothing downstream is:
77
- // the daemon's response socket has no read timeout, so a daemon that is
78
- // reachable but stalled would hang `artifacts render --open` forever.
79
- // A timeout kills the child and leaves `r.error` set, which the check
80
- // below already treats as failure — so the OS fallback fires for free.
81
- timeout: deps.timeoutMs ?? AGENTS_SHOW_TIMEOUT_MS,
82
- });
83
- // `status === 0` alone would in fact be sufficient: spawnSync reports both
84
- // ENOENT and a timeout kill with a NULL status, and `null === 0` is false,
85
- // so the fallback fires either way. Probed both. `!r.error` is kept as
86
- // belt-and-braces against a future case where a child both errors and
87
- // exits 0 — it is not the load-bearing part of this check.
88
- return !r.error && r.status === 0;
89
- });
90
- if (tryAgents(path))
91
- return;
92
- if (deps.osOpen) {
93
- deps.osOpen(path);
94
- return;
95
- }
96
- const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
97
- const args = process.platform === 'win32' ? ['/c', 'start', '', path] : [path];
98
- const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
99
- child.unref();
100
- }
51
+ export { openPath } from './lib/open.js';
101
52
  export async function serveArtifact(source, out, options = {}) {
102
53
  const sourcePath = resolve(source);
103
54
  const outPath = resolve(out);
@@ -140,6 +91,71 @@ export async function serveArtifact(source, out, options = {}) {
140
91
  });
141
92
  return;
142
93
  }
94
+ // The header action buttons' live channel. Two guards, both needed: a JSON
95
+ // content-type is preflighted cross-origin and this server answers no CORS
96
+ // preflight; and the Host header must be exactly the bound loopback address
97
+ // — content-type alone is defeated by DNS rebinding (a page on
98
+ // attacker.example resolving to 127.0.0.1 sends a same-origin, unpreflighted
99
+ // POST). Without both, a drive-by web page could trigger a publish or a
100
+ // favorite toggle.
101
+ const boundPort = request.socket.localPort;
102
+ const host = request.headers.host ?? '';
103
+ if (request.url?.startsWith('/artifacts/') && host !== `127.0.0.1:${boundPort}` && host !== `localhost:${boundPort}`) {
104
+ response.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' }).end('unexpected host');
105
+ return;
106
+ }
107
+ if (request.method === 'POST' && request.url === '/artifacts/favorite') {
108
+ if (!/application\/json/.test(request.headers['content-type'] ?? '')) {
109
+ response.writeHead(415, { 'content-type': 'text/plain; charset=utf-8' }).end('expected a JSON body');
110
+ return;
111
+ }
112
+ let raw = '';
113
+ request.setEncoding('utf8');
114
+ request.on('data', (chunk) => { raw += chunk; if (raw.length > 100_000)
115
+ request.destroy(); });
116
+ request.on('end', () => {
117
+ void (async () => {
118
+ try {
119
+ const { setFavorite, toggleFavorite } = await import('./lib/favorites.js');
120
+ const body = raw.trim() ? JSON.parse(raw) : {};
121
+ const title = typeof body.title === 'string' ? body.title : undefined;
122
+ const state = typeof body.favorite === 'boolean'
123
+ ? await setFavorite(sourcePath, body.favorite, { title })
124
+ : await toggleFavorite(sourcePath, { title });
125
+ // Re-render so a reload (and the on-disk file) reflects the mark.
126
+ rerender();
127
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(state));
128
+ }
129
+ catch (error) {
130
+ response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end(error instanceof Error ? error.message : String(error));
131
+ }
132
+ })();
133
+ });
134
+ return;
135
+ }
136
+ if (request.method === 'POST' && request.url === '/artifacts/share') {
137
+ if (!/application\/json/.test(request.headers['content-type'] ?? '')) {
138
+ response.writeHead(415, { 'content-type': 'text/plain; charset=utf-8' }).end('expected a JSON body');
139
+ return;
140
+ }
141
+ request.resume();
142
+ request.on('end', () => {
143
+ void (async () => {
144
+ try {
145
+ // The same act as `artifacts share <file> --visibility me`:
146
+ // owner-only, Phoenix-gated, default 30d expiry.
147
+ const { publishFile } = await import('./lib/share/publish.js');
148
+ const result = await publishFile(outPath, { visibility: 'me' });
149
+ response.writeHead(200, { 'content-type': 'application/json' })
150
+ .end(JSON.stringify({ ok: true, url: result.url, expiresAt: result.expiresAt ?? null }));
151
+ }
152
+ catch (error) {
153
+ response.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }).end(error instanceof Error ? error.message : String(error));
154
+ }
155
+ })();
156
+ });
157
+ return;
158
+ }
143
159
  if (request.method !== 'GET' || (request.url !== '/' && request.url?.split('?')[0] !== pagePath)) {
144
160
  response.writeHead(404).end('not found');
145
161
  return;
@@ -188,6 +204,20 @@ program
188
204
  .option('--json', 'emit the local history manifest')
189
205
  .option('--open <number>', 'open a saved revision on this device')
190
206
  .action((target, options) => historyCommand(target, options, openPath));
207
+ program
208
+ .command('favorite')
209
+ .description('Toggle an artifact as a favorite, or set it explicitly with --on/--off.')
210
+ .argument('<source.md|artifact-id>')
211
+ .option('--on', 'mark the artifact as a favorite')
212
+ .option('--off', 'remove the artifact from favorites')
213
+ .option('--json', 'emit machine-readable JSON')
214
+ .action((target, options) => favoriteCommand(target, options));
215
+ program
216
+ .command('list')
217
+ .description('List artifacts known to this device (id, title, source, dates, favorite).')
218
+ .option('--favorites', 'show only favorited artifacts')
219
+ .option('--json', 'emit machine-readable JSON')
220
+ .action((options) => listCommand(options));
191
221
  program
192
222
  .command('notes')
193
223
  .description('Read artifact review notes or import an artifacts.notes.v1 sidecar.')
@@ -248,6 +278,7 @@ program
248
278
  // the 150-object managed quota and the endpoint hit 413 within two weeks.
249
279
  // A rendered page is a local review surface; a share link is a deliberate act.
250
280
  .option('--publish', 'also publish a private managed URL (owner-only, permanent)')
281
+ .option('--no-link-previews', 'skip fetching title/description previews for outbound links (offline renders; ARTIFACTS_NO_LINK_PREVIEWS=1 does the same)')
251
282
  // Accepted so a lagging hook copy that still passes the old default-off flag
252
283
  // gets the same (now default) behavior instead of a Commander parse error.
253
284
  .addOption(new Option('--no-publish', 'deprecated; publishing is already off by default').hideHelp())
@@ -287,7 +318,10 @@ Notes:
287
318
  // With both --publish and the hidden --no-publish declared, Commander leaves
288
319
  // the value undefined when neither is passed — only an explicit --publish is true.
289
320
  const publish = opts.publish === true;
290
- const result = await compileArtifact(file, out, { publish });
321
+ // Commander's --no-link-previews leaves this true unless the flag is passed;
322
+ // an explicit false is the only way to skip the fetch from the CLI.
323
+ const linkPreviews = opts.linkPreviews === false ? false : undefined;
324
+ const result = await compileArtifact(file, out, { publish, linkPreviews });
291
325
  printDiagnostics(result.diagnostics);
292
326
  if (result.diagnostics.some((diagnostic) => diagnostic.level === 'error')) {
293
327
  process.exitCode = 1;
@@ -300,7 +334,7 @@ Notes:
300
334
  console.log(chalk.bold('opened locally'));
301
335
  }
302
336
  else {
303
- const served = await serveArtifact(file, out, { publish });
337
+ const served = await serveArtifact(file, out, { publish, linkPreviews });
304
338
  openPath(served.url);
305
339
  console.log(chalk.bold('served locally'));
306
340
  }
@@ -342,35 +376,9 @@ program
342
376
  printDiagnostics(published.diagnostics);
343
377
  await printArtifactResult(published, opts.out);
344
378
  });
345
- const share = program.command('share').description('Publish static artifacts with the R2/Worker share model.');
346
- share
347
- .argument('[file]', 'file to publish')
348
- .option('--slug <slug>', 'URL slug override (default: derived from the artifact title)')
349
- .option('--expire <spec>', 'expiry such as 30d, 12h, or 2026-08-01')
350
- .option('--github-user <user>', 'URL namespace')
351
- .option('--json', 'emit JSON')
352
- .action(async (file, opts) => {
353
- if (!file) {
354
- share.help();
355
- return;
356
- }
357
- await sharePublish(file, opts);
358
- });
359
- share.command('setup').description('Provision Cloudflare R2 + Worker and save ~/.artifacts/config.json.')
360
- .option('--token <token>', 'Cloudflare API token')
361
- .option('--account <id>', 'Cloudflare account id')
362
- .option('--worker <name>', 'Worker name')
363
- .option('--bucket <name>', 'R2 bucket name')
364
- .option('--domain <host>', 'custom hostname already mapped in Cloudflare')
365
- .option('--analytics-token <token>', 'Cloudflare Web Analytics token')
366
- .action(shareSetup);
367
- share.command('join').description('Use an existing share endpoint.')
368
- .argument('<baseUrl>')
369
- .option('--token <token>', 'write token')
370
- .action(shareJoin);
371
- share.command('status').description('Show configured share endpoint.').action(shareStatus);
372
- share.command('analytics').description('Show Cloudflare Web Analytics dashboard link.').action(shareAnalytics);
373
- share.command('delete').description('Delete a published artifact by URL or key.').argument('<url|key>').action(shareDelete);
379
+ registerAuthCommand(program);
380
+ registerShareCommands(program);
381
+ registerUnshareCommand(program);
374
382
  program.parseAsync().catch((error) => {
375
383
  console.error(`${chalk.red('error')} ${error instanceof Error ? error.message : String(error)}`);
376
384
  process.exitCode = 1;