brewsorted-cli 0.8.4__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.
- brewsorted_cli/__init__.py +5 -0
- brewsorted_cli/_skill/SKILL.md +201 -0
- brewsorted_cli/_skill/__init__.py +1 -0
- brewsorted_cli/_skill/agents/openai.yaml +6 -0
- brewsorted_cli/_skill/references/cli.md +471 -0
- brewsorted_cli/_skill/tests/acceptance_scenarios.json +946 -0
- brewsorted_cli/_skill/tests/test_skill.py +534 -0
- brewsorted_cli/auth_state.py +273 -0
- brewsorted_cli/client.py +482 -0
- brewsorted_cli/http.py +29 -0
- brewsorted_cli/main.py +851 -0
- brewsorted_cli/oauth_discovery.py +120 -0
- brewsorted_cli/oauth_login.py +277 -0
- brewsorted_cli/product_feedback.py +114 -0
- brewsorted_cli/skills.py +45 -0
- brewsorted_cli/updates.py +76 -0
- brewsorted_cli-0.8.4.dist-info/METADATA +172 -0
- brewsorted_cli-0.8.4.dist-info/RECORD +21 -0
- brewsorted_cli-0.8.4.dist-info/WHEEL +5 -0
- brewsorted_cli-0.8.4.dist-info/entry_points.txt +2 -0
- brewsorted_cli-0.8.4.dist-info/top_level.txt +1 -0
brewsorted_cli/main.py
ADDED
|
@@ -0,0 +1,851 @@
|
|
|
1
|
+
"""Resource-oriented command line interface."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
12
|
+
from uuid import UUID
|
|
13
|
+
|
|
14
|
+
from .http import proxy_url
|
|
15
|
+
from .client import ApiClient, ApiError, BackendUnavailable, InvalidServerResponse
|
|
16
|
+
from .auth_state import AuthState, AuthStateError, IssuerUnavailable, SignInRequired, select_state_path
|
|
17
|
+
from .oauth_discovery import AccessTokenVerifier, discover
|
|
18
|
+
from .oauth_login import LoginDenied, OAuthLogin
|
|
19
|
+
from .updates import check_updates, claim_reminder, update_message
|
|
20
|
+
from .skills import install_skill
|
|
21
|
+
|
|
22
|
+
DEFAULT_API_URL = "http://127.0.0.1:8765"
|
|
23
|
+
QUALIFIED_ID = re.compile(r"^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]/[1-9][0-9]*$")
|
|
24
|
+
USERNAME = re.compile(r"^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CliUsageError(ValueError):
|
|
28
|
+
"""Raised instead of letting argparse emit non-JSON process output."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class JsonArgumentParser(argparse.ArgumentParser):
|
|
32
|
+
def error(self, message: str) -> None:
|
|
33
|
+
raise CliUsageError(message)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _proxy(value: str) -> str:
|
|
37
|
+
try:
|
|
38
|
+
return proxy_url(value)
|
|
39
|
+
except ValueError as exc:
|
|
40
|
+
raise argparse.ArgumentTypeError(str(exc)) from None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _ratio(value: str) -> float:
|
|
44
|
+
return float(value.split(":", 1)[1] if ":" in value else value)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _time(value: str) -> int:
|
|
48
|
+
if ":" in value:
|
|
49
|
+
minutes, seconds = value.split(":", 1)
|
|
50
|
+
return int(minutes) * 60 + int(seconds)
|
|
51
|
+
return int(value)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _json_object(value: str) -> dict[str, Any]:
|
|
55
|
+
result = json.loads(value)
|
|
56
|
+
if not isinstance(result, dict):
|
|
57
|
+
raise argparse.ArgumentTypeError("must be a JSON object")
|
|
58
|
+
return result
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _record_id(value: str) -> str:
|
|
62
|
+
if not QUALIFIED_ID.fullmatch(value):
|
|
63
|
+
raise argparse.ArgumentTypeError("must be a Qualified ID (username/number)")
|
|
64
|
+
return value
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _is_record_id(value: object) -> bool:
|
|
68
|
+
return isinstance(value, str) and QUALIFIED_ID.fullmatch(value) is not None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _image_handle(value: str) -> str:
|
|
72
|
+
try:
|
|
73
|
+
username, image_id = value.split("/", 1)
|
|
74
|
+
UUID(image_id)
|
|
75
|
+
except (AttributeError, TypeError, ValueError) as error:
|
|
76
|
+
raise argparse.ArgumentTypeError(
|
|
77
|
+
"must be a User-qualified image handle (username/UUID)"
|
|
78
|
+
) from error
|
|
79
|
+
if not USERNAME.fullmatch(username):
|
|
80
|
+
raise argparse.ArgumentTypeError(
|
|
81
|
+
"must be a User-qualified image handle (username/UUID)"
|
|
82
|
+
)
|
|
83
|
+
return value
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _web_origin(value: str | None) -> str | None:
|
|
87
|
+
if value is None:
|
|
88
|
+
return None
|
|
89
|
+
if not value or value != value.strip():
|
|
90
|
+
raise ValueError("web URL must be an absolute HTTP(S) origin")
|
|
91
|
+
parsed = urlsplit(value)
|
|
92
|
+
try:
|
|
93
|
+
parsed.port
|
|
94
|
+
except ValueError as error:
|
|
95
|
+
raise ValueError("web URL must be an absolute HTTP(S) origin") from error
|
|
96
|
+
if (
|
|
97
|
+
parsed.scheme not in {"http", "https"}
|
|
98
|
+
or parsed.hostname is None
|
|
99
|
+
or parsed.username is not None
|
|
100
|
+
or parsed.password is not None
|
|
101
|
+
or parsed.path not in {"", "/"}
|
|
102
|
+
or parsed.query
|
|
103
|
+
or parsed.fragment
|
|
104
|
+
):
|
|
105
|
+
raise ValueError("web URL must be an absolute HTTP(S) origin")
|
|
106
|
+
return urlunsplit((parsed.scheme, parsed.netloc, "", "", ""))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _item_web_url(origin: str, resource: str, item: Any) -> dict[str, Any] | Any:
|
|
110
|
+
if not isinstance(item, dict):
|
|
111
|
+
return item
|
|
112
|
+
item_id = item.get("id")
|
|
113
|
+
if not _is_record_id(item_id):
|
|
114
|
+
return item
|
|
115
|
+
return item | {"web_url": f"{origin}/{resource}/{item_id}"}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _add_web_links(value: Any, args: argparse.Namespace) -> Any:
|
|
119
|
+
origin = _web_origin(args.web_url)
|
|
120
|
+
if origin is None or args.resource in {"status", "bag-adjustments", "product-feedback"} or value is None:
|
|
121
|
+
return value
|
|
122
|
+
resource = args.resource
|
|
123
|
+
if resource == "context" and isinstance(value, dict):
|
|
124
|
+
linked = dict(value)
|
|
125
|
+
for field, route in (
|
|
126
|
+
("equipment", "equipment"),
|
|
127
|
+
("devices", "devices"),
|
|
128
|
+
("grinders", "grinders"),
|
|
129
|
+
("brew_methods", "brew-methods"),
|
|
130
|
+
("drink_types", "drink-types"),
|
|
131
|
+
("recipes", "recipes"),
|
|
132
|
+
("brews", "brews"),
|
|
133
|
+
):
|
|
134
|
+
items = value.get(field)
|
|
135
|
+
if isinstance(items, list):
|
|
136
|
+
linked[field] = [
|
|
137
|
+
_item_web_url(origin, route, item) for item in items
|
|
138
|
+
]
|
|
139
|
+
return linked
|
|
140
|
+
operation = args.operation
|
|
141
|
+
if resource == "brews" and operation == "compare" and isinstance(value, dict):
|
|
142
|
+
linked = dict(value)
|
|
143
|
+
for side in ("left", "right"):
|
|
144
|
+
item_id = value.get(f"{side}_id")
|
|
145
|
+
if _is_record_id(item_id):
|
|
146
|
+
linked[f"{side}_web_url"] = f"{origin}/brews/{item_id}"
|
|
147
|
+
return linked
|
|
148
|
+
if resource == "recipes" and operation == "apply":
|
|
149
|
+
return _item_web_url(origin, "brews", value)
|
|
150
|
+
if resource in {"suggestion-attempts", "suggestion-feedback"}:
|
|
151
|
+
def suggestion_link(item: Any) -> Any:
|
|
152
|
+
if not isinstance(item, dict):
|
|
153
|
+
return item
|
|
154
|
+
suggestion_id = item.get("suggestion_id")
|
|
155
|
+
if not _is_record_id(suggestion_id):
|
|
156
|
+
return item
|
|
157
|
+
return item | {
|
|
158
|
+
"suggestion_web_url": f"{origin}/suggestions/{suggestion_id}"
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if operation == "list" and isinstance(value, dict):
|
|
162
|
+
items = value.get("items")
|
|
163
|
+
if isinstance(items, list):
|
|
164
|
+
return value | {"items": [suggestion_link(item) for item in items]}
|
|
165
|
+
return value
|
|
166
|
+
return suggestion_link(value)
|
|
167
|
+
if operation in {"list", "history"} and isinstance(value, dict):
|
|
168
|
+
items = value.get("items")
|
|
169
|
+
if isinstance(items, list):
|
|
170
|
+
return value | {
|
|
171
|
+
"items": [_item_web_url(origin, resource, item) for item in items]
|
|
172
|
+
}
|
|
173
|
+
return value
|
|
174
|
+
return _item_web_url(origin, resource, value)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
Field = tuple[str, Callable[[str], Any] | type]
|
|
178
|
+
|
|
179
|
+
RESOURCE_FIELDS: dict[str, list[Field]] = {
|
|
180
|
+
"roasteries": [
|
|
181
|
+
("name", str), ("country", str), ("city", str), ("website", str),
|
|
182
|
+
("image_id", str), ("notes", str),
|
|
183
|
+
],
|
|
184
|
+
"coffees": [
|
|
185
|
+
("roastery_id", _record_id), ("name", str), ("origin_country", str), ("region", str),
|
|
186
|
+
("producer_farm", str), ("varietal", str), ("process", str),
|
|
187
|
+
("altitude_masl", int), ("roast_level", str), ("roast_target", str),
|
|
188
|
+
("tasting_notes", str), ("product_url", str), ("image_id", str),
|
|
189
|
+
("is_decaf", bool), ("notes", str),
|
|
190
|
+
],
|
|
191
|
+
"bags": [
|
|
192
|
+
("coffee_id", _record_id), ("roast_date", str), ("purchase_date", str),
|
|
193
|
+
("opened_date", str), ("weight_g", float), ("price", float),
|
|
194
|
+
("currency", str), ("vendor", str), ("best_before", str),
|
|
195
|
+
("finished_date", str), ("notes", str),
|
|
196
|
+
],
|
|
197
|
+
"equipment": [
|
|
198
|
+
("name", str), ("type", str), ("image_id", str), ("notes", str),
|
|
199
|
+
("tag", str), ("brewer_kind", str), ("grinder_kind", str),
|
|
200
|
+
("burr_type", str), ("setting_scale", str), ("scale_description", str),
|
|
201
|
+
("scale_minimum", float), ("scale_maximum", float), ("scale_step", float),
|
|
202
|
+
("scale_direction", str),
|
|
203
|
+
],
|
|
204
|
+
"brew-methods": [("name", str), ("description", str), ("image_id", str), ('ratio_basis', str)],
|
|
205
|
+
"drink-types": [("name", str), ("description", str), ("image_id", str)],
|
|
206
|
+
"water-profiles": [
|
|
207
|
+
("name", str), ("source", str), ("tds_ppm", int), ("gh", int),
|
|
208
|
+
("kh", int), ("image_id", str), ("notes", str),
|
|
209
|
+
],
|
|
210
|
+
"brews": [
|
|
211
|
+
('acknowledge_missing_ratio_measurement', bool),
|
|
212
|
+
("coffee_bag_id", _record_id), ("brewer_id", _record_id),
|
|
213
|
+
("grinder_id", _record_id), ("kettle_id", _record_id), ("scale_id", _record_id),
|
|
214
|
+
("server_id", _record_id), ("filter_id", _record_id),
|
|
215
|
+
("additional_equipment_ids", _record_id), ("grind_setting", float),
|
|
216
|
+
("dose_g", float), ("water_g", float),
|
|
217
|
+
("ratio", _ratio), ("drink_type_id", _record_id), ("brew_method_id", _record_id), ("water_profile_id", _record_id),
|
|
218
|
+
("water_temp_c", float), ("total_time_s", _time), ("bloom_water_g", float),
|
|
219
|
+
("bloom_time_s", _time), ("agitation", str), ("filter_type", str),
|
|
220
|
+
("method_params", _json_object), ("tds_percent", float),
|
|
221
|
+
("beverage_weight_g", float), ("brewed_at", str), ("notes", str),
|
|
222
|
+
("rating", _json_object),
|
|
223
|
+
],
|
|
224
|
+
"recipes": [
|
|
225
|
+
('target_beverage_weight_g', float),
|
|
226
|
+
("name", str), ("description", str), ("brew_method_id", _record_id),
|
|
227
|
+
("drink_type_id", _record_id), ("water_profile_id", _record_id),
|
|
228
|
+
("brewer_id", _record_id), ("grinder_id", _record_id), ("kettle_id", _record_id),
|
|
229
|
+
("scale_id", _record_id), ("server_id", _record_id), ("filter_id", _record_id),
|
|
230
|
+
("additional_equipment_ids", _record_id), ("grind_setting", float),
|
|
231
|
+
("dose_g", float), ("water_g", float), ("ratio", _ratio),
|
|
232
|
+
("water_temp_c", float), ("total_time_s", _time),
|
|
233
|
+
("bloom_water_g", float), ("bloom_time_s", _time),
|
|
234
|
+
("agitation", str), ("filter_type", str),
|
|
235
|
+
("method_params", _json_object), ("instructions", str),
|
|
236
|
+
],
|
|
237
|
+
"recipe-application": [
|
|
238
|
+
('beverage_weight_g', float), ('scale_from', str),
|
|
239
|
+
('acknowledge_missing_ratio_measurement', bool), ('allow_ratio_override', bool),
|
|
240
|
+
("coffee_bag_id", _record_id), ("brew_method_id", _record_id),
|
|
241
|
+
("drink_type_id", _record_id), ("water_profile_id", _record_id),
|
|
242
|
+
("brewer_id", _record_id), ("grinder_id", _record_id), ("kettle_id", _record_id),
|
|
243
|
+
("scale_id", _record_id), ("server_id", _record_id), ("filter_id", _record_id),
|
|
244
|
+
("additional_equipment_ids", _record_id), ("grind_setting", float),
|
|
245
|
+
("dose_g", float), ("water_g", float), ("ratio", _ratio),
|
|
246
|
+
("water_temp_c", float), ("total_time_s", _time),
|
|
247
|
+
("bloom_water_g", float), ("bloom_time_s", _time),
|
|
248
|
+
("agitation", str), ("filter_type", str),
|
|
249
|
+
("method_params", _json_object), ("instructions", str),
|
|
250
|
+
("brewed_at", str), ("notes", str), ("rating", _json_object),
|
|
251
|
+
],
|
|
252
|
+
"brew-ratings": [
|
|
253
|
+
("overall", int), ("acidity", int), ("sweetness", int), ("body", int),
|
|
254
|
+
("bitterness", int), ("aftertaste", int), ("balance", int),
|
|
255
|
+
("extraction", str), ("notes", str), ("rated_at", str),
|
|
256
|
+
],
|
|
257
|
+
"coffee-ratings": [
|
|
258
|
+
("overall", int), ("would_rebuy", bool), ("notes", str), ("rated_at", str),
|
|
259
|
+
],
|
|
260
|
+
"bag-adjustments": [
|
|
261
|
+
("change_g", float), ("remaining_weight_g", float), ("finish", bool),
|
|
262
|
+
("reason", str), ("notes", str),
|
|
263
|
+
],
|
|
264
|
+
"suggestions": [("strategy_id", str)],
|
|
265
|
+
"suggestion-attempts": [("brew_id", _record_id)],
|
|
266
|
+
"suggestion-feedback": [("outcome", str), ("notes", str)],
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
STANDARD_RESOURCES = (
|
|
270
|
+
"roasteries", "coffees", "bags", "equipment",
|
|
271
|
+
"water-profiles", "brew-methods", "drink-types", "recipes", "brews"
|
|
272
|
+
)
|
|
273
|
+
LEGACY_READ_RESOURCES = ("grinders", "devices")
|
|
274
|
+
RATING_RESOURCES = {"brew-ratings": ("brews", "brew"), "coffee-ratings": ("coffees", "coffee")}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _add_fields(parser: argparse.ArgumentParser, resource: str) -> None:
|
|
278
|
+
for name, converter in RESOURCE_FIELDS[resource]:
|
|
279
|
+
option = "--" + name.replace("_", "-")
|
|
280
|
+
if resource == "equipment" and name == "tag":
|
|
281
|
+
parser.add_argument(option, dest=name, action="append")
|
|
282
|
+
elif (
|
|
283
|
+
resource in {"brews", "recipes", "recipe-application"}
|
|
284
|
+
and name == "additional_equipment_ids"
|
|
285
|
+
):
|
|
286
|
+
parser.add_argument(
|
|
287
|
+
"--additional-equipment-id", dest=name, type=converter, action="append"
|
|
288
|
+
)
|
|
289
|
+
elif converter is bool:
|
|
290
|
+
parser.add_argument(option, action=argparse.BooleanOptionalAction, default=None)
|
|
291
|
+
else:
|
|
292
|
+
help_text = None
|
|
293
|
+
if name in {"roast_date", "purchase_date", "opened_date", "best_before", "finished_date"}:
|
|
294
|
+
help_text = "calendar date YYYY-MM-DD"
|
|
295
|
+
elif name in {"brewed_at", "rated_at"}:
|
|
296
|
+
help_text = "date or timestamp with seconds, optional 1–6 fractional digits and Z/±HH:MM; naive means UTC"
|
|
297
|
+
parser.add_argument(option, dest=name, type=converter, help=help_text)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _add_input(parser: argparse.ArgumentParser) -> None:
|
|
301
|
+
parser.add_argument("--input", help="JSON from '-' (stdin) or '@path'")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _add_paging(parser: argparse.ArgumentParser) -> None:
|
|
305
|
+
parser.add_argument("--limit", type=int, default=50)
|
|
306
|
+
parser.add_argument("--offset", type=int, default=0)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
310
|
+
parser = JsonArgumentParser(prog="brewsorted")
|
|
311
|
+
parser.add_argument(
|
|
312
|
+
"--api-url", default=os.environ.get("BREWSORTED_API_URL", DEFAULT_API_URL)
|
|
313
|
+
)
|
|
314
|
+
parser.add_argument(
|
|
315
|
+
"--web-url", default=os.environ.get("BREWSORTED_WEB_URL") or None
|
|
316
|
+
)
|
|
317
|
+
parser.add_argument("--proxy", type=_proxy,
|
|
318
|
+
help="HTTP(S) proxy URL; overrides environment proxy and bypass settings")
|
|
319
|
+
parser.add_argument("--timeout", type=float, default=5.0)
|
|
320
|
+
parser.add_argument("--state-file", default=None, help="protected OAuth credential file")
|
|
321
|
+
commands = parser.add_subparsers(dest="resource", required=True)
|
|
322
|
+
skills = commands.add_parser("skills", help="install the matching complete agent skill")
|
|
323
|
+
skill_operations = skills.add_subparsers(dest="operation", required=True)
|
|
324
|
+
skill_install = skill_operations.add_parser("install", help="copy the bundled skill; never overwrite")
|
|
325
|
+
skill_install.add_argument(
|
|
326
|
+
"--destination", type=Path, default=Path.home() / ".agents/skills/brewsorted",
|
|
327
|
+
help="complete destination directory (default: ~/.agents/skills/brewsorted)",
|
|
328
|
+
)
|
|
329
|
+
commands.add_parser("status", help="check API and schema status")
|
|
330
|
+
commands.add_parser("context", help="load recently used gear and Brews")
|
|
331
|
+
product_feedback = commands.add_parser("product-feedback", help="explicitly submit private Product feedback")
|
|
332
|
+
feedback_operations = product_feedback.add_subparsers(dest="operation", required=True)
|
|
333
|
+
submit = feedback_operations.add_parser("submit", help="send once; receipt only, no guaranteed reply")
|
|
334
|
+
submit.add_argument("--input", required=True, help="JSON from '-' stdin or '@path'")
|
|
335
|
+
updates = commands.add_parser("updates", help="check for a newer client bundle")
|
|
336
|
+
updates.add_argument("--claim-reminder", action="store_true",
|
|
337
|
+
help="reserve at most one reminder per 24 hours after handling a request")
|
|
338
|
+
login = commands.add_parser("login", help="authorize a CLI Connection")
|
|
339
|
+
login_method = login.add_mutually_exclusive_group()
|
|
340
|
+
login_method.add_argument("--device", action="store_true", help="authorize from another device")
|
|
341
|
+
login_method.add_argument("--open-browser", action="store_true", help="open the local sign-in URL")
|
|
342
|
+
logout = commands.add_parser("logout", help="revoke and remove the local Connection")
|
|
343
|
+
logout.add_argument("--local", action="store_true", help="remove only local credentials")
|
|
344
|
+
|
|
345
|
+
equipment_types = commands.add_parser("equipment-types")
|
|
346
|
+
equipment_type_operations = equipment_types.add_subparsers(
|
|
347
|
+
dest="operation", required=True
|
|
348
|
+
)
|
|
349
|
+
equipment_type_list = equipment_type_operations.add_parser("list")
|
|
350
|
+
_add_paging(equipment_type_list)
|
|
351
|
+
|
|
352
|
+
images = commands.add_parser("images")
|
|
353
|
+
image_operations = images.add_subparsers(dest="operation", required=True)
|
|
354
|
+
upload = image_operations.add_parser("upload")
|
|
355
|
+
upload.add_argument("path")
|
|
356
|
+
image_get = image_operations.add_parser("get")
|
|
357
|
+
image_get.add_argument("id", type=_image_handle)
|
|
358
|
+
image_delete = image_operations.add_parser("delete")
|
|
359
|
+
image_delete.add_argument("id", type=_image_handle)
|
|
360
|
+
|
|
361
|
+
for resource in STANDARD_RESOURCES:
|
|
362
|
+
group = commands.add_parser(resource)
|
|
363
|
+
operations = group.add_subparsers(dest="operation", required=True)
|
|
364
|
+
create = operations.add_parser("create")
|
|
365
|
+
_add_fields(create, resource)
|
|
366
|
+
_add_input(create)
|
|
367
|
+
listing = operations.add_parser("list")
|
|
368
|
+
_add_paging(listing)
|
|
369
|
+
if resource in {"roasteries", "coffees", "grinders", "devices", "equipment", "water-profiles", "brew-methods", "drink-types", "recipes"}:
|
|
370
|
+
listing.add_argument("--q")
|
|
371
|
+
if resource == "equipment":
|
|
372
|
+
listing.add_argument("--type")
|
|
373
|
+
listing.add_argument("--tag")
|
|
374
|
+
if resource == "coffees":
|
|
375
|
+
listing.add_argument("--roastery-id", type=_record_id)
|
|
376
|
+
if resource == "bags":
|
|
377
|
+
listing.add_argument("--coffee-id", type=_record_id)
|
|
378
|
+
listing.add_argument("--active", action=argparse.BooleanOptionalAction, default=None)
|
|
379
|
+
if resource == "brews":
|
|
380
|
+
listing.add_argument("--coffee-id", type=_record_id)
|
|
381
|
+
listing.add_argument("--bag-id", type=_record_id)
|
|
382
|
+
listing.add_argument("--drink-type-id", type=_record_id)
|
|
383
|
+
listing.add_argument("--source-recipe-id", type=_record_id)
|
|
384
|
+
listing.add_argument("--date-from", help="inclusive UTC date or instant")
|
|
385
|
+
listing.add_argument("--date-to", help="inclusive instant, or entire UTC day for YYYY-MM-DD")
|
|
386
|
+
if resource == "recipes":
|
|
387
|
+
listing.add_argument("--brew-method-id", type=_record_id)
|
|
388
|
+
listing.add_argument("--equipment-id", type=_record_id)
|
|
389
|
+
get = operations.add_parser("get")
|
|
390
|
+
get.add_argument("id", type=_record_id)
|
|
391
|
+
update = operations.add_parser("update")
|
|
392
|
+
update.add_argument("id", type=_record_id)
|
|
393
|
+
_add_fields(update, resource)
|
|
394
|
+
_add_input(update)
|
|
395
|
+
delete = operations.add_parser("delete")
|
|
396
|
+
delete.add_argument("id", type=_record_id)
|
|
397
|
+
if resource == "brews":
|
|
398
|
+
history = operations.add_parser("history")
|
|
399
|
+
history.add_argument("--coffee-id", type=_record_id, required=True)
|
|
400
|
+
history.add_argument("--drink-type-id", type=_record_id)
|
|
401
|
+
_add_paging(history)
|
|
402
|
+
latest = operations.add_parser("latest")
|
|
403
|
+
latest.add_argument("--coffee-id", type=_record_id, required=True)
|
|
404
|
+
compare = operations.add_parser("compare")
|
|
405
|
+
compare.add_argument("left_id", type=_record_id)
|
|
406
|
+
compare.add_argument("right_id", type=_record_id)
|
|
407
|
+
if resource == "recipes":
|
|
408
|
+
for name in ("preview", "apply"):
|
|
409
|
+
command = operations.add_parser(name)
|
|
410
|
+
command.add_argument("id", type=_record_id)
|
|
411
|
+
_add_fields(command, "recipe-application")
|
|
412
|
+
_add_input(command)
|
|
413
|
+
|
|
414
|
+
for resource in LEGACY_READ_RESOURCES:
|
|
415
|
+
group = commands.add_parser(resource)
|
|
416
|
+
operations = group.add_subparsers(dest="operation", required=True)
|
|
417
|
+
listing = operations.add_parser("list")
|
|
418
|
+
_add_paging(listing)
|
|
419
|
+
listing.add_argument("--q")
|
|
420
|
+
get = operations.add_parser("get")
|
|
421
|
+
get.add_argument("id", type=_record_id)
|
|
422
|
+
|
|
423
|
+
for resource, (_, parent_name) in RATING_RESOURCES.items():
|
|
424
|
+
group = commands.add_parser(resource)
|
|
425
|
+
operations = group.add_subparsers(dest="operation", required=True)
|
|
426
|
+
create = operations.add_parser("create")
|
|
427
|
+
create.add_argument(f"--{parent_name}-id", type=_record_id, required=True)
|
|
428
|
+
_add_fields(create, resource)
|
|
429
|
+
_add_input(create)
|
|
430
|
+
listing = operations.add_parser("list")
|
|
431
|
+
listing.add_argument(f"--{parent_name}-id", type=_record_id, required=True)
|
|
432
|
+
_add_paging(listing)
|
|
433
|
+
get = operations.add_parser("get")
|
|
434
|
+
get.add_argument("id", type=_record_id)
|
|
435
|
+
update = operations.add_parser("update")
|
|
436
|
+
update.add_argument("id", type=_record_id)
|
|
437
|
+
_add_fields(update, resource)
|
|
438
|
+
_add_input(update)
|
|
439
|
+
delete = operations.add_parser("delete")
|
|
440
|
+
delete.add_argument("id", type=_record_id)
|
|
441
|
+
|
|
442
|
+
adjustments = commands.add_parser("bag-adjustments")
|
|
443
|
+
adjustment_ops = adjustments.add_subparsers(dest="operation", required=True)
|
|
444
|
+
adjustment_create = adjustment_ops.add_parser("create")
|
|
445
|
+
adjustment_create.add_argument("--bag-id", type=_record_id, required=True)
|
|
446
|
+
_add_fields(adjustment_create, "bag-adjustments")
|
|
447
|
+
_add_input(adjustment_create)
|
|
448
|
+
adjustment_list = adjustment_ops.add_parser("list")
|
|
449
|
+
adjustment_list.add_argument("--bag-id", type=_record_id, required=True)
|
|
450
|
+
_add_paging(adjustment_list)
|
|
451
|
+
adjustment_get = adjustment_ops.add_parser("get")
|
|
452
|
+
adjustment_get.add_argument("id", type=_record_id)
|
|
453
|
+
|
|
454
|
+
strategies = commands.add_parser("suggestion-strategies")
|
|
455
|
+
strategy_ops = strategies.add_subparsers(dest="operation", required=True)
|
|
456
|
+
strategy_list = strategy_ops.add_parser("list")
|
|
457
|
+
_add_paging(strategy_list)
|
|
458
|
+
|
|
459
|
+
suggestions = commands.add_parser("suggestions")
|
|
460
|
+
suggestion_ops = suggestions.add_subparsers(dest="operation", required=True)
|
|
461
|
+
suggestion_create = suggestion_ops.add_parser("create")
|
|
462
|
+
suggestion_create.add_argument("--brew-id", type=_record_id, required=True)
|
|
463
|
+
_add_fields(suggestion_create, "suggestions")
|
|
464
|
+
_add_input(suggestion_create)
|
|
465
|
+
suggestion_list = suggestion_ops.add_parser("list")
|
|
466
|
+
suggestion_list.add_argument("--brew-id", type=_record_id)
|
|
467
|
+
suggestion_list.add_argument(
|
|
468
|
+
"--outcome", choices=("proposed", "insufficient_evidence")
|
|
469
|
+
)
|
|
470
|
+
suggestion_list.add_argument("--strategy-id")
|
|
471
|
+
_add_paging(suggestion_list)
|
|
472
|
+
suggestion_get = suggestion_ops.add_parser("get")
|
|
473
|
+
suggestion_get.add_argument("id", type=_record_id)
|
|
474
|
+
|
|
475
|
+
attempts = commands.add_parser("suggestion-attempts")
|
|
476
|
+
attempt_ops = attempts.add_subparsers(dest="operation", required=True)
|
|
477
|
+
attempt_create = attempt_ops.add_parser("create")
|
|
478
|
+
attempt_create.add_argument("--suggestion-id", type=_record_id, required=True)
|
|
479
|
+
_add_fields(attempt_create, "suggestion-attempts")
|
|
480
|
+
_add_input(attempt_create)
|
|
481
|
+
attempt_get = attempt_ops.add_parser("get")
|
|
482
|
+
attempt_get.add_argument("id", type=_record_id)
|
|
483
|
+
|
|
484
|
+
feedback = commands.add_parser("suggestion-feedback")
|
|
485
|
+
feedback_ops = feedback.add_subparsers(dest="operation", required=True)
|
|
486
|
+
feedback_create = feedback_ops.add_parser("create")
|
|
487
|
+
feedback_create.add_argument("--attempt-id", type=_record_id, required=True)
|
|
488
|
+
_add_fields(feedback_create, "suggestion-feedback")
|
|
489
|
+
_add_input(feedback_create)
|
|
490
|
+
feedback_list = feedback_ops.add_parser("list")
|
|
491
|
+
feedback_list.add_argument("--attempt-id", type=_record_id, required=True)
|
|
492
|
+
_add_paging(feedback_list)
|
|
493
|
+
feedback_get = feedback_ops.add_parser("get")
|
|
494
|
+
feedback_get.add_argument("id", type=_record_id)
|
|
495
|
+
return parser
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _load_input(value: str) -> dict[str, Any]:
|
|
499
|
+
if value == "-":
|
|
500
|
+
raw = sys.stdin.read()
|
|
501
|
+
elif value.startswith("@"):
|
|
502
|
+
raw = Path(value[1:]).read_text(encoding="utf-8")
|
|
503
|
+
else:
|
|
504
|
+
raise ValueError("--input must be '-' or '@path'")
|
|
505
|
+
parsed = json.loads(raw)
|
|
506
|
+
if not isinstance(parsed, dict):
|
|
507
|
+
raise ValueError("input must contain a JSON object")
|
|
508
|
+
return parsed
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _payload(args: argparse.Namespace, resource: str) -> dict[str, Any]:
|
|
512
|
+
flags = {
|
|
513
|
+
name: getattr(args, name) for name, _ in RESOURCE_FIELDS[resource]
|
|
514
|
+
if hasattr(args, name) and getattr(args, name) is not None
|
|
515
|
+
}
|
|
516
|
+
input_value = getattr(args, "input", None)
|
|
517
|
+
if input_value and flags:
|
|
518
|
+
raise ValueError("use either typed flags or --input, not both")
|
|
519
|
+
if input_value:
|
|
520
|
+
return _load_input(input_value)
|
|
521
|
+
if resource != "equipment":
|
|
522
|
+
return flags
|
|
523
|
+
|
|
524
|
+
payload = {
|
|
525
|
+
key: flags.pop(key) for key in ("name", "type", "image_id", "notes")
|
|
526
|
+
if key in flags
|
|
527
|
+
}
|
|
528
|
+
tags = flags.pop("tag", None)
|
|
529
|
+
if tags is not None:
|
|
530
|
+
payload["tags"] = tags
|
|
531
|
+
brewer_kind = flags.pop("brewer_kind", None)
|
|
532
|
+
if brewer_kind is not None:
|
|
533
|
+
payload["brewer"] = {"kind": brewer_kind}
|
|
534
|
+
grinder_values = {
|
|
535
|
+
target: flags.pop(source)
|
|
536
|
+
for source, target in (
|
|
537
|
+
("grinder_kind", "kind"), ("burr_type", "burr_type"),
|
|
538
|
+
("setting_scale", "setting_scale"),
|
|
539
|
+
)
|
|
540
|
+
if source in flags
|
|
541
|
+
}
|
|
542
|
+
scale_values = {
|
|
543
|
+
target: flags.pop(source)
|
|
544
|
+
for source, target in (
|
|
545
|
+
("scale_description", "description"), ("scale_minimum", "minimum"),
|
|
546
|
+
("scale_maximum", "maximum"), ("scale_step", "step"),
|
|
547
|
+
("scale_direction", "direction"),
|
|
548
|
+
)
|
|
549
|
+
if source in flags
|
|
550
|
+
}
|
|
551
|
+
if scale_values:
|
|
552
|
+
grinder_values["scale"] = scale_values
|
|
553
|
+
if grinder_values:
|
|
554
|
+
payload["grinder"] = grinder_values
|
|
555
|
+
return payload
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _dispatch(args: argparse.Namespace, client: ApiClient) -> Any:
|
|
559
|
+
resource = args.resource
|
|
560
|
+
if resource == "product-feedback":
|
|
561
|
+
from .product_feedback import strict_json, validate_submission
|
|
562
|
+
value = args.input
|
|
563
|
+
if value == "-":
|
|
564
|
+
raw = sys.stdin.read(128 * 1024 + 1)
|
|
565
|
+
elif value.startswith("@"):
|
|
566
|
+
with Path(value[1:]).open(encoding="utf-8") as source:
|
|
567
|
+
raw = source.read(128 * 1024 + 1)
|
|
568
|
+
else:
|
|
569
|
+
raise ValueError("--input must be '-' or '@path'")
|
|
570
|
+
try:
|
|
571
|
+
if len(raw.encode("utf-8")) > 128 * 1024:
|
|
572
|
+
raise ValueError("Product feedback input is too large")
|
|
573
|
+
body = validate_submission(strict_json(raw))
|
|
574
|
+
except (ValueError, RecursionError):
|
|
575
|
+
raise ValueError("Product feedback requires exactly one valid text message") from None
|
|
576
|
+
return client.submit_product_feedback(body)
|
|
577
|
+
if resource == "status":
|
|
578
|
+
return client.request(
|
|
579
|
+
"GET", "/healthz", response_kind="health", authenticate=False
|
|
580
|
+
)
|
|
581
|
+
if resource == "context":
|
|
582
|
+
return client.request("GET", "/v1/context", response_kind="context")
|
|
583
|
+
|
|
584
|
+
operation = args.operation
|
|
585
|
+
if resource == "equipment-types":
|
|
586
|
+
return client.request(
|
|
587
|
+
"GET", "/v1/equipment-types",
|
|
588
|
+
params={"limit": args.limit, "offset": args.offset},
|
|
589
|
+
response_kind="system_list",
|
|
590
|
+
)
|
|
591
|
+
if resource == "images":
|
|
592
|
+
if operation == "upload":
|
|
593
|
+
return client.request(
|
|
594
|
+
"POST", "/v1/images", file_path=args.path, response_kind="image"
|
|
595
|
+
)
|
|
596
|
+
if operation == "get":
|
|
597
|
+
return client.request(
|
|
598
|
+
"GET", f"/v1/images/{args.id}", response_kind="image"
|
|
599
|
+
)
|
|
600
|
+
return client.request("DELETE", f"/v1/images/{args.id}")
|
|
601
|
+
if resource == "bag-adjustments":
|
|
602
|
+
if operation in {"create", "list"}:
|
|
603
|
+
path = f"/v1/bags/{args.bag_id}/adjustments"
|
|
604
|
+
if operation == "create":
|
|
605
|
+
return client.request(
|
|
606
|
+
"POST", path, body=_payload(args, "bag-adjustments")
|
|
607
|
+
)
|
|
608
|
+
return client.request(
|
|
609
|
+
"GET", path,
|
|
610
|
+
params={"limit": args.limit, "offset": args.offset},
|
|
611
|
+
response_kind="list",
|
|
612
|
+
)
|
|
613
|
+
return client.request("GET", f"/v1/bag-adjustments/{args.id}")
|
|
614
|
+
if resource == "suggestion-strategies":
|
|
615
|
+
return client.request(
|
|
616
|
+
"GET", "/v1/suggestion-strategies",
|
|
617
|
+
params={"limit": args.limit, "offset": args.offset},
|
|
618
|
+
response_kind="strategy_list",
|
|
619
|
+
)
|
|
620
|
+
if resource == "suggestions":
|
|
621
|
+
if operation == "create":
|
|
622
|
+
return client.request(
|
|
623
|
+
"POST", f"/v1/brews/{args.brew_id}/suggestions",
|
|
624
|
+
body=_payload(args, "suggestions"), response_kind="suggestion",
|
|
625
|
+
)
|
|
626
|
+
if operation == "list":
|
|
627
|
+
return client.request(
|
|
628
|
+
"GET", "/v1/suggestions",
|
|
629
|
+
params={
|
|
630
|
+
"brew_id": args.brew_id, "outcome": args.outcome,
|
|
631
|
+
"strategy_id": args.strategy_id,
|
|
632
|
+
"limit": args.limit, "offset": args.offset,
|
|
633
|
+
},
|
|
634
|
+
response_kind="suggestion_list",
|
|
635
|
+
)
|
|
636
|
+
return client.request(
|
|
637
|
+
"GET", f"/v1/suggestions/{args.id}", response_kind="suggestion"
|
|
638
|
+
)
|
|
639
|
+
if resource == "suggestion-attempts":
|
|
640
|
+
if operation == "create":
|
|
641
|
+
return client.request(
|
|
642
|
+
"POST", f"/v1/suggestions/{args.suggestion_id}/attempts",
|
|
643
|
+
body=_payload(args, "suggestion-attempts"), response_kind="attempt",
|
|
644
|
+
)
|
|
645
|
+
return client.request(
|
|
646
|
+
"GET", f"/v1/suggestion-attempts/{args.id}", response_kind="attempt"
|
|
647
|
+
)
|
|
648
|
+
if resource == "suggestion-feedback":
|
|
649
|
+
if operation == "create":
|
|
650
|
+
return client.request(
|
|
651
|
+
"POST", f"/v1/suggestion-attempts/{args.attempt_id}/feedback",
|
|
652
|
+
body=_payload(args, "suggestion-feedback"), response_kind="feedback",
|
|
653
|
+
)
|
|
654
|
+
if operation == "list":
|
|
655
|
+
return client.request(
|
|
656
|
+
"GET", f"/v1/suggestion-attempts/{args.attempt_id}/feedback",
|
|
657
|
+
params={"limit": args.limit, "offset": args.offset},
|
|
658
|
+
response_kind="feedback_list",
|
|
659
|
+
)
|
|
660
|
+
return client.request(
|
|
661
|
+
"GET", f"/v1/suggestion-feedback/{args.id}", response_kind="feedback"
|
|
662
|
+
)
|
|
663
|
+
if resource == "brews" and operation == "history":
|
|
664
|
+
return client.request(
|
|
665
|
+
"GET", f"/v1/coffees/{args.coffee_id}/brews",
|
|
666
|
+
params={"limit": args.limit, "offset": args.offset, "drink_type_id": args.drink_type_id}, response_kind="list",
|
|
667
|
+
)
|
|
668
|
+
if resource == "brews" and operation == "latest":
|
|
669
|
+
return client.request("GET", f"/v1/coffees/{args.coffee_id}/brews/latest")
|
|
670
|
+
if resource == "brews" and operation == "compare":
|
|
671
|
+
return client.request(
|
|
672
|
+
"GET", "/v1/brews/compare",
|
|
673
|
+
params={"left_id": args.left_id, "right_id": args.right_id},
|
|
674
|
+
response_kind="comparison",
|
|
675
|
+
)
|
|
676
|
+
if resource == "recipes" and operation in {"preview", "apply"}:
|
|
677
|
+
suffix = "preview" if operation == "preview" else "brews"
|
|
678
|
+
return client.request(
|
|
679
|
+
"POST", f"/v1/recipes/{args.id}/{suffix}",
|
|
680
|
+
body=_payload(args, "recipe-application"),
|
|
681
|
+
response_kind="preview" if operation == "preview" else "item",
|
|
682
|
+
expected_status=200 if operation == "preview" else 201,
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
if resource in RATING_RESOURCES:
|
|
686
|
+
parent_resource, parent_name = RATING_RESOURCES[resource]
|
|
687
|
+
if operation in {"create", "list"}:
|
|
688
|
+
parent_id = getattr(args, f"{parent_name}_id")
|
|
689
|
+
path = f"/v1/{parent_resource}/{parent_id}/ratings"
|
|
690
|
+
if operation == "create":
|
|
691
|
+
return client.request("POST", path, body=_payload(args, resource))
|
|
692
|
+
return client.request(
|
|
693
|
+
"GET", path, params={"limit": args.limit, "offset": args.offset},
|
|
694
|
+
response_kind="list",
|
|
695
|
+
)
|
|
696
|
+
path = f"/v1/{resource}/{args.id}"
|
|
697
|
+
else:
|
|
698
|
+
path = f"/v1/{resource}"
|
|
699
|
+
|
|
700
|
+
if operation == "create":
|
|
701
|
+
return client.request("POST", path, body=_payload(args, resource))
|
|
702
|
+
if operation == "list":
|
|
703
|
+
params = {
|
|
704
|
+
key: value for key, value in vars(args).items()
|
|
705
|
+
if key
|
|
706
|
+
not in {"resource", "operation", "api_url", "web_url", "timeout"}
|
|
707
|
+
}
|
|
708
|
+
return client.request("GET", path, params=params, response_kind="list")
|
|
709
|
+
item_path = f"{path}/{args.id}" if resource not in RATING_RESOURCES else path
|
|
710
|
+
if operation == "get":
|
|
711
|
+
return client.request("GET", item_path)
|
|
712
|
+
if operation == "update":
|
|
713
|
+
return client.request("PATCH", item_path, body=_payload(args, resource))
|
|
714
|
+
return client.request("DELETE", item_path)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def _write(value: Any, *, stream=None) -> None:
|
|
718
|
+
print(json.dumps(value, indent=2, ensure_ascii=False), file=stream or sys.stdout)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def main(argv: list[str] | None = None, *, client: ApiClient | None = None) -> int:
|
|
722
|
+
try:
|
|
723
|
+
args = build_parser().parse_args(argv)
|
|
724
|
+
if args.resource == "skills":
|
|
725
|
+
_write(install_skill(args.destination))
|
|
726
|
+
return 0
|
|
727
|
+
args.web_url = _web_origin(args.web_url)
|
|
728
|
+
selected_origin = ApiClient(args.api_url).base_url
|
|
729
|
+
if args.resource == "updates":
|
|
730
|
+
result = check_updates(client or ApiClient(selected_origin, timeout=args.timeout, proxy=args.proxy))
|
|
731
|
+
if args.claim_reminder:
|
|
732
|
+
result["reminder_due"] = False
|
|
733
|
+
if result["update_available"]:
|
|
734
|
+
try:
|
|
735
|
+
path = select_state_path(selected_origin, DEFAULT_API_URL, args.state_file)
|
|
736
|
+
result["reminder_due"] = claim_reminder(path)
|
|
737
|
+
except AuthStateError:
|
|
738
|
+
pass
|
|
739
|
+
_write(result)
|
|
740
|
+
return 0
|
|
741
|
+
if args.resource in {"login", "logout"}:
|
|
742
|
+
state_path = select_state_path(selected_origin, DEFAULT_API_URL, args.state_file)
|
|
743
|
+
state = AuthState(state_path, selected_origin)
|
|
744
|
+
if args.resource == "login":
|
|
745
|
+
try:
|
|
746
|
+
existing = state.read()
|
|
747
|
+
except SignInRequired:
|
|
748
|
+
existing = None
|
|
749
|
+
if existing is not None:
|
|
750
|
+
raise AuthStateError(
|
|
751
|
+
f"Already connected as {existing.username} to {existing.service_origin}; logout first"
|
|
752
|
+
)
|
|
753
|
+
flow = OAuthLogin(
|
|
754
|
+
selected_origin, state, proxy=args.proxy,
|
|
755
|
+
progress=lambda message: print(message, file=sys.stderr),
|
|
756
|
+
)
|
|
757
|
+
result = flow.device() if args.device else flow.loopback(open_browser=args.open_browser)
|
|
758
|
+
else:
|
|
759
|
+
confirmed = state.logout(local_only=args.local, proxy=args.proxy)
|
|
760
|
+
result = {
|
|
761
|
+
"local_binding_removed": True,
|
|
762
|
+
"remote_revocation_confirmed": confirmed,
|
|
763
|
+
}
|
|
764
|
+
if not confirmed and not args.local:
|
|
765
|
+
result["guidance"] = "Remote revocation is unconfirmed; check Connections on the website."
|
|
766
|
+
_write(result)
|
|
767
|
+
return 0
|
|
768
|
+
transport = client
|
|
769
|
+
if transport is None and args.resource == "status":
|
|
770
|
+
transport = ApiClient(selected_origin, timeout=args.timeout, proxy=args.proxy)
|
|
771
|
+
if transport is None:
|
|
772
|
+
access_override = os.environ.get("BREWSORTED_ACCESS_TOKEN") or None
|
|
773
|
+
configured_origin = os.environ.get("BREWSORTED_API_URL")
|
|
774
|
+
if (
|
|
775
|
+
access_override is not None
|
|
776
|
+
and configured_origin
|
|
777
|
+
and selected_origin != ApiClient(configured_origin).base_url
|
|
778
|
+
):
|
|
779
|
+
raise ValueError(
|
|
780
|
+
"API credential is bound to BREWSORTED_API_URL; "
|
|
781
|
+
"refusing a different --api-url origin"
|
|
782
|
+
)
|
|
783
|
+
if access_override is not None and configured_origin is None:
|
|
784
|
+
raise ValueError("BREWSORTED_ACCESS_TOKEN requires explicit BREWSORTED_API_URL")
|
|
785
|
+
state_file = args.state_file or os.environ.get("BREWSORTED_STATE_FILE")
|
|
786
|
+
selected_state_path = (
|
|
787
|
+
select_state_path(selected_origin, DEFAULT_API_URL, state_file)
|
|
788
|
+
if state_file or selected_origin == DEFAULT_API_URL else None
|
|
789
|
+
)
|
|
790
|
+
if access_override is not None:
|
|
791
|
+
transport = ApiClient(selected_origin, token=access_override, timeout=args.timeout, proxy=args.proxy)
|
|
792
|
+
elif selected_state_path is not None and selected_state_path.exists():
|
|
793
|
+
state = AuthState(selected_state_path, selected_origin)
|
|
794
|
+
binding = state.read()
|
|
795
|
+
|
|
796
|
+
def verified_access_token() -> str:
|
|
797
|
+
def verify_refreshed(token: str) -> None:
|
|
798
|
+
metadata = discover(selected_origin, proxy=args.proxy)
|
|
799
|
+
AccessTokenVerifier(metadata, proxy=args.proxy).verify(token, expected_subject=binding.subject)
|
|
800
|
+
|
|
801
|
+
return state.access_token(verify_access_token=verify_refreshed, proxy=args.proxy)
|
|
802
|
+
|
|
803
|
+
transport = ApiClient(
|
|
804
|
+
selected_origin, token_provider=verified_access_token,
|
|
805
|
+
timeout=args.timeout, proxy=args.proxy,
|
|
806
|
+
)
|
|
807
|
+
else:
|
|
808
|
+
raise SignInRequired(
|
|
809
|
+
"No local Connection exists; run brewsorted login"
|
|
810
|
+
)
|
|
811
|
+
result = _add_web_links(_dispatch(args, transport), args)
|
|
812
|
+
if args.resource in {"status", "context"}:
|
|
813
|
+
update = update_message(check_updates(transport))
|
|
814
|
+
if update is not None:
|
|
815
|
+
result = {**result, "client_update": update}
|
|
816
|
+
_write(result)
|
|
817
|
+
return 0
|
|
818
|
+
except SignInRequired as exc:
|
|
819
|
+
_write({"type": "about:blank", "title": "Sign-In Required", "status": 0,
|
|
820
|
+
"detail": str(exc), "code": "sign_in_required"}, stream=sys.stderr)
|
|
821
|
+
return 4
|
|
822
|
+
except IssuerUnavailable as exc:
|
|
823
|
+
_write({"type": "about:blank", "title": "Issuer Unavailable", "status": 0,
|
|
824
|
+
"detail": str(exc), "code": "issuer_unavailable"}, stream=sys.stderr)
|
|
825
|
+
return 3
|
|
826
|
+
except LoginDenied as exc:
|
|
827
|
+
_write({"type": "about:blank", "title": "Login Denied", "status": 0,
|
|
828
|
+
"detail": str(exc), "code": "login_denied"}, stream=sys.stderr)
|
|
829
|
+
return 4
|
|
830
|
+
except AuthStateError as exc:
|
|
831
|
+
_write({"type": "about:blank", "title": "OAuth State Error", "status": 0,
|
|
832
|
+
"detail": str(exc), "code": "oauth_state_error"}, stream=sys.stderr)
|
|
833
|
+
return 2
|
|
834
|
+
except (ValueError, OSError, json.JSONDecodeError) as exc:
|
|
835
|
+
_write({"type": "about:blank", "title": "CLI Input Error", "status": 0,
|
|
836
|
+
"detail": str(exc), "code": "cli_input_error"}, stream=sys.stderr)
|
|
837
|
+
return 2
|
|
838
|
+
except BackendUnavailable as exc:
|
|
839
|
+
_write({"type": "about:blank", "title": "Backend Unavailable", "status": 0,
|
|
840
|
+
"detail": str(exc), "code": "backend_unavailable"}, stream=sys.stderr)
|
|
841
|
+
return 3
|
|
842
|
+
except InvalidServerResponse as exc:
|
|
843
|
+
_write(exc.body, stream=sys.stderr)
|
|
844
|
+
return 6
|
|
845
|
+
except ApiError as exc:
|
|
846
|
+
_write(exc.body, stream=sys.stderr)
|
|
847
|
+
return 4 if exc.status < 500 else 5
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
if __name__ == "__main__":
|
|
851
|
+
raise SystemExit(main())
|