arctiq-cli 0.2.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.
arctiq_cli/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """The `arctiq` command: ARCTIQ from a terminal, for developers and their assistants (ADR 0025).
2
+
3
+ Standard library only. It signs in with the terminal sign-in (the device flow), keeps its token
4
+ in the system keyring when `keyring` is installed, else in a file only you can read, and calls
5
+ `/api/v1` only, saying what it is (`ARCTIQ-Client`) and, when an assistant drives it, which
6
+ (`ARCTIQ-Agent`), so its changes show "API" and "Agent" on the pages.
7
+ """
8
+
9
+ __version__ = "0.2.0"
arctiq_cli/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from arctiq_cli.main import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,14 @@
1
+ -----BEGIN CERTIFICATE-----
2
+ MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTEL
3
+ MAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYD
4
+ VQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4
5
+ MTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQL
6
+ DANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEG
7
+ BSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb
8
+ 48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZE
9
+ h8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkF
10
+ R+eWw5b6cp3PmanfS5YwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYC
11
+ MQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPW
12
+ rfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6N
13
+ IwLz3/Y=
14
+ -----END CERTIFICATE-----
arctiq_cli/client.py ADDED
@@ -0,0 +1,156 @@
1
+ """Calls to `/api/v1`. The transport is a function, so tests can answer without a network."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import os
8
+ import secrets
9
+ import urllib.error
10
+ import urllib.request
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, field
13
+ from urllib.parse import quote
14
+
15
+ from arctiq_cli import __version__
16
+
17
+
18
+ class Reading:
19
+ """A request body sent in blocks, telling `progress` (bytes sent, of total) as it goes. What
20
+ lets the TUI draw an upload's progress; the plain CLI sends bytes."""
21
+
22
+ def __init__(self, data: bytes, progress: Callable[[int, int], None]) -> None:
23
+ self._data, self.progress, self.total, self.sent = io.BytesIO(data), progress, len(data), 0
24
+
25
+ def read(self, size: int = -1) -> bytes:
26
+ block = self._data.read(size if size and size > 0 else 64 * 1024)
27
+ self.sent += len(block)
28
+ self.progress(self.sent, self.total)
29
+ return block
30
+
31
+ def getvalue(self) -> bytes:
32
+ return self._data.getvalue()
33
+
34
+
35
+ #: (method, url, headers, body) -> (status, body)
36
+ Transport = Callable[[str, str, dict[str, str], "bytes | Reading | None"], tuple[int, bytes]]
37
+ TIMEOUT = 300 # pinning keeps a copy of a release, and uploads can be large: give them time
38
+
39
+
40
+ def urllib_transport(
41
+ method: str, url: str, headers: dict[str, str], body: bytes | Reading | None
42
+ ) -> tuple[int, bytes]:
43
+ if not url.startswith(("https://", "http://localhost", "http://127.0.0.1")):
44
+ raise ApiError(0, "The server must be https (or localhost).")
45
+ if isinstance(body, Reading): # sent in blocks; its length is known, so no chunking
46
+ headers = {**headers, "Content-Length": str(body.total)}
47
+ request = urllib.request.Request(url, data=body, headers=headers, method=method) # noqa: S310
48
+ try:
49
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as answer: # noqa: S310
50
+ return answer.status, answer.read()
51
+ except urllib.error.HTTPError as exc:
52
+ return exc.code, exc.read()
53
+ except (urllib.error.URLError, TimeoutError) as exc:
54
+ raise ApiError(0, f"Could not reach {url.split('/api/')[0]}: {exc}") from None
55
+
56
+
57
+ def agent() -> str | None:
58
+ """The assistant driving this command, as it declares itself: `ARCTIQ_AGENT`, or Claude
59
+ Code's own marker. Recorded as declared, never as proof (ADR 0023)."""
60
+ named = os.environ.get("ARCTIQ_AGENT", "").strip()
61
+ if named:
62
+ return named[:100]
63
+ if os.environ.get("CLAUDECODE") == "1":
64
+ return "claude-code"
65
+ return None
66
+
67
+
68
+ class ApiError(Exception):
69
+ def __init__(self, status: int, detail: str, error: str | None = None) -> None:
70
+ super().__init__(detail)
71
+ self.status, self.detail, self.error = status, detail, error
72
+
73
+
74
+ @dataclass
75
+ class Api:
76
+ server: str
77
+ token: str | None = None
78
+ transport: Transport = field(default=urllib_transport)
79
+
80
+ def _headers(self, content_type: str | None) -> dict[str, str]:
81
+ headers = {"Accept": "application/json", "ARCTIQ-Client": f"arctiq-cli/{__version__}"}
82
+ if content_type:
83
+ headers["Content-Type"] = content_type
84
+ if self.token:
85
+ headers["Authorization"] = f"Bearer {self.token}"
86
+ if (who := agent()) is not None:
87
+ headers["ARCTIQ-Agent"] = who
88
+ return headers
89
+
90
+ def _send(
91
+ self, method: str, path: str, body: bytes | Reading | None, content_type: str | None
92
+ ) -> tuple[int, bytes]:
93
+ url = f"{self.server.rstrip('/')}/api/v1{path}"
94
+ status, raw = self.transport(method, url, self._headers(content_type), body)
95
+ if status >= 400:
96
+ try:
97
+ data = json.loads(raw) if raw else None
98
+ except ValueError:
99
+ data = None
100
+ detail = data.get("detail") if isinstance(data, dict) else None
101
+ error = data.get("error") if isinstance(data, dict) else None
102
+ if isinstance(detail, list): # FastAPI's validation errors
103
+ detail = "; ".join(str(d.get("msg", d)) for d in detail)
104
+ raise ApiError(status, str(detail or error or f"The server answered {status}."), error)
105
+ return status, raw
106
+
107
+ def call(self, method: str, path: str, payload: dict | None = None) -> object:
108
+ body = json.dumps(payload).encode() if payload is not None else None
109
+ _, raw = self._send(method, path, body, "application/json" if body is not None else None)
110
+ try:
111
+ return json.loads(raw) if raw else None
112
+ except ValueError:
113
+ return None
114
+
115
+ def upload(
116
+ self,
117
+ path: str,
118
+ filename: str,
119
+ data: bytes,
120
+ progress: Callable[[int, int], None] | None = None,
121
+ ) -> object:
122
+ """POST one file as `multipart/form-data`, field `file`. The server decides its type.
123
+ With `progress`, it is told (bytes sent, of total) as the body goes out."""
124
+ boundary = f"arctiq-{secrets.token_hex(16)}"
125
+ name = "".join("_" if ch in '"\\\r\n' else ch for ch in filename)
126
+ head = (
127
+ f"--{boundary}\r\n"
128
+ f'Content-Disposition: form-data; name="file"; filename="{name}"\r\n'
129
+ "Content-Type: application/octet-stream\r\n\r\n"
130
+ ).encode()
131
+ body = head + data + f"\r\n--{boundary}--\r\n".encode()
132
+ sent: bytes | Reading = body if progress is None else Reading(body, progress)
133
+ _, raw = self._send("POST", path, sent, f"multipart/form-data; boundary={boundary}")
134
+ return json.loads(raw) if raw else None
135
+
136
+ def download(self, path: str) -> bytes:
137
+ return self._send("GET", path, None, None)[1]
138
+
139
+ def get(self, path: str) -> object:
140
+ return self.call("GET", path)
141
+
142
+ def post(self, path: str, payload: dict) -> object:
143
+ return self.call("POST", path, payload)
144
+
145
+ def delete(self, path: str) -> object:
146
+ return self.call("DELETE", path)
147
+
148
+ def put_bytes(self, path: str, data: bytes) -> object:
149
+ """PUT raw bytes: one part of a file sent in parts."""
150
+ _, raw = self._send("PUT", path, data, "application/octet-stream")
151
+ return json.loads(raw) if raw else None
152
+
153
+
154
+ def part(value: str) -> str:
155
+ """One path segment, escaped."""
156
+ return quote(value, safe="")
@@ -0,0 +1,109 @@
1
+ """Where the token is kept: the system keyring when `keyring` is installed, else a file only
2
+ you can read (0600, in a 0700 folder). `ARCTIQ_TOKEN` and `ARCTIQ_SERVER` override both, for CI.
3
+
4
+ There is no built-in server: `arctiq login` asks for the ARCTIQ address the first time and the
5
+ file remembers it, also after `arctiq logout`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import importlib
12
+ import json
13
+ import os
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+ SERVICE = "arctiq"
18
+
19
+
20
+ def address(typed: str) -> str:
21
+ """An ARCTIQ address as a person types it: `https://` when no scheme is given, no slash at
22
+ the end. Whether it may be used (https, or localhost) is the transport's to decide."""
23
+ found = typed.strip().rstrip("/")
24
+ if found and "://" not in found:
25
+ found = f"https://{found}"
26
+ return found
27
+
28
+
29
+ def folder() -> Path:
30
+ base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
31
+ return Path(base) / "arctiq"
32
+
33
+
34
+ def _file() -> Path:
35
+ return folder() / "credentials.json"
36
+
37
+
38
+ def _keyring(): # noqa: ANN202 - an optional module
39
+ if os.environ.get("ARCTIQ_NO_KEYRING"):
40
+ return None
41
+ try:
42
+ return importlib.import_module("keyring")
43
+ except ImportError:
44
+ return None
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Saved:
49
+ #: None until `arctiq login` has been given an address (or `ARCTIQ_SERVER` is set).
50
+ server: str | None
51
+ token: str | None
52
+ #: "keyring", "file" or "environment".
53
+ where: str = "file"
54
+
55
+
56
+ def load() -> Saved:
57
+ given = os.environ.get("ARCTIQ_SERVER", "").strip()
58
+ token = os.environ.get("ARCTIQ_TOKEN", "").strip()
59
+ data: dict = {}
60
+ if _file().exists():
61
+ try:
62
+ data = json.loads(_file().read_text())
63
+ except (OSError, ValueError):
64
+ data = {}
65
+ server = address(given or str(data.get("server") or "")) or None
66
+ if token:
67
+ return Saved(server, token, "environment")
68
+ if server and data.get("keyring") and (kr := _keyring()) is not None:
69
+ return Saved(server, kr.get_password(SERVICE, server), "keyring")
70
+ return Saved(server, data.get("token") or None, "file")
71
+
72
+
73
+ def _write(data: dict) -> None:
74
+ path = _file()
75
+ path.parent.mkdir(parents=True, exist_ok=True)
76
+ path.parent.chmod(0o700)
77
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
78
+ with os.fdopen(fd, "w") as out:
79
+ json.dump(data, out)
80
+ path.chmod(0o600)
81
+
82
+
83
+ def save(server: str, token: str) -> str:
84
+ """Keep the token, and the address it is for; returns where the token went."""
85
+ data: dict = {"server": server}
86
+ where = "file"
87
+ kr = _keyring()
88
+ if kr is not None:
89
+ try:
90
+ kr.set_password(SERVICE, server, token)
91
+ data["keyring"], where = True, "keyring"
92
+ except Exception: # noqa: BLE001 - no usable keyring: fall back to the file
93
+ kr = None
94
+ if kr is None:
95
+ data["token"] = token
96
+ _write(data)
97
+ return where
98
+
99
+
100
+ def forget(server: str | None) -> None:
101
+ """Forget the token; keep the address, so the next `arctiq login` needn't ask for it."""
102
+ kr = _keyring()
103
+ if kr is not None and server:
104
+ with contextlib.suppress(Exception): # nothing was kept there
105
+ kr.delete_password(SERVICE, server)
106
+ if server:
107
+ _write({"server": server})
108
+ elif _file().exists():
109
+ _file().unlink()