claude-artifact-cli 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,324 @@
1
+ """Minimal client for the Claude Artifacts ("frame") API.
2
+
3
+ Protocol reverse-engineered from the Claude Code CLI v2.1.273 bundle.
4
+
5
+ POST {base}/api/frame/deploy/direct publish
6
+ POST {base}/api/frame/deploy/prepare content-hash preflight (large publishes)
7
+ POST {base}/api/frame/upload stage blobs the preflight asked for
8
+ GET {base}/api/frame/read/{slug} read an artifact back
9
+ GET {base}/api/frame/frames?limit=N list artifacts
10
+
11
+ base defaults to https://api.anthropic.com. Auth is the claude.ai OAuth access
12
+ token as a bearer, with the anthropic-beta: oauth-2025-04-20 opt-in.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import base64
18
+ import hashlib
19
+ import json
20
+ import mimetypes
21
+ import re
22
+ import urllib.error
23
+ import urllib.parse
24
+ import urllib.request
25
+ from dataclasses import dataclass
26
+ from typing import Any
27
+
28
+ DEFAULT_BASE = "https://api.anthropic.com"
29
+ ARTIFACT_URL = "https://claude.ai/code/artifact/{slug}"
30
+ OAUTH_BETA = "oauth-2025-04-20"
31
+ CLIENT_VERSION = "2.1.273"
32
+
33
+ SLUG_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
34
+
35
+ # Content types the server takes as a raw UTF-8 string; everything else is
36
+ # base64-encoded on the wire. Mirrors the CLI's own set exactly.
37
+ TEXT_TYPES = frozenset(
38
+ {
39
+ "text/html",
40
+ "text/css",
41
+ "text/plain",
42
+ "text/markdown",
43
+ "text/csv",
44
+ "text/javascript",
45
+ "application/javascript",
46
+ "application/json",
47
+ "application/manifest+json",
48
+ "application/xml",
49
+ "text/xml",
50
+ "image/svg+xml",
51
+ }
52
+ )
53
+
54
+ # Inline bodies above this get split into prepare -> upload -> deploy.
55
+ INLINE_BUDGET = 15 * 1024 * 1024
56
+ UPLOAD_BATCH = 15 * 1024 * 1024
57
+
58
+
59
+ class ApiError(RuntimeError):
60
+ def __init__(self, message: str, status: int | None = None, body: Any = None):
61
+ super().__init__(message)
62
+ self.status = status
63
+ self.body = body
64
+
65
+
66
+ @dataclass
67
+ class Asset:
68
+ """One file in the publish."""
69
+
70
+ path: str
71
+ data: bytes
72
+ content_type: str
73
+
74
+ @property
75
+ def sha256(self) -> str:
76
+ return hashlib.sha256(self.data).hexdigest()
77
+
78
+ def wire(self) -> str:
79
+ if self.content_type in TEXT_TYPES:
80
+ return self.data.decode("utf-8")
81
+ return base64.b64encode(self.data).decode("ascii")
82
+
83
+ def wire_bytes(self) -> int:
84
+ """Roughly what this costs JSON-encoded, matching the CLI's accounting."""
85
+ return len(json.dumps(self.wire())) - 2
86
+
87
+
88
+ def guess_content_type(path: str) -> str:
89
+ guessed, _ = mimetypes.guess_type(path)
90
+ if guessed == "application/x-javascript":
91
+ return "text/javascript"
92
+ return guessed or "application/octet-stream"
93
+
94
+
95
+ def slug_from(value: str) -> str:
96
+ """Accept a bare slug or a full claude.ai artifact URL."""
97
+ value = value.strip()
98
+ match = re.search(r"/code/artifact/([A-Za-z0-9_-]+)", value)
99
+ if match:
100
+ return match.group(1)
101
+ if SLUG_RE.match(value):
102
+ return value
103
+ raise ApiError(f"not a valid artifact slug or URL: {value!r}")
104
+
105
+
106
+ class FrameClient:
107
+ def __init__(self, token: str, base: str = DEFAULT_BASE, timeout: int = 120):
108
+ self.token = token
109
+ self.base = base.rstrip("/")
110
+ self.timeout = timeout
111
+
112
+ # -- transport ---------------------------------------------------------
113
+
114
+ def _headers(self) -> dict[str, str]:
115
+ return {
116
+ "Authorization": f"Bearer {self.token}",
117
+ "anthropic-beta": OAUTH_BETA,
118
+ "Content-Type": "application/json",
119
+ "Accept": "application/json, application/vnd.ant.frame-refusal+json",
120
+ "X-Frame-CP": "go",
121
+ "X-Frame-Surface": "code",
122
+ "X-Frame-Platform": "cli",
123
+ "X-Frame-Client-Version": CLIENT_VERSION,
124
+ "User-Agent": f"claude-artifact-cli/{CLIENT_VERSION}",
125
+ }
126
+
127
+ def _request(self, method: str, path: str, body: dict | None = None) -> Any:
128
+ data = json.dumps(body).encode("utf-8") if body is not None else None
129
+ req = urllib.request.Request(
130
+ f"{self.base}{path}", data=data, headers=self._headers(), method=method
131
+ )
132
+ try:
133
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
134
+ raw = resp.read()
135
+ status = resp.status
136
+ except urllib.error.HTTPError as exc:
137
+ raw = exc.read()
138
+ status = exc.code
139
+ except urllib.error.URLError as exc:
140
+ raise ApiError(f"network error talking to {self.base}: {exc.reason}") from exc
141
+
142
+ try:
143
+ parsed = json.loads(raw) if raw else None
144
+ except json.JSONDecodeError:
145
+ parsed = raw.decode("utf-8", "replace")
146
+
147
+ if status == 401:
148
+ raise ApiError(
149
+ "401 unauthorized - the token was rejected. Note this route needs a "
150
+ "claude.ai OAuth token (from `claude /login`), not an ANTHROPIC_API_KEY.",
151
+ status,
152
+ parsed,
153
+ )
154
+ if status >= 400:
155
+ raise ApiError(_describe(status, parsed), status, parsed)
156
+ return parsed
157
+
158
+ # -- operations --------------------------------------------------------
159
+
160
+ def list_frames(self, limit: int = 200) -> list[dict]:
161
+ data = self._request("GET", f"/api/frame/frames?limit={int(limit)}")
162
+ if isinstance(data, list):
163
+ return data
164
+ for key in ("frames", "results", "data"):
165
+ if isinstance(data, dict) and isinstance(data.get(key), list):
166
+ return data[key]
167
+ raise ApiError("unexpected listing response shape", body=data)
168
+
169
+ def read(self, slug: str) -> dict:
170
+ """Artifact metadata + published file manifest.
171
+
172
+ Note: the published *bytes* are served from a separate sandboxed host
173
+ behind a short-lived asset token, so they are not fetched here. This
174
+ returns paths, sizes, sha256 and content types.
175
+ """
176
+ quoted = urllib.parse.quote(slug)
177
+ boot = self._request("GET", f"/api/frame/{quoted}?via=model_read")
178
+ try:
179
+ boot["_access"] = self._request("GET", f"/api/frame/read/{quoted}")
180
+ except ApiError:
181
+ pass
182
+ return boot
183
+
184
+ def publish(
185
+ self,
186
+ page: Asset,
187
+ extra: list[Asset] | None = None,
188
+ removals: list[str] | None = None,
189
+ slug: str | None = None,
190
+ meta: dict | None = None,
191
+ mode: str | None = None,
192
+ base_version=None,
193
+ force: bool = False,
194
+ on_progress=lambda msg: None,
195
+ ) -> dict:
196
+ assets = [page] + list(extra or [])
197
+ manifest: dict[str, Any] = {}
198
+
199
+ total = sum(a.wire_bytes() for a in assets)
200
+ staged: list[Asset] = []
201
+
202
+ if total > INLINE_BUDGET:
203
+ on_progress(
204
+ f"body is {total // 1024 // 1024} MB - using prepare/upload flow"
205
+ )
206
+ slug, staged = self._stage(assets, slug, on_progress)
207
+
208
+ staged_paths = {a.path for a in staged}
209
+ for asset in assets:
210
+ if asset.path in staged_paths:
211
+ manifest[asset.path] = {
212
+ "sha256": asset.sha256,
213
+ "contentType": asset.content_type,
214
+ }
215
+ else:
216
+ manifest[asset.path] = {
217
+ "content": asset.wire(),
218
+ "contentType": asset.content_type,
219
+ }
220
+ for path in removals or []:
221
+ manifest[path] = None
222
+
223
+ body: dict[str, Any] = dict(meta or {})
224
+ body["manifest"] = manifest
225
+ # "replace" publishes the manifest as the whole artifact, so omitting a
226
+ # file already drops it. Explicit null removals are only legal in "patch".
227
+ if mode is None:
228
+ mode = "patch" if (slug and (removals or base_version is not None)) else "replace"
229
+ if removals and mode != "patch":
230
+ raise ApiError(
231
+ 'removing a file needs --mode patch (in "replace" mode, just omit the file)'
232
+ )
233
+ if removals and not slug:
234
+ raise ApiError("removing a file needs --slug/--url (there is nothing to patch)")
235
+ if mode == "patch" and base_version is None:
236
+ # The server overlays a patch onto a known version, so look up the
237
+ # current one rather than making the caller pass it.
238
+ on_progress("looking up current version for the patch")
239
+ current = self.read(slug).get("ver")
240
+ if current is None:
241
+ raise ApiError("couldn't determine the current version to patch onto")
242
+ base_version = current
243
+ body["mode"] = mode
244
+ if slug:
245
+ body["slug"] = slug
246
+ if base_version is not None:
247
+ body["baseVersion"] = base_version
248
+ if force:
249
+ body["force"] = True
250
+
251
+ on_progress("POST /api/frame/deploy/direct")
252
+ result = self._request("POST", "/api/frame/deploy/direct", body)
253
+ if not isinstance(result, dict) or "slug" not in result:
254
+ raise ApiError("deploy returned an incomplete response", body=result)
255
+ return result
256
+
257
+ # -- large-publish path ------------------------------------------------
258
+
259
+ def _stage(self, assets: list[Asset], slug: str | None, on_progress):
260
+ """prepare -> upload. Returns (slug, assets staged by hash)."""
261
+ by_sha = {a.sha256: a for a in assets}
262
+ prep_body: dict[str, Any] = {"shas": list(by_sha)}
263
+ if slug:
264
+ prep_body["slug"] = slug
265
+
266
+ on_progress("POST /api/frame/deploy/prepare")
267
+ prep = self._request("POST", "/api/frame/deploy/prepare", prep_body)
268
+ if not isinstance(prep, dict) or not isinstance(prep.get("slug"), str):
269
+ raise ApiError("malformed preflight answer", body=prep)
270
+
271
+ reserved = prep["slug"]
272
+ if slug and reserved != slug:
273
+ raise ApiError("preflight answered for a different artifact - not publishing")
274
+
275
+ missing = [s for s in prep.get("missing") or [] if s in by_sha]
276
+ if not missing:
277
+ return reserved, []
278
+
279
+ batch: list[Asset] = []
280
+ size = 0
281
+ staged: list[Asset] = []
282
+ for sha in missing:
283
+ asset = by_sha[sha]
284
+ cost = asset.wire_bytes()
285
+ if batch and size + cost > UPLOAD_BATCH:
286
+ self._upload(reserved, batch, on_progress)
287
+ staged.extend(batch)
288
+ batch, size = [], 0
289
+ batch.append(asset)
290
+ size += cost
291
+ if batch:
292
+ self._upload(reserved, batch, on_progress)
293
+ staged.extend(batch)
294
+ return reserved, staged
295
+
296
+ def _upload(self, slug: str, batch: list[Asset], on_progress) -> None:
297
+ on_progress(f"POST /api/frame/upload ({len(batch)} file(s))")
298
+ self._request(
299
+ "POST",
300
+ "/api/frame/upload",
301
+ {
302
+ "slug": slug,
303
+ "files": [
304
+ {"path": a.path, "content": a.wire(), "contentType": a.content_type}
305
+ for a in batch
306
+ ],
307
+ },
308
+ )
309
+
310
+
311
+ def _describe(status: int, body: Any) -> str:
312
+ detail = ""
313
+ if isinstance(body, dict):
314
+ detail = body.get("message") or body.get("error") or json.dumps(body)[:400]
315
+ elif isinstance(body, str):
316
+ detail = body[:400]
317
+ hint = {
318
+ 403: " (the account may not have Artifacts enabled)",
319
+ 404: " (no such artifact, or it isn't yours to update)",
320
+ 409: " (a newer version exists - re-read it, merge, and retry, or pass --force)",
321
+ 413: " (payload too large)",
322
+ 429: " (rate limited or daily publish cap reached)",
323
+ }.get(status, "")
324
+ return f"HTTP {status}{hint}: {detail}".rstrip(": ")
@@ -0,0 +1,129 @@
1
+ """Locate the claude.ai OAuth access token this machine already holds.
2
+
3
+ Claude Code stores its login in the macOS login Keychain under the generic
4
+ password service "Claude Code-credentials" (and, on other platforms or as a
5
+ fallback, in ~/.claude/.credentials.json). The stored value is a JSON blob
6
+ holding the OAuth access token, refresh token and expiry.
7
+
8
+ The exact key path has moved between Claude Code releases, so rather than
9
+ hardcode one we walk the JSON and take the most plausible access token,
10
+ preferring anything nested under a claude.ai-looking key.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ KEYCHAIN_SERVICE = "Claude Code-credentials"
23
+ CREDENTIALS_FILE = Path.home() / ".claude" / ".credentials.json"
24
+
25
+ # Checked in order; first one set wins.
26
+ ENV_VARS = ("CLAUDE_ARTIFACT_TOKEN", "CLAUDE_CODE_ARTIFACTS_API_TOKEN")
27
+
28
+ _TOKEN_KEYS = ("accesstoken", "access_token")
29
+ _PREFERRED_PARENTS = ("claudeaioauth", "claude_ai_oauth", "oauth")
30
+ _EXPIRY_KEYS = ("expiresat", "expires_at")
31
+
32
+
33
+ class AuthError(RuntimeError):
34
+ pass
35
+
36
+
37
+ def _walk(node: Any, parent: str = "") -> list[tuple[str, str, Any]]:
38
+ """Yield (parent_key, token, containing_dict) for every token-looking leaf."""
39
+ found: list[tuple[str, str, Any]] = []
40
+ if isinstance(node, dict):
41
+ for key, value in node.items():
42
+ if key.lower().replace("-", "_").replace("_", "") in (
43
+ k.replace("_", "") for k in _TOKEN_KEYS
44
+ ) and isinstance(value, str) and value:
45
+ found.append((parent, value, node))
46
+ else:
47
+ found.extend(_walk(value, key))
48
+ elif isinstance(node, list):
49
+ for item in node:
50
+ found.extend(_walk(item, parent))
51
+ return found
52
+
53
+
54
+ def _pick(blob: str) -> tuple[str, int | None]:
55
+ try:
56
+ data = json.loads(blob)
57
+ except json.JSONDecodeError as exc:
58
+ raise AuthError(f"stored credentials are not valid JSON: {exc}") from exc
59
+
60
+ candidates = _walk(data)
61
+ if not candidates:
62
+ raise AuthError(
63
+ "no access token found in the stored credentials. "
64
+ "Run `claude /login`, or pass --token explicitly."
65
+ )
66
+
67
+ def rank(item: tuple[str, str, Any]) -> int:
68
+ parent = item[0].lower().replace("_", "")
69
+ return 0 if parent in [p.replace("_", "") for p in _PREFERRED_PARENTS] else 1
70
+
71
+ candidates.sort(key=rank)
72
+ _, token, container = candidates[0]
73
+
74
+ expires_at = None
75
+ for key, value in container.items():
76
+ if key.lower().replace("_", "") in [e.replace("_", "") for e in _EXPIRY_KEYS]:
77
+ if isinstance(value, (int, float)):
78
+ expires_at = int(value)
79
+ break
80
+ return token, expires_at
81
+
82
+
83
+ def _from_keychain() -> str | None:
84
+ try:
85
+ result = subprocess.run(
86
+ ["security", "find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
87
+ capture_output=True,
88
+ text=True,
89
+ timeout=15,
90
+ check=False,
91
+ )
92
+ except (FileNotFoundError, subprocess.TimeoutExpired):
93
+ return None
94
+ if result.returncode != 0:
95
+ return None
96
+ return result.stdout.strip() or None
97
+
98
+
99
+ def _from_file() -> str | None:
100
+ if not CREDENTIALS_FILE.is_file():
101
+ return None
102
+ return CREDENTIALS_FILE.read_text(encoding="utf-8")
103
+
104
+
105
+ def get_token(explicit: str | None = None) -> str:
106
+ """Return a bearer token, or raise AuthError explaining what to do."""
107
+ if explicit:
108
+ return explicit
109
+ for var in ENV_VARS:
110
+ value = os.environ.get(var)
111
+ if value:
112
+ return value
113
+
114
+ blob = _from_keychain() or _from_file()
115
+ if blob is None:
116
+ raise AuthError(
117
+ "couldn't find a Claude Code login on this machine.\n"
118
+ f" Looked in: macOS Keychain service {KEYCHAIN_SERVICE!r}, {CREDENTIALS_FILE}\n"
119
+ " Fix: run `claude /login`, or pass --token / set "
120
+ f"{ENV_VARS[0]}."
121
+ )
122
+
123
+ token, expires_at = _pick(blob)
124
+ if expires_at and expires_at / 1000 < time.time():
125
+ raise AuthError(
126
+ "the stored Claude Code access token has expired. "
127
+ "Start Claude Code once (it refreshes on launch), or run `claude /login`."
128
+ )
129
+ return token
@@ -0,0 +1,255 @@
1
+ """Command-line front end."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from . import api, auth
12
+
13
+ TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)
14
+
15
+
16
+ def _eprint(msg: str) -> None:
17
+ print(msg, file=sys.stderr)
18
+
19
+
20
+ def _client(args) -> api.FrameClient:
21
+ return api.FrameClient(auth.get_token(args.token), base=args.base)
22
+
23
+
24
+ def _title_from_html(text: str, fallback: str) -> str:
25
+ match = TITLE_RE.search(text)
26
+ if match:
27
+ title = re.sub(r"\s+", " ", match.group(1)).strip()
28
+ if title:
29
+ return title[:200]
30
+ return fallback
31
+
32
+
33
+ def _load_assets(specs: list[str], root: str | None) -> list[api.Asset]:
34
+ """Each spec is 'published/path=source/path' or just 'path' for both."""
35
+ base = Path(root) if root else Path.cwd()
36
+ assets = []
37
+ for spec in specs:
38
+ published, _, source = spec.partition("=")
39
+ src = Path(source or published)
40
+ if not src.is_absolute():
41
+ src = base / src
42
+ if not src.is_file():
43
+ raise SystemExit(f"error: no such file: {src}")
44
+ assets.append(
45
+ api.Asset(
46
+ path=published.lstrip("/"),
47
+ data=src.read_bytes(),
48
+ content_type=api.guess_content_type(published),
49
+ )
50
+ )
51
+ return assets
52
+
53
+
54
+ # -- commands --------------------------------------------------------------
55
+
56
+
57
+ def cmd_publish(args) -> int:
58
+ page_path = Path(args.file)
59
+ if not page_path.is_file():
60
+ raise SystemExit(f"error: no such file: {page_path}")
61
+
62
+ raw = page_path.read_bytes()
63
+ content_type = api.guess_content_type(page_path.name)
64
+ if content_type not in ("text/html", "text/markdown"):
65
+ content_type = "text/html"
66
+
67
+ page = api.Asset(path="index.html", data=raw, content_type=content_type)
68
+ extra = _load_assets(args.file_spec or [], args.root)
69
+
70
+ slug = api.slug_from(args.url or args.slug) if (args.url or args.slug) else None
71
+
72
+ meta = {}
73
+ meta["title"] = args.title or _title_from_html(
74
+ raw.decode("utf-8", "replace"), page_path.stem
75
+ )
76
+ if args.favicon:
77
+ meta["favicon"] = args.favicon
78
+ elif not slug:
79
+ meta["favicon"] = "📄" # required on a first publish
80
+ for key, value in (
81
+ ("description", args.description),
82
+ ("icon", args.icon),
83
+ ("label", args.label),
84
+ ):
85
+ if value:
86
+ meta[key] = value
87
+
88
+ progress = (lambda m: None) if args.quiet else (lambda m: _eprint(f" {m}"))
89
+
90
+ client = _client(args)
91
+ result = client.publish(
92
+ page=page,
93
+ extra=extra,
94
+ removals=args.remove or [],
95
+ slug=slug,
96
+ meta=meta,
97
+ mode=args.mode,
98
+ base_version=args.base_version,
99
+ force=args.force,
100
+ on_progress=progress,
101
+ )
102
+
103
+ if args.json:
104
+ print(json.dumps(result, indent=2))
105
+ else:
106
+ print(api.ARTIFACT_URL.format(slug=result["slug"]))
107
+ if result.get("version") is not None and not args.quiet:
108
+ _eprint(f" version {result['version']}")
109
+ return 0
110
+
111
+
112
+ def cmd_list(args) -> int:
113
+ frames = _client(args).list_frames(limit=args.limit)
114
+
115
+ if args.scope != "all":
116
+ want = "mine" if args.scope == "mine" else "shared"
117
+ frames = [f for f in frames if (f.get("rel") or "mine") == want]
118
+ frames = [f for f in frames if not f.get("softDeleted")]
119
+
120
+ if args.json:
121
+ print(json.dumps(frames, indent=2))
122
+ return 0
123
+
124
+ if not frames:
125
+ print("No artifacts.")
126
+ return 0
127
+
128
+ for f in frames:
129
+ slug = f.get("slug", "?")
130
+ title = (f.get("title") or "(untitled)").strip()
131
+ updated = (f.get("updatedAt") or "")[:10]
132
+ print(f"{slug:<38} {updated:<11} {title}")
133
+ return 0
134
+
135
+
136
+ def cmd_read(args) -> int:
137
+ slug = api.slug_from(args.slug)
138
+ data = _client(args).read(slug)
139
+
140
+ if args.json:
141
+ print(json.dumps(data, indent=2))
142
+ return 0
143
+
144
+ print(f"{data.get('title') or '(untitled)'} {data.get('favicon') or ''}".strip())
145
+ print(f" url {api.ARTIFACT_URL.format(slug=slug)}")
146
+ print(f" version {data.get('ver')}")
147
+ print(f" updated {data.get('updated_at')}")
148
+ access = data.get("_access") or {}
149
+ role = (data.get("perm") or {}).get("role")
150
+ print(f" role {role or '?'}"
151
+ f"{' (public)' if access.get('public') else ''}")
152
+
153
+ files = data.get("files") or []
154
+ if files:
155
+ print(f" files {len(files)}")
156
+ for f in sorted(files, key=lambda x: x.get("path", "")):
157
+ size = f.get("size")
158
+ size_s = f"{size:>9,}" if isinstance(size, int) else " " * 9
159
+ print(f" {size_s} {f.get('contentType',''):<26} {f.get('path','')}")
160
+
161
+ if args.out:
162
+ Path(args.out).write_text(json.dumps(data, indent=2), encoding="utf-8")
163
+ _eprint(f"wrote metadata to {args.out}")
164
+ return 0
165
+
166
+
167
+ def cmd_whoami(args) -> int:
168
+ """Confirm the token works, without printing it."""
169
+ token = auth.get_token(args.token)
170
+ _eprint(f"token found ({len(token)} chars, ends …{token[-6:]})")
171
+ frames = api.FrameClient(token, base=args.base).list_frames(limit=1)
172
+ _eprint(f"authenticated against {args.base} - listing returned {len(frames)} row(s)")
173
+ return 0
174
+
175
+
176
+ # -- parser ----------------------------------------------------------------
177
+
178
+
179
+ def build_parser() -> argparse.ArgumentParser:
180
+ parser = argparse.ArgumentParser(
181
+ prog="claude-artifact",
182
+ description="Publish Claude Artifacts from the command line, "
183
+ "using the Claude Code login already on this machine.",
184
+ )
185
+ parser.add_argument("--token", help="bearer token (default: read from Keychain)")
186
+ parser.add_argument("--base", default=api.DEFAULT_BASE, help=argparse.SUPPRESS)
187
+ parser.add_argument("--json", action="store_true", help="raw JSON output")
188
+ sub = parser.add_subparsers(dest="command", required=True)
189
+
190
+ # Accept the global flags after the subcommand too. SUPPRESS keeps the
191
+ # subparser from clobbering a value given before it.
192
+ common = argparse.ArgumentParser(add_help=False)
193
+ common.add_argument("--token", default=argparse.SUPPRESS, help=argparse.SUPPRESS)
194
+ common.add_argument(
195
+ "--json", action="store_true", default=argparse.SUPPRESS, help="raw JSON output"
196
+ )
197
+
198
+ p = sub.add_parser("publish", parents=[common], help="publish or update an artifact")
199
+ p.add_argument("file", help="the HTML page to publish")
200
+ p.add_argument("--slug", help="update this existing artifact")
201
+ p.add_argument("--url", help="update the artifact at this claude.ai URL")
202
+ p.add_argument("--title", help="defaults to the page's <title>")
203
+ p.add_argument("--favicon", help="emoji for the browser tab")
204
+ p.add_argument("--description", help="one-sentence subtitle")
205
+ p.add_argument("--icon", help="one generic word, e.g. chart")
206
+ p.add_argument("--label", help="short name for this publish")
207
+ p.add_argument(
208
+ "--file",
209
+ dest="file_spec",
210
+ action="append",
211
+ metavar="PUB[=SRC]",
212
+ help="supporting file; repeatable",
213
+ )
214
+ p.add_argument("--root", help="base directory for --file sources")
215
+ p.add_argument(
216
+ "--remove", action="append", metavar="PATH", help="delete a published file"
217
+ )
218
+ p.add_argument("--mode", choices=["replace", "patch"], help="default: replace")
219
+ p.add_argument("--base-version", help="expected current version (default: look it up)")
220
+ p.add_argument("--force", action="store_true", help="overwrite a newer version")
221
+ p.add_argument("-q", "--quiet", action="store_true")
222
+ p.set_defaults(func=cmd_publish)
223
+
224
+ p = sub.add_parser("list", parents=[common], help="list your artifacts")
225
+ p.add_argument("--limit", type=int, default=200)
226
+ p.add_argument("--scope", choices=["mine", "shared", "all"], default="mine")
227
+ p.set_defaults(func=cmd_list)
228
+
229
+ p = sub.add_parser("read", parents=[common], help="read a published artifact back")
230
+ p.add_argument("slug", help="slug or full artifact URL")
231
+ p.add_argument("-o", "--out", help="write the metadata JSON to this file")
232
+ p.set_defaults(func=cmd_read)
233
+
234
+ p = sub.add_parser("whoami", parents=[common], help="check that auth works")
235
+ p.set_defaults(func=cmd_whoami)
236
+
237
+ return parser
238
+
239
+
240
+ def main(argv: list[str] | None = None) -> int:
241
+ args = build_parser().parse_args(argv)
242
+ try:
243
+ return args.func(args)
244
+ except auth.AuthError as exc:
245
+ _eprint(f"auth error: {exc}")
246
+ return 2
247
+ except api.ApiError as exc:
248
+ _eprint(f"error: {exc}")
249
+ return 1
250
+ except KeyboardInterrupt:
251
+ return 130
252
+
253
+
254
+ if __name__ == "__main__":
255
+ sys.exit(main())
@@ -0,0 +1,273 @@
1
+ Metadata-Version: 2.5
2
+ Name: claude-artifact-cli
3
+ Version: 0.1.0
4
+ Summary: Publish, update, list and inspect Claude Artifacts from the terminal, using the Claude Code login already on your machine.
5
+ Project-URL: Homepage, https://github.com/nikships/claude-artifact-cli
6
+ Project-URL: Repository, https://github.com/nikships/claude-artifact-cli
7
+ Project-URL: Issues, https://github.com/nikships/claude-artifact-cli/issues
8
+ Project-URL: Releases, https://github.com/nikships/claude-artifact-cli/releases
9
+ Author-email: Nik <nik.anand.1998@gmail.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agent-skill,ai,anthropic,artifacts,automation,claude,claude-artifacts,claude-code,cli,command-line,developer-tools,html,llm,publish,terminal
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Topic :: Internet :: WWW/HTTP
26
+ Classifier: Topic :: Software Development :: Build Tools
27
+ Classifier: Topic :: Utilities
28
+ Requires-Python: >=3.10
29
+ Description-Content-Type: text/markdown
30
+
31
+ <div align="center">
32
+
33
+ <img src="https://raw.githubusercontent.com/nikships/claude-artifact-cli/main/assets/header.png" alt="claude-artifact-cli: publish Claude Artifacts from your terminal" width="100%" />
34
+
35
+ # claude-artifact-cli
36
+
37
+ Publish, update, list and inspect Claude Artifacts from the terminal, using the Claude Code login already on your machine.
38
+
39
+ [![PyPI](https://img.shields.io/pypi/v/claude-artifact-cli?style=for-the-badge)](https://pypi.org/project/claude-artifact-cli/)
40
+ [![Python](https://img.shields.io/pypi/pyversions/claude-artifact-cli?style=for-the-badge)](https://pypi.org/project/claude-artifact-cli/)
41
+ [![CI](https://img.shields.io/github/actions/workflow/status/nikships/claude-artifact-cli/publish.yml?branch=main&style=for-the-badge)](https://github.com/nikships/claude-artifact-cli/actions)
42
+ [![License](https://img.shields.io/github/license/nikships/claude-artifact-cli?style=for-the-badge)](https://github.com/nikships/claude-artifact-cli/blob/main/LICENSE)
43
+ [![Stars](https://img.shields.io/github/stars/nikships/claude-artifact-cli?style=for-the-badge)](https://github.com/nikships/claude-artifact-cli/stargazers)
44
+
45
+ </div>
46
+
47
+ ## What is this?
48
+
49
+ `claude-artifact` publishes an HTML page (plus any CSS, JS and images it uses) as a [Claude Artifact](https://claude.ai/code/artifacts) and prints the link. It talks to the same API the Claude Code `Artifact` tool uses and reuses the claude.ai login from `claude /login`. No API key, no config file, no dependencies beyond Python 3.10+.
50
+
51
+ Use it where the built-in tool can't reach: shell scripts, Makefiles, git hooks, CI jobs, subagents and other coding agents.
52
+
53
+ > [!NOTE]
54
+ > Unofficial and not affiliated with Anthropic. It uses a private, undocumented API that can change or break without notice.
55
+
56
+ ## Quick Start
57
+
58
+ ```bash
59
+ uv tool install claude-artifact-cli # or: pipx install claude-artifact-cli
60
+ claude-artifact whoami # confirms the Claude Code login works
61
+ claude-artifact publish report.html --favicon 📊
62
+ # https://claude.ai/code/artifact/1c5586a4-acec-4266-a9aa-03dfa0912b43
63
+ ```
64
+
65
+ Run it once without installing:
66
+
67
+ ```bash
68
+ uvx --from claude-artifact-cli claude-artifact publish report.html
69
+ ```
70
+
71
+ ## Commands
72
+
73
+ ```
74
+ claude-artifact publish FILE [options] publish or update an artifact
75
+ claude-artifact list [--scope mine|shared|all]
76
+ claude-artifact read SLUG_OR_URL metadata + published file manifest
77
+ claude-artifact whoami check that auth works
78
+ ```
79
+
80
+ 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 any command for raw output. Exit codes: `0` success, `1` API error, `2` auth error.
81
+
82
+ ### publish
83
+
84
+ ```bash
85
+ # new artifact; the title comes from the page's <title>
86
+ claude-artifact publish dashboard.html --favicon 📊 --description "Q3 numbers"
87
+
88
+ # update in place, same URL
89
+ claude-artifact publish dashboard.html --url https://claude.ai/code/artifact/<slug>
90
+ claude-artifact publish dashboard.html --slug <slug>
91
+
92
+ # multi-file page
93
+ claude-artifact publish index.html \
94
+ --root ./site \
95
+ --file app.css --file app.js --file img/logo.png
96
+
97
+ # rename a file's published path, and drop one
98
+ claude-artifact publish index.html --slug <slug> \
99
+ --file styles.css=src/main.css \
100
+ --remove old.js
101
+ ```
102
+
103
+ | Option | Meaning |
104
+ |--------|---------|
105
+ | `--slug`, `--url` | Update this artifact. Without one, every publish creates a new artifact. |
106
+ | `--title` | Defaults to the page's `<title>`. |
107
+ | `--favicon` | Emoji for the tab. Set it on a first publish. |
108
+ | `--description` | One-sentence subtitle. |
109
+ | `--icon`, `--label` | Generic icon word; short name for this publish. |
110
+ | `--file PUB[=SRC]` | Supporting file. Without `=`, published and source paths match. Repeatable. |
111
+ | `--root` | Base directory for `--file` sources. Published paths are unchanged. |
112
+ | `--remove PATH` | Delete a published file. Implies `--mode patch`. |
113
+ | `--mode replace\|patch` | `replace` (default) makes the manifest the whole artifact, so omitting a file removes it. `patch` overlays onto the current version. |
114
+ | `--base-version` | Expected current version for patch mode. Looked up automatically. |
115
+ | `--force` | Overwrite a newer version someone else published. |
116
+ | `-q`, `--quiet` | Print only the URL. |
117
+
118
+ ### list and read
119
+
120
+ ```bash
121
+ claude-artifact list --scope shared
122
+ claude-artifact read <slug-or-url> # title, version, role, file manifest
123
+ claude-artifact read <slug> -o meta.json # also save the metadata JSON
124
+ ```
125
+
126
+ `read` returns metadata, paths, sizes, content types and sha256 hashes, not the page bytes.
127
+
128
+ ## Auth
129
+
130
+ The token is looked up in this order:
131
+
132
+ 1. `--token`
133
+ 2. `$CLAUDE_ARTIFACT_TOKEN`, then `$CLAUDE_CODE_ARTIFACTS_API_TOKEN`
134
+ 3. macOS Keychain, generic password service `Claude Code-credentials`
135
+ 4. `~/.claude/.credentials.json`
136
+
137
+ It must be the **claude.ai OAuth token** from `claude /login`. The artifacts routes reject an `ANTHROPIC_API_KEY` with a 401. The token is short-lived; Claude Code refreshes it on launch and this tool re-reads it on every run, so there is nothing to rotate. `whoami` shows only the token's length and last few characters.
138
+
139
+ ## Agent skill
140
+
141
+ [`skills/claude-artifact-cli/SKILL.md`](skills/claude-artifact-cli/SKILL.md) teaches Claude Code, Droid, Codex and other agents when and how to use the CLI. Install it for Claude Code:
142
+
143
+ ```bash
144
+ mkdir -p ~/.claude/skills/claude-artifact-cli
145
+ curl -fsSL https://raw.githubusercontent.com/nikships/claude-artifact-cli/main/skills/claude-artifact-cli/SKILL.md \
146
+ -o ~/.claude/skills/claude-artifact-cli/SKILL.md
147
+ ```
148
+
149
+ ## Troubleshooting
150
+
151
+ | Symptom | Cause |
152
+ |---------|-------|
153
+ | `401 unauthorized` | An API key instead of the OAuth token, or an expired login. Start Claude Code once or run `claude /login`. |
154
+ | `400 … null deletes a path in mode:"patch"` | `--remove` without patch mode. |
155
+ | `404 … isn't yours to update` | Wrong slug, deleted artifact, or another org. |
156
+ | `409 … newer version exists` | Someone else published. Re-read, merge, retry, or pass `--force`. |
157
+ | `429 … daily publish cap` | Plan limit. Resets at UTC midnight. |
158
+
159
+ ## The protocol
160
+
161
+ Reverse-engineered from the Claude Code CLI v2.1.273 binary, where artifacts are called *frames*. Every call goes to `api.anthropic.com`, even though the artifact is served from `claude.ai`.
162
+
163
+ ```
164
+ POST /api/frame/deploy/direct publish
165
+ POST /api/frame/deploy/prepare content-hash preflight (bodies over ~15 MB)
166
+ POST /api/frame/upload stage blobs the preflight asked for
167
+ GET /api/frame/{slug}?via=model_read metadata + file manifest
168
+ GET /api/frame/read/{slug} ownership / sharing status
169
+ GET /api/frame/frames?limit=N list
170
+ ```
171
+
172
+ Headers:
173
+
174
+ ```
175
+ Authorization: Bearer <claude.ai OAuth access token>
176
+ anthropic-beta: oauth-2025-04-20
177
+ Accept: application/json, application/vnd.ant.frame-refusal+json
178
+ X-Frame-CP: go
179
+ X-Frame-Surface: code
180
+ X-Frame-Platform: cli
181
+ X-Frame-Client-Version: 2.1.273
182
+ ```
183
+
184
+ Only `Authorization` and `anthropic-beta` are load-bearing.
185
+
186
+ ### Deploy body
187
+
188
+ ```jsonc
189
+ {
190
+ "slug": "…", // omit to create a new artifact
191
+ "title": "My Page",
192
+ "favicon": "📊",
193
+ "description": "…",
194
+ "mode": "replace", // or "patch" (requires baseVersion)
195
+ "baseVersion": "1789541006-9f63",
196
+ "force": true,
197
+ "manifest": {
198
+ "index.html": { "content": "<!doctype html>…", "contentType": "text/html" },
199
+ "logo.png": { "sha256": "<64 hex>", "contentType": "image/png" },
200
+ "old.js": null
201
+ }
202
+ }
203
+ ```
204
+
205
+ A manifest value with `content` inlines the file; one with `sha256` references a blob already staged via `/upload`; `null` deletes that path (patch mode only).
206
+
207
+ **Wire encoding.** These content types go as raw UTF-8 strings; everything else is base64: `text/html`, `text/css`, `text/plain`, `text/markdown`, `text/csv`, `text/javascript`, `application/javascript`, `application/json`, `application/manifest+json`, `application/xml`, `text/xml`, `image/svg+xml`.
208
+
209
+ Response: `{"slug", "version", "read", "shared", "kind"}`. The page lives at `https://claude.ai/code/artifact/<slug>`.
210
+
211
+ ### Large publishes
212
+
213
+ Over ~15 MB inline, the client switches to `prepare` → `upload` → `deploy`. `prepare` takes `{slug?, shas:[…]}` and answers `{slug, missing:[…]}`. The missing blobs go to `/upload` in batches of at most 15 MB, and the final deploy references them by `sha256`: the hex sha256 of the raw file bytes.
214
+
215
+ ### Not supported
216
+
217
+ - **Reading published bytes.** Pages are served from a separate sandboxed host behind a short-lived asset token.
218
+ - **Delete and pin.** Both go through a relay-only route that isn't reachable on the direct path. Use `/artifacts` in Claude Code, or claude.ai.
219
+ - **Capabilities.** Runtime capability declarations (`capabilities`, `contract`) are accepted by the API but not exposed as flags.
220
+ - **Comments, watching, thumbnails.**
221
+
222
+ ## Project Structure
223
+
224
+ ```
225
+ .github/
226
+ └── workflows/
227
+ └── publish.yml lint, auto-version, PyPI publish, GitHub release
228
+ assets/
229
+ └── header.png
230
+ skills/
231
+ └── claude-artifact-cli/
232
+ └── SKILL.md agent skill
233
+ src/
234
+ └── claude_artifact_cli/
235
+ ├── __init__.py version
236
+ ├── __main__.py python -m claude_artifact_cli
237
+ ├── api.py frame API client
238
+ ├── auth.py token lookup
239
+ └── cli.py argparse entry point
240
+ AGENTS.md
241
+ LICENSE
242
+ README.md
243
+ pyproject.toml
244
+ ```
245
+
246
+ ## Documentation
247
+
248
+ | Resource | Description |
249
+ |----------|-------------|
250
+ | [SKILL.md](skills/claude-artifact-cli/SKILL.md) | Agent skill: when to use the CLI and how |
251
+ | [AGENTS.md](AGENTS.md) | Constraints and commands for coding agents working in this repo |
252
+ | [publish.yml](.github/workflows/publish.yml) | CI and release pipeline |
253
+ | [The protocol](#the-protocol) | Endpoints, headers and deploy body |
254
+
255
+ ## Contributing
256
+
257
+ Issues and pull requests are welcome. Keep the package dependency-free and run `uvx ruff check .` before pushing. Every merge to `main` that touches `src/` or `pyproject.toml` is released to PyPI automatically with a patch bump.
258
+
259
+ <a href="https://github.com/nikships/claude-artifact-cli/graphs/contributors">
260
+ <img src="https://contrib.rocks/image?repo=nikships/claude-artifact-cli" />
261
+ </a>
262
+
263
+ ## License
264
+
265
+ [Apache-2.0](LICENSE)
266
+
267
+ ---
268
+
269
+ <div align="center">
270
+
271
+ [![Star History Chart](https://api.star-history.com/svg?repos=nikships/claude-artifact-cli&type=Date)](https://star-history.com/#nikships/claude-artifact-cli&Date)
272
+
273
+ </div>
@@ -0,0 +1,10 @@
1
+ claude_artifact_cli/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ claude_artifact_cli/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83
3
+ claude_artifact_cli/api.py,sha256=9UBY5ht5ikHBJPoKUSnb5O3v4ogY-ScuLyv2U0a99O0,11693
4
+ claude_artifact_cli/auth.py,sha256=-hDqXpks5YGdTDeIaB_eZTVu0HHT_n2AAYmiNPcXKb8,4301
5
+ claude_artifact_cli/cli.py,sha256=XjPU5-27Rjq6yIBEHyP_IjZZ5872gt24OUXc77_QNaA,8723
6
+ claude_artifact_cli-0.1.0.dist-info/METADATA,sha256=XiwikywaLfS3cPSp3A-iW_UVuKBGa9Ka2phajBr9X_Q,12047
7
+ claude_artifact_cli-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
+ claude_artifact_cli-0.1.0.dist-info/entry_points.txt,sha256=Fd9AKWCQ5EwkW1wHwLHIhZbworFxcjPrdr8X_F9u0uY,65
9
+ claude_artifact_cli-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ claude_artifact_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ claude-artifact = claude_artifact_cli.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.