claude-artifact-cli 0.2.0__tar.gz → 0.2.1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: claude-artifact-cli
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Publish, update, list and inspect Claude Artifacts from the terminal, using the Claude Code login already on your machine.
5
5
  Project-URL: Homepage, https://github.com/nikships/claude-artifact-cli
6
6
  Project-URL: Repository, https://github.com/nikships/claude-artifact-cli
@@ -81,6 +81,8 @@ claude-artifact read SLUG_OR_URL [-o FILE] metadata + published file manifest
81
81
  claude-artifact read SLUG_OR_URL --path P [--path P ... --out-dir DIR]
82
82
  a published file's exact bytes
83
83
  claude-artifact whoami check that auth works
84
+ claude-artifact update upgrade to the latest release now
85
+ claude-artifact --version
84
86
  ```
85
87
 
86
88
  The URL goes to stdout and progress goes to stderr, so `URL=$(claude-artifact publish page.html -q)` captures only the link. Add `--json` to `publish`, `status`, `list` or `read` for raw output. Exit codes: `0` success, `1` API error, `2` auth error, `3` version conflict (HTTP 409), `130` interrupted.
@@ -226,6 +228,19 @@ claude-artifact read <slug> --path index.html --path app.css --out-dir ./out #
226
228
 
227
229
  Never WebFetch or curl a `claude.ai` artifact URL: it is a login-walled app shell and returns no page content.
228
230
 
231
+ ## Updates
232
+
233
+ A uv tool or pipx install keeps itself current. At most once a day, a command checks PyPI in the background (2-second timeout, never in CI). When a newer release is out, it starts `uv tool upgrade claude-artifact-cli` (or `pipx upgrade claude-artifact-cli`) in a detached process after the command finishes and says so on stderr; `-q` keeps that quiet. The upgrade's output goes to `~/.config/claude-artifact-cli/update.log`. A plain pip install isn't changed behind your back: it prints a notice instead. A failed check or upgrade never changes the command's output or exit code.
234
+
235
+ ```bash
236
+ claude-artifact update # upgrade now, in the foreground
237
+ ```
238
+
239
+ | Variable | Effect |
240
+ |----------|--------|
241
+ | `CLAUDE_ARTIFACT_NO_AUTO_UPDATE=1` | Check and print a notice, but never upgrade. |
242
+ | `CLAUDE_ARTIFACT_NO_UPDATE_CHECK=1` | No check at all. `CI` set does the same. |
243
+
229
244
  ## Auth
230
245
 
231
246
  The token is looked up in this order:
@@ -386,7 +401,8 @@ src/
386
401
  ├── __main__.py python -m claude_artifact_cli
387
402
  ├── api.py frame API client
388
403
  ├── auth.py token lookup
389
- └── cli.py argparse entry point
404
+ ├── cli.py argparse entry point
405
+ └── update.py daily update check, background upgrade, `update`
390
406
  tests/ unit tests (offline; transport mocked)
391
407
  AGENTS.md
392
408
  LICENSE
@@ -51,6 +51,8 @@ claude-artifact read SLUG_OR_URL [-o FILE] metadata + published file manifest
51
51
  claude-artifact read SLUG_OR_URL --path P [--path P ... --out-dir DIR]
52
52
  a published file's exact bytes
53
53
  claude-artifact whoami check that auth works
54
+ claude-artifact update upgrade to the latest release now
55
+ claude-artifact --version
54
56
  ```
55
57
 
56
58
  The URL goes to stdout and progress goes to stderr, so `URL=$(claude-artifact publish page.html -q)` captures only the link. Add `--json` to `publish`, `status`, `list` or `read` for raw output. Exit codes: `0` success, `1` API error, `2` auth error, `3` version conflict (HTTP 409), `130` interrupted.
@@ -196,6 +198,19 @@ claude-artifact read <slug> --path index.html --path app.css --out-dir ./out #
196
198
 
197
199
  Never WebFetch or curl a `claude.ai` artifact URL: it is a login-walled app shell and returns no page content.
198
200
 
201
+ ## Updates
202
+
203
+ A uv tool or pipx install keeps itself current. At most once a day, a command checks PyPI in the background (2-second timeout, never in CI). When a newer release is out, it starts `uv tool upgrade claude-artifact-cli` (or `pipx upgrade claude-artifact-cli`) in a detached process after the command finishes and says so on stderr; `-q` keeps that quiet. The upgrade's output goes to `~/.config/claude-artifact-cli/update.log`. A plain pip install isn't changed behind your back: it prints a notice instead. A failed check or upgrade never changes the command's output or exit code.
204
+
205
+ ```bash
206
+ claude-artifact update # upgrade now, in the foreground
207
+ ```
208
+
209
+ | Variable | Effect |
210
+ |----------|--------|
211
+ | `CLAUDE_ARTIFACT_NO_AUTO_UPDATE=1` | Check and print a notice, but never upgrade. |
212
+ | `CLAUDE_ARTIFACT_NO_UPDATE_CHECK=1` | No check at all. `CI` set does the same. |
213
+
199
214
  ## Auth
200
215
 
201
216
  The token is looked up in this order:
@@ -356,7 +371,8 @@ src/
356
371
  ├── __main__.py python -m claude_artifact_cli
357
372
  ├── api.py frame API client
358
373
  ├── auth.py token lookup
359
- └── cli.py argparse entry point
374
+ ├── cli.py argparse entry point
375
+ └── update.py daily update check, background upgrade, `update`
360
376
  tests/ unit tests (offline; transport mocked)
361
377
  AGENTS.md
362
378
  LICENSE
@@ -0,0 +1 @@
1
+ __version__ = "0.2.1"
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
+ import contextlib
6
7
  import hashlib
7
8
  import json
8
9
  import os
@@ -11,7 +12,7 @@ import sys
11
12
  from dataclasses import dataclass, field
12
13
  from pathlib import Path
13
14
 
14
- from . import api, auth
15
+ from . import __version__, api, auth, update
15
16
 
16
17
  TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)
17
18
 
@@ -577,6 +578,7 @@ def build_parser() -> argparse.ArgumentParser:
577
578
  description="Publish Claude Artifacts from the command line, "
578
579
  "using the Claude Code login already on this machine.",
579
580
  )
581
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
580
582
  parser.add_argument("--token", help="bearer token (default: read from Keychain)")
581
583
  parser.add_argument("--base", default=api.DEFAULT_BASE, help=argparse.SUPPRESS)
582
584
  parser.add_argument("--json", action="store_true", help="raw JSON output")
@@ -666,6 +668,9 @@ def build_parser() -> argparse.ArgumentParser:
666
668
  p.add_argument("--url", help="artifact URL to compare with")
667
669
  p.set_defaults(func=cmd_status)
668
670
 
671
+ p = sub.add_parser("update", help="upgrade this CLI to the latest release now")
672
+ p.set_defaults(func=update.cmd_update)
673
+
669
674
  p = sub.add_parser("whoami", parents=[common], help="check that auth works")
670
675
  p.set_defaults(func=cmd_whoami)
671
676
 
@@ -674,6 +679,19 @@ def build_parser() -> argparse.ArgumentParser:
674
679
 
675
680
  def main(argv: list[str] | None = None) -> int:
676
681
  args = build_parser().parse_args(argv)
682
+ # Updating is best effort: no problem with it may stop or change a command.
683
+ check = None
684
+ if args.command != "update":
685
+ with contextlib.suppress(Exception):
686
+ check = update.start_check()
687
+ try:
688
+ return _run(args)
689
+ finally:
690
+ with contextlib.suppress(Exception):
691
+ update.finish_check(check, quiet=getattr(args, "quiet", False))
692
+
693
+
694
+ def _run(args) -> int:
677
695
  try:
678
696
  return args.func(args)
679
697
  except auth.AuthError as exc:
@@ -0,0 +1,243 @@
1
+ """Keep the installed CLI current.
2
+
3
+ Same shape as muse-cli's update check: look at most once a day, in a
4
+ background thread with a short timeout, never in CI, never fail or slow the
5
+ command. On top of that it upgrades: a uv tool or pipx install is upgraded in
6
+ a detached process once the command has finished. A pip install only gets the
7
+ notice, because that environment belongs to someone else.
8
+
9
+ CLAUDE_ARTIFACT_NO_AUTO_UPDATE=1 notice only, never upgrade
10
+ CLAUDE_ARTIFACT_NO_UPDATE_CHECK=1 no check at all
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import http.client
16
+ import json
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import threading
22
+ import time
23
+ import urllib.request
24
+
25
+ from . import __version__
26
+
27
+ PACKAGE = "claude-artifact-cli"
28
+ PYPI_URL = f"https://pypi.org/pypi/{PACKAGE}/json"
29
+ CHECK_INTERVAL = 24 * 60 * 60
30
+ FAIL_BACKOFF = 60 * 60
31
+ FETCH_TIMEOUT = 2
32
+ JOIN_TIMEOUT = 1.5
33
+ _ON_WINDOWS = os.name == "nt"
34
+
35
+
36
+ def _config_dir() -> str:
37
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
38
+ return os.path.join(base, PACKAGE)
39
+
40
+
41
+ STATE_FILE = os.path.join(_config_dir(), "update.json")
42
+ LOG_FILE = os.path.join(_config_dir(), "update.log")
43
+
44
+
45
+ def version_key(value) -> tuple[int, ...] | None:
46
+ """Stable x.y.z as a tuple. Pre-releases and junk compare as absent."""
47
+ text = str(value or "").strip().lstrip("v").split("+", 1)[0]
48
+ if not text or any(c.isalpha() for c in text):
49
+ return None
50
+ try:
51
+ return tuple(int(part) for part in text.split("."))
52
+ except ValueError:
53
+ return None
54
+
55
+
56
+ def is_newer(latest, current) -> bool:
57
+ new, old = version_key(latest), version_key(current)
58
+ return bool(new and old and new > old)
59
+
60
+
61
+ def install_kind() -> str:
62
+ """How this copy was installed: "uv", "pipx" or "pip".
63
+
64
+ uv and pipx leave a marker in every environment they manage, wherever it
65
+ lives (a custom UV_TOOL_DIR, %APPDATA%\\uv\\data\\tools on Windows).
66
+ """
67
+ prefix = os.path.realpath(sys.prefix)
68
+ sep = os.sep
69
+ if os.path.exists(os.path.join(prefix, "uv-receipt.toml")) or f"{sep}uv{sep}tools{sep}" in prefix:
70
+ return "uv"
71
+ if os.path.exists(os.path.join(prefix, "pipx_metadata.json")) or f"{sep}pipx{sep}" in prefix:
72
+ return "pipx"
73
+ return "pip"
74
+
75
+
76
+ def upgrade_argv() -> list[str]:
77
+ kind = install_kind()
78
+ if kind == "uv":
79
+ return ["uv", "tool", "upgrade", PACKAGE]
80
+ if kind == "pipx":
81
+ return ["pipx", "upgrade", PACKAGE]
82
+ return [sys.executable, "-m", "pip", "install", "-U", PACKAGE]
83
+
84
+
85
+ def upgrade_command() -> str:
86
+ return " ".join(upgrade_argv())
87
+
88
+
89
+ def _enabled() -> bool:
90
+ return not (os.environ.get("CLAUDE_ARTIFACT_NO_UPDATE_CHECK") or os.environ.get("CI"))
91
+
92
+
93
+ def _auto_enabled() -> bool:
94
+ return not os.environ.get("CLAUDE_ARTIFACT_NO_AUTO_UPDATE") and install_kind() != "pip"
95
+
96
+
97
+ def _number(value) -> float:
98
+ """A timestamp from the state file, or 0 if it isn't one."""
99
+ try:
100
+ return float(value or 0)
101
+ except (TypeError, ValueError):
102
+ return 0.0
103
+
104
+
105
+ def _load_state() -> dict:
106
+ try:
107
+ with open(STATE_FILE, encoding="utf-8") as fh:
108
+ data = json.load(fh)
109
+ except (OSError, ValueError):
110
+ return {}
111
+ return data if isinstance(data, dict) else {}
112
+
113
+
114
+ def _save_state(data: dict) -> None:
115
+ try:
116
+ os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
117
+ tmp = STATE_FILE + ".tmp"
118
+ with open(tmp, "w", encoding="utf-8") as fh:
119
+ json.dump(data, fh)
120
+ os.replace(tmp, STATE_FILE)
121
+ except OSError:
122
+ pass
123
+
124
+
125
+ def _fetch_latest() -> str:
126
+ req = urllib.request.Request(
127
+ PYPI_URL,
128
+ headers={"Accept": "application/json", "User-Agent": f"{PACKAGE}/{__version__}"},
129
+ )
130
+ with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as resp:
131
+ payload = json.loads(resp.read().decode("utf-8"))
132
+ return str(payload["info"]["version"])
133
+
134
+
135
+ def start_check() -> dict | None:
136
+ """Begin a check, or use the cached answer. None when checks are off."""
137
+ if not _enabled():
138
+ return None
139
+ state = _load_state()
140
+ latest = state.get("latest") if isinstance(state.get("latest"), str) else ""
141
+ holder: dict = {"latest": latest or None, "thread": None}
142
+ # A recent check, or a failed one less than an hour ago, answers for now.
143
+ if time.time() - _number(state.get("checked_at")) < CHECK_INTERVAL:
144
+ return holder
145
+ # Count the attempt before it starts: a fetch still running when the
146
+ # command exits is abandoned, and must not make the next command retry.
147
+ retry_at = time.time() - CHECK_INTERVAL + FAIL_BACKOFF
148
+ _save_state({**state, "checked_at": retry_at, "latest": latest})
149
+
150
+ def work() -> None:
151
+ try:
152
+ found = _fetch_latest()
153
+ holder["latest"] = found
154
+ # Reload: the main thread may have recorded an upgrade meanwhile.
155
+ _save_state({**_load_state(), "checked_at": time.time(), "latest": found})
156
+ except (OSError, ValueError, KeyError, TypeError, http.client.HTTPException):
157
+ pass # offline or a PyPI blip: the attempt saved above retries in an hour
158
+
159
+ thread = threading.Thread(target=work, daemon=True)
160
+ holder["thread"] = thread
161
+ thread.start()
162
+ return holder
163
+
164
+
165
+ def finish_check(holder: dict | None, quiet: bool = False) -> None:
166
+ """After the command: upgrade in the background, or print the notice."""
167
+ if not holder:
168
+ return
169
+ thread = holder.get("thread")
170
+ if thread is not None:
171
+ thread.join(timeout=JOIN_TIMEOUT)
172
+ latest = holder.get("latest")
173
+ if not is_newer(latest, __version__):
174
+ return
175
+ if _auto_enabled() and _start_upgrade(latest):
176
+ if not quiet:
177
+ print(
178
+ f"\n{PACKAGE} {__version__} → {latest}: updating in the background "
179
+ f"(log: {LOG_FILE})",
180
+ file=sys.stderr,
181
+ )
182
+ return
183
+ # No upgrade started (a pip install, opted out, the tool missing, or
184
+ # today's attempt didn't take): say so instead.
185
+ if not quiet:
186
+ print(
187
+ f"\nA new release of {PACKAGE} is available: {__version__} → {latest}\n"
188
+ f"To upgrade, run: claude-artifact update",
189
+ file=sys.stderr,
190
+ )
191
+
192
+
193
+ def _start_upgrade(latest: str) -> bool:
194
+ """Start one detached upgrade per release per day. True if one started."""
195
+ state = _load_state()
196
+ if (
197
+ state.get("upgrade_to") == latest
198
+ and time.time() - _number(state.get("upgrade_started_at")) < CHECK_INTERVAL
199
+ ):
200
+ return False
201
+ argv = upgrade_argv()
202
+ if shutil.which(argv[0]) is None or not _spawn(argv):
203
+ return False
204
+ _save_state({**_load_state(), "upgrade_to": latest, "upgrade_started_at": time.time()})
205
+ return True
206
+
207
+
208
+ def _spawn(argv: list[str]) -> bool:
209
+ """Run argv detached, after this process, logging to LOG_FILE."""
210
+ try:
211
+ os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
212
+ with open(LOG_FILE, "a", encoding="utf-8") as log:
213
+ log.write(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] {' '.join(argv)}\n")
214
+ log.flush()
215
+ detach = (
216
+ {"creationflags": subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP}
217
+ if _ON_WINDOWS
218
+ else {"start_new_session": True}
219
+ )
220
+ subprocess.Popen(
221
+ argv, stdin=subprocess.DEVNULL, stdout=log, stderr=log, close_fds=True, **detach
222
+ )
223
+ except OSError:
224
+ return False
225
+ return True
226
+
227
+
228
+ def cmd_update(args) -> int:
229
+ """Upgrade now: in the foreground, or detached on Windows."""
230
+ argv = upgrade_argv()
231
+ if argv[0] != sys.executable and shutil.which(argv[0]) is None:
232
+ print(f"{argv[0]} is not on PATH. To upgrade, run: {upgrade_command()}", file=sys.stderr)
233
+ return 1
234
+ if _ON_WINDOWS:
235
+ # Windows locks the running claude-artifact.exe, so the upgrade has to
236
+ # replace it after this process exits.
237
+ if not _spawn(argv):
238
+ print(f"couldn't start the upgrade. Run: {upgrade_command()}", file=sys.stderr)
239
+ return 1
240
+ print(f"upgrading in the background: {upgrade_command()} (log: {LOG_FILE})", file=sys.stderr)
241
+ return 0
242
+ print(f"running: {upgrade_command()}", file=sys.stderr)
243
+ return subprocess.call(argv)
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"