deliberaide-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,985 @@
1
+ from __future__ import annotations
2
+
3
+ import shlex
4
+ import sys
5
+ import time
6
+ import webbrowser
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from urllib.parse import urlparse
10
+ from typing import Any
11
+
12
+ import click
13
+ from websockets.sync.client import connect as websocket_connect
14
+
15
+ from deliberaide_cli import __version__
16
+ from deliberaide_cli.core.manifest import FieldSpec, OperationSpec, load_manifest
17
+ from deliberaide_cli.core.session import ProfileState, ProfileStore, normalize_base_url
18
+ from deliberaide_cli.utils.api_backend import ApiBackend, decode_response
19
+ from deliberaide_cli.utils.formatting import (
20
+ coerce_value,
21
+ json_dumps,
22
+ load_json_file,
23
+ load_text_file,
24
+ parse_assignment,
25
+ schema_template,
26
+ )
27
+ from deliberaide_cli.utils.repl_skin import ReplSkin
28
+
29
+
30
+ CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
31
+ DEFAULT_PROFILE = "default"
32
+ MANIFEST = load_manifest()
33
+
34
+
35
+ @dataclass(slots=True)
36
+ class CliRuntime:
37
+ manifest: Any
38
+ store: ProfileStore
39
+ profile: ProfileState
40
+ profile_name: str
41
+ backend: ApiBackend
42
+ json_output: bool
43
+ auto_refresh: bool
44
+
45
+ def save(self) -> None:
46
+ self.profile.base_url = normalize_base_url(self.profile.base_url)
47
+ self.profile.cookies = self.backend.export_cookies()
48
+ self.store.save(self.profile)
49
+
50
+ def reset_backend(self) -> None:
51
+ self.backend = ApiBackend(
52
+ self.profile.base_url,
53
+ self.profile.timeout_seconds,
54
+ cookies=self.profile.cookies,
55
+ )
56
+
57
+
58
+ def _coerce_generic_value(raw_value: str) -> Any:
59
+ lowered = raw_value.strip().lower()
60
+ if lowered in {"true", "false", "null"}:
61
+ return {"true": True, "false": False, "null": None}[lowered]
62
+ try:
63
+ return load_json_value(raw_value)
64
+ except Exception:
65
+ return raw_value
66
+
67
+
68
+ def load_json_value(raw_value: str) -> Any:
69
+ import json
70
+
71
+ return json.loads(raw_value)
72
+
73
+
74
+ def _ensure_runtime(ctx: click.Context, profile_name: str, base_url: str | None, timeout_seconds: float | None, json_output: bool, auto_refresh: bool) -> CliRuntime:
75
+ existing = ctx.obj if isinstance(ctx.obj, CliRuntime) else None
76
+ if existing is not None:
77
+ if base_url:
78
+ existing.profile.base_url = normalize_base_url(base_url)
79
+ existing.reset_backend()
80
+ if timeout_seconds is not None:
81
+ existing.profile.timeout_seconds = timeout_seconds
82
+ existing.reset_backend()
83
+ existing.json_output = json_output
84
+ existing.auto_refresh = auto_refresh
85
+ return existing
86
+
87
+ store = ProfileStore()
88
+ profile = store.load(profile_name)
89
+ if base_url:
90
+ profile.base_url = normalize_base_url(base_url)
91
+ if timeout_seconds is not None:
92
+ profile.timeout_seconds = timeout_seconds
93
+ backend = ApiBackend(profile.base_url, profile.timeout_seconds, cookies=profile.cookies)
94
+ runtime = CliRuntime(
95
+ manifest=MANIFEST,
96
+ store=store,
97
+ profile=profile,
98
+ profile_name=profile_name,
99
+ backend=backend,
100
+ json_output=json_output,
101
+ auto_refresh=auto_refresh,
102
+ )
103
+ return runtime
104
+
105
+
106
+ @click.group(invoke_without_command=True, context_settings=CONTEXT_SETTINGS)
107
+ @click.option("--profile", "profile_name", default=DEFAULT_PROFILE, show_default=True, help="Saved CLI profile to use.")
108
+ @click.option("--base-url", default=None, help="Override the saved API base URL for this run.")
109
+ @click.option("--timeout", "timeout_seconds", type=float, default=None, help="Request timeout in seconds.")
110
+ @click.option("--json", "json_output", is_flag=True, help="Emit machine-readable JSON envelopes.")
111
+ @click.option("--auto-refresh/--no-auto-refresh", default=True, show_default=True, help="Retry once after refreshing auth cookies on 401 responses.")
112
+ @click.pass_context
113
+ def cli(ctx: click.Context, profile_name: str, base_url: str | None, timeout_seconds: float | None, json_output: bool, auto_refresh: bool) -> None:
114
+ runtime = _ensure_runtime(ctx, profile_name, base_url, timeout_seconds, json_output, auto_refresh)
115
+ ctx.obj = runtime
116
+ if ctx.invoked_subcommand is None:
117
+ ctx.invoke(repl)
118
+
119
+
120
+ def _render_human(envelope: dict[str, Any]) -> None:
121
+ request = envelope["request"]
122
+ response = envelope["response"]
123
+ click.echo(f"{request['method']} {request['path']} -> {response['status_code']}")
124
+ if response.get("saved_to"):
125
+ click.echo(f"Saved to {response['saved_to']}")
126
+ body = response.get("body")
127
+ body_kind = response.get("body_kind")
128
+ if body is None:
129
+ return
130
+ if body_kind == "json":
131
+ click.echo(json_dumps(body))
132
+ return
133
+ if body_kind == "text":
134
+ click.echo(body)
135
+ return
136
+ click.echo(json_dumps(body))
137
+
138
+
139
+ def _emit_result(runtime: CliRuntime, envelope: dict[str, Any], success: bool) -> None:
140
+ if runtime.json_output:
141
+ click.echo(json_dumps(envelope, compact=True))
142
+ else:
143
+ _render_human(envelope)
144
+ if not success:
145
+ raise SystemExit(1)
146
+
147
+
148
+ def _binary_metadata(payload: bytes, content_type: str | None, filename: str | None, saved_to: str | None) -> dict[str, Any]:
149
+ return {
150
+ "content_type": content_type,
151
+ "filename": filename,
152
+ "size_bytes": len(payload),
153
+ "saved_to": saved_to,
154
+ }
155
+
156
+
157
+ def _save_binary(path_option: Path, default_name: str, payload: bytes) -> Path:
158
+ path = path_option
159
+ if path.exists() and path.is_dir():
160
+ path = path / default_name
161
+ path.parent.mkdir(parents=True, exist_ok=True)
162
+ path.write_bytes(payload)
163
+ return path
164
+
165
+
166
+ def _response_envelope(operation: OperationSpec, response: Any, decoded: Any, saved_to: str | None = None) -> dict[str, Any]:
167
+ if decoded.kind == "json":
168
+ body = decoded.value
169
+ elif decoded.kind == "text":
170
+ body = decoded.value
171
+ else:
172
+ body = _binary_metadata(decoded.value, decoded.content_type, decoded.filename, saved_to)
173
+
174
+ return {
175
+ "ok": response.is_success,
176
+ "operation": operation.operation_key,
177
+ "request": {
178
+ "method": operation.method,
179
+ "path": operation.path,
180
+ "url": str(response.request.url),
181
+ },
182
+ "response": {
183
+ "status_code": response.status_code,
184
+ "headers": dict(response.headers),
185
+ "body_kind": decoded.kind,
186
+ "body": body,
187
+ "saved_to": saved_to,
188
+ },
189
+ }
190
+
191
+
192
+ def _error_detail(decoded: Any) -> str:
193
+ if decoded.kind == "json":
194
+ if isinstance(decoded.value, dict) and "detail" in decoded.value:
195
+ return str(decoded.value["detail"])
196
+ return json_dumps(decoded.value)
197
+ if decoded.kind == "text":
198
+ return decoded.value.strip() or "Request failed"
199
+ return f"Binary error response ({decoded.content_type or 'unknown'})"
200
+
201
+
202
+ def _value_from_runtime(runtime: CliRuntime, raw_value: Any, name: str, required: bool) -> Any:
203
+ value = raw_value
204
+ if value in {None, ""}:
205
+ value = runtime.profile.defaults.get(name)
206
+ if value in {None, ""} and required:
207
+ raise click.ClickException(f"Missing required value: {name}")
208
+ return value
209
+
210
+
211
+ def _build_headers(runtime: CliRuntime, operation: OperationSpec, option_values: dict[str, Any], extra_headers: tuple[str, ...]) -> dict[str, str]:
212
+ headers: dict[str, str] = {}
213
+ for parameter in operation.header_parameters:
214
+ value = _value_from_runtime(runtime, option_values.get(parameter.cli_name), parameter.cli_name, parameter.required)
215
+ if value not in {None, ""}:
216
+ headers[parameter.name] = str(value)
217
+ for raw_header in extra_headers:
218
+ key, value = parse_assignment(raw_header)
219
+ headers[key] = value
220
+ return headers
221
+
222
+
223
+ def _build_path(runtime: CliRuntime, operation: OperationSpec, option_values: dict[str, Any]) -> str:
224
+ path = operation.path
225
+ for parameter in operation.path_parameters:
226
+ value = _value_from_runtime(runtime, option_values.get(parameter.cli_name), parameter.cli_name, parameter.required)
227
+ if value in {None, ""}:
228
+ continue
229
+ path = path.replace("{" + parameter.name + "}", str(value))
230
+ return path
231
+
232
+
233
+ def _build_query(runtime: CliRuntime, operation: OperationSpec, option_values: dict[str, Any]) -> dict[str, str] | None:
234
+ query: dict[str, str] = {}
235
+ for parameter in operation.query_parameters:
236
+ value = _value_from_runtime(runtime, option_values.get(parameter.cli_name), parameter.cli_name, parameter.required)
237
+ if value in {None, ""}:
238
+ continue
239
+ query[parameter.name] = str(value)
240
+ return query or None
241
+
242
+
243
+ def _extract_direct_body_values(body_bindings: dict[str, FieldSpec], option_values: dict[str, Any]) -> dict[str, Any]:
244
+ values: dict[str, Any] = {}
245
+ for internal_key, field in body_bindings.items():
246
+ raw_value = option_values.get(internal_key)
247
+ if raw_value in {None, ""} or raw_value == ():
248
+ continue
249
+ values[field.name] = raw_value
250
+ return values
251
+
252
+
253
+ def _build_json_body(body_spec: Any, direct_values: dict[str, Any], raw_body: str | None, body_file: Path | None, set_values: tuple[str, ...], set_files: tuple[str, ...]) -> Any:
254
+ if raw_body and body_file:
255
+ raise click.ClickException("Use either --body or --body-file, not both.")
256
+
257
+ payload = None
258
+ if body_file is not None:
259
+ payload = load_json_file(body_file)
260
+ elif raw_body is not None:
261
+ payload = load_json_value(raw_body)
262
+
263
+ if payload is None:
264
+ payload = {}
265
+
266
+ if direct_values or set_values or set_files:
267
+ if not isinstance(payload, dict):
268
+ raise click.ClickException("Direct field flags can only be used with object JSON bodies.")
269
+ for field in body_spec.fields:
270
+ if field.name not in direct_values:
271
+ continue
272
+ payload[field.name] = coerce_value(str(direct_values[field.name]), field.schema)
273
+ for raw_value in set_values:
274
+ key, value = parse_assignment(raw_value)
275
+ payload[key] = _coerce_generic_value(value)
276
+ for raw_value in set_files:
277
+ key, file_name = parse_assignment(raw_value)
278
+ payload[key] = load_json_file(Path(file_name))
279
+
280
+ if body_spec.required and payload is None:
281
+ raise click.ClickException("This route requires a JSON request body.")
282
+ if body_spec.required and payload == {} and not (direct_values or raw_body or body_file or set_values or set_files):
283
+ raise click.ClickException("This route requires a JSON request body.")
284
+ return payload
285
+
286
+
287
+ def _build_form_body(body_spec: Any, direct_values: dict[str, Any], set_values: tuple[str, ...], set_files: tuple[str, ...]) -> tuple[dict[str, str] | None, list[tuple[str, Path]] | None]:
288
+ data: dict[str, str] = {}
289
+ uploads: list[tuple[str, Path]] = []
290
+
291
+ for field in body_spec.fields:
292
+ if field.name not in direct_values:
293
+ continue
294
+ value = direct_values[field.name]
295
+ if field.is_file:
296
+ if field.allows_multiple:
297
+ for item in value:
298
+ uploads.append((field.name, item))
299
+ else:
300
+ uploads.append((field.name, value))
301
+ continue
302
+ data[field.name] = str(value)
303
+
304
+ for raw_value in set_values:
305
+ key, value = parse_assignment(raw_value)
306
+ data[key] = value
307
+ for raw_value in set_files:
308
+ key, file_name = parse_assignment(raw_value)
309
+ data[key] = load_text_file(Path(file_name))
310
+
311
+ if body_spec.required and not data and not uploads:
312
+ raise click.ClickException("This route requires form fields or file uploads.")
313
+ return data or None, uploads or None
314
+
315
+
316
+ def invoke_http_operation(runtime: CliRuntime, operation: OperationSpec, body_bindings: dict[str, FieldSpec], option_values: dict[str, Any]) -> None:
317
+ extra_headers = option_values.pop("extra_headers", ())
318
+ download = option_values.pop("download", None)
319
+ raw_body = option_values.pop("body", None)
320
+ body_file = option_values.pop("body_file", None)
321
+ set_values = option_values.pop("set_values", ())
322
+ set_files = option_values.pop("set_files", ())
323
+
324
+ path = _build_path(runtime, operation, option_values)
325
+ query = _build_query(runtime, operation, option_values)
326
+ headers = _build_headers(runtime, operation, option_values, extra_headers)
327
+ direct_values = _extract_direct_body_values(body_bindings, option_values)
328
+
329
+ json_body = None
330
+ data = None
331
+ uploads = None
332
+ if operation.request_body is not None:
333
+ if operation.request_body.is_json:
334
+ json_body = _build_json_body(operation.request_body, direct_values, raw_body, body_file, set_values, set_files)
335
+ elif operation.request_body.is_form:
336
+ if raw_body or body_file:
337
+ raise click.ClickException("Use field flags or --set for form routes, not --body/--body-file.")
338
+ data, uploads = _build_form_body(operation.request_body, direct_values, set_values, set_files)
339
+ elif operation.request_body.required:
340
+ raise click.ClickException("This route uses an unsupported request body content type.")
341
+ elif raw_body or body_file or set_values or set_files or direct_values:
342
+ raise click.ClickException("This route does not accept a request body.")
343
+
344
+ response = runtime.backend.request(
345
+ operation.method or "GET",
346
+ path,
347
+ params=query,
348
+ headers=headers,
349
+ json_body=json_body,
350
+ data=data,
351
+ uploads=uploads,
352
+ allow_refresh=runtime.auto_refresh,
353
+ )
354
+ runtime.save()
355
+
356
+ decoded = decode_response(response)
357
+ saved_to = None
358
+ if decoded.kind == "binary" and download is not None:
359
+ saved_path = _save_binary(download, decoded.filename or f"{operation.command_name}.bin", decoded.value)
360
+ saved_to = str(saved_path)
361
+ envelope = _response_envelope(operation, response, decoded, saved_to)
362
+ if not response.is_success:
363
+ if not runtime.json_output:
364
+ raise click.ClickException(_error_detail(decoded))
365
+ _emit_result(runtime, envelope, success=False)
366
+ return
367
+ _emit_result(runtime, envelope, success=True)
368
+
369
+
370
+ def invoke_websocket_operation(runtime: CliRuntime, operation: OperationSpec, option_values: dict[str, Any]) -> None:
371
+ extra_headers = option_values.pop("extra_headers", ())
372
+ messages = option_values.pop("messages", ())
373
+ json_messages = option_values.pop("json_messages", ())
374
+ receive_count = option_values.pop("receive_count", 1)
375
+ stdin_mode = option_values.pop("stdin_mode", False)
376
+
377
+ path = _build_path(runtime, operation, option_values)
378
+ query = _build_query(runtime, operation, option_values)
379
+ headers = _build_headers(runtime, operation, option_values, extra_headers)
380
+
381
+ cookie_header = "; ".join(
382
+ f"{cookie.name}={cookie.value}" for cookie in runtime.backend.export_cookies() if cookie.value
383
+ )
384
+ if cookie_header and "Cookie" not in headers:
385
+ headers["Cookie"] = cookie_header
386
+
387
+ url = runtime.backend.build_websocket_url(path, query)
388
+ received: list[str] = []
389
+ with websocket_connect(url, additional_headers=headers or None, open_timeout=runtime.profile.timeout_seconds) as websocket:
390
+ for message in messages:
391
+ websocket.send(message)
392
+ for raw_message in json_messages:
393
+ websocket.send(json_dumps(load_json_value(raw_message), compact=True))
394
+ if stdin_mode:
395
+ for line in sys.stdin:
396
+ websocket.send(line.rstrip("\n"))
397
+ for _ in range(max(receive_count, 0)):
398
+ received.append(websocket.recv())
399
+
400
+ envelope = {
401
+ "ok": True,
402
+ "operation": operation.operation_key,
403
+ "request": {
404
+ "method": "WEBSOCKET",
405
+ "path": operation.path,
406
+ "url": url,
407
+ },
408
+ "response": {
409
+ "status_code": 101,
410
+ "headers": headers,
411
+ "body_kind": "json" if runtime.json_output else "text",
412
+ "body": {"messages": received} if runtime.json_output else "\n".join(received),
413
+ "saved_to": None,
414
+ },
415
+ }
416
+ _emit_result(runtime, envelope, success=True)
417
+
418
+
419
+ @cli.group()
420
+ @click.pass_obj
421
+ def routes(runtime: CliRuntime) -> None:
422
+ """Inspect the generated route manifest."""
423
+
424
+
425
+ @routes.command("list")
426
+ @click.option("--group", "group_name", default=None, help="Filter by route group.")
427
+ @click.option("--kind", type=click.Choice(["http", "websocket", "all"]), default="all", show_default=True)
428
+ @click.pass_obj
429
+ def routes_list(runtime: CliRuntime, group_name: str | None, kind: str) -> None:
430
+ rows: list[dict[str, Any]] = []
431
+ for operation in runtime.manifest.all_operations:
432
+ if group_name and operation.group != group_name:
433
+ continue
434
+ if kind != "all" and operation.kind != kind:
435
+ continue
436
+ rows.append(
437
+ {
438
+ "operation": operation.operation_key,
439
+ "method": operation.method or "WS",
440
+ "path": operation.path,
441
+ "group": operation.group,
442
+ }
443
+ )
444
+ if runtime.json_output:
445
+ click.echo(json_dumps({"items": rows}, compact=True))
446
+ return
447
+ for row in rows:
448
+ click.echo(f"{row['operation']:<45} {row['method']:<6} {row['path']}")
449
+
450
+
451
+ @routes.command("show")
452
+ @click.argument("operation_key")
453
+ @click.pass_obj
454
+ def routes_show(runtime: CliRuntime, operation_key: str) -> None:
455
+ operation = runtime.manifest.find_operation(operation_key)
456
+ if operation is None:
457
+ raise click.ClickException(f"Unknown operation: {operation_key}")
458
+
459
+ payload = {
460
+ "operation": operation.operation_key,
461
+ "kind": operation.kind,
462
+ "group": operation.group,
463
+ "method": operation.method,
464
+ "path": operation.path,
465
+ "parameters": [
466
+ {
467
+ "name": item.name,
468
+ "cli_name": item.cli_name,
469
+ "location": item.location,
470
+ "required": item.required,
471
+ }
472
+ for item in operation.parameters
473
+ ],
474
+ "request_body": None,
475
+ }
476
+ if operation.request_body is not None:
477
+ payload["request_body"] = {
478
+ "required": operation.request_body.required,
479
+ "content_types": list(operation.request_body.content_types),
480
+ "fields": [
481
+ {
482
+ "name": item.name,
483
+ "cli_name": item.cli_name,
484
+ "required": item.required,
485
+ "is_file": item.is_file,
486
+ }
487
+ for item in operation.request_body.fields
488
+ ],
489
+ "template": schema_template(operation.request_body.schema),
490
+ }
491
+ if runtime.json_output:
492
+ click.echo(json_dumps(payload, compact=True))
493
+ return
494
+ click.echo(f"{operation.operation_key}\n{operation.method or 'WS'} {operation.path}")
495
+ if payload["parameters"]:
496
+ click.echo("Parameters:")
497
+ for item in payload["parameters"]:
498
+ required = "required" if item["required"] else "optional"
499
+ click.echo(f" --{item['cli_name'].replace('_', '-')} ({item['location']}, {required})")
500
+ if payload["request_body"] is not None:
501
+ click.echo("Request body:")
502
+ click.echo(json_dumps(payload["request_body"]))
503
+
504
+
505
+ @routes.command("search")
506
+ @click.argument("term")
507
+ @click.pass_obj
508
+ def routes_search(runtime: CliRuntime, term: str) -> None:
509
+ lowered = term.lower()
510
+ matches = [
511
+ operation for operation in runtime.manifest.all_operations
512
+ if lowered in operation.operation_key.lower() or lowered in operation.path.lower()
513
+ ]
514
+ payload = {
515
+ "count": len(matches),
516
+ "items": [
517
+ {
518
+ "operation": operation.operation_key,
519
+ "method": operation.method or "WS",
520
+ "path": operation.path,
521
+ }
522
+ for operation in matches
523
+ ],
524
+ }
525
+ if runtime.json_output:
526
+ click.echo(json_dumps(payload, compact=True))
527
+ return
528
+ for item in payload["items"]:
529
+ click.echo(f"{item['operation']:<45} {item['method']:<6} {item['path']}")
530
+
531
+
532
+ @cli.group()
533
+ @click.pass_obj
534
+ def profile(runtime: CliRuntime) -> None:
535
+ """Manage saved connection profiles."""
536
+
537
+
538
+ @profile.command("show")
539
+ @click.pass_obj
540
+ def profile_show(runtime: CliRuntime) -> None:
541
+ payload = {
542
+ "name": runtime.profile_name,
543
+ "base_url": runtime.profile.base_url,
544
+ "timeout_seconds": runtime.profile.timeout_seconds,
545
+ "defaults": runtime.profile.defaults,
546
+ "cookie_count": len(runtime.profile.cookies),
547
+ }
548
+ if runtime.json_output:
549
+ click.echo(json_dumps(payload, compact=True))
550
+ return
551
+ click.echo(json_dumps(payload))
552
+
553
+
554
+ @profile.command("list")
555
+ @click.pass_obj
556
+ def profile_list(runtime: CliRuntime) -> None:
557
+ payload = {"items": runtime.store.list_profiles()}
558
+ if runtime.json_output:
559
+ click.echo(json_dumps(payload, compact=True))
560
+ return
561
+ for item in payload["items"]:
562
+ click.echo(item)
563
+
564
+
565
+ @profile.command("set-base-url")
566
+ @click.argument("base_url")
567
+ @click.pass_obj
568
+ def profile_set_base_url(runtime: CliRuntime, base_url: str) -> None:
569
+ runtime.profile.base_url = normalize_base_url(base_url)
570
+ runtime.reset_backend()
571
+ runtime.save()
572
+ payload = {"ok": True, "base_url": runtime.profile.base_url}
573
+ if runtime.json_output:
574
+ click.echo(json_dumps(payload, compact=True))
575
+ return
576
+ click.echo(f"Base URL set to {runtime.profile.base_url}")
577
+
578
+
579
+ @profile.command("clear-cookies")
580
+ @click.pass_obj
581
+ def profile_clear_cookies(runtime: CliRuntime) -> None:
582
+ runtime.store.clear_cookies(runtime.profile)
583
+ runtime.reset_backend()
584
+ runtime.save()
585
+ payload = {"ok": True, "cookie_count": 0}
586
+ if runtime.json_output:
587
+ click.echo(json_dumps(payload, compact=True))
588
+ return
589
+ click.echo("Saved cookies cleared.")
590
+
591
+
592
+ @cli.group()
593
+ @click.pass_obj
594
+ def context(runtime: CliRuntime) -> None:
595
+ """Manage saved default identifiers and headers."""
596
+
597
+
598
+ @context.command("show")
599
+ @click.pass_obj
600
+ def context_show(runtime: CliRuntime) -> None:
601
+ payload = {"defaults": runtime.profile.defaults}
602
+ if runtime.json_output:
603
+ click.echo(json_dumps(payload, compact=True))
604
+ return
605
+ click.echo(json_dumps(payload))
606
+
607
+
608
+ @context.command("set")
609
+ @click.argument("key")
610
+ @click.argument("value")
611
+ @click.pass_obj
612
+ def context_set(runtime: CliRuntime, key: str, value: str) -> None:
613
+ runtime.store.set_default(runtime.profile, key, value)
614
+ runtime.save()
615
+ payload = {"ok": True, "defaults": runtime.profile.defaults}
616
+ if runtime.json_output:
617
+ click.echo(json_dumps(payload, compact=True))
618
+ return
619
+ click.echo(f"Saved {key}={value}")
620
+
621
+
622
+ @context.command("unset")
623
+ @click.argument("key")
624
+ @click.pass_obj
625
+ def context_unset(runtime: CliRuntime, key: str) -> None:
626
+ runtime.store.unset_default(runtime.profile, key)
627
+ runtime.save()
628
+ payload = {"ok": True, "defaults": runtime.profile.defaults}
629
+ if runtime.json_output:
630
+ click.echo(json_dumps(payload, compact=True))
631
+ return
632
+ click.echo(f"Removed {key}")
633
+
634
+
635
+ @context.command("clear")
636
+ @click.pass_obj
637
+ def context_clear(runtime: CliRuntime) -> None:
638
+ runtime.store.clear_defaults(runtime.profile)
639
+ runtime.save()
640
+ payload = {"ok": True, "defaults": runtime.profile.defaults}
641
+ if runtime.json_output:
642
+ click.echo(json_dumps(payload, compact=True))
643
+ return
644
+ click.echo("Saved defaults cleared.")
645
+
646
+
647
+ @context.command("undo")
648
+ @click.pass_obj
649
+ def context_undo(runtime: CliRuntime) -> None:
650
+ if not runtime.store.undo_defaults(runtime.profile):
651
+ raise click.ClickException("Nothing to undo.")
652
+ runtime.save()
653
+ payload = {"ok": True, "defaults": runtime.profile.defaults}
654
+ if runtime.json_output:
655
+ click.echo(json_dumps(payload, compact=True))
656
+ return
657
+ click.echo("Restored the previous saved-default state.")
658
+
659
+
660
+ @context.command("redo")
661
+ @click.pass_obj
662
+ def context_redo(runtime: CliRuntime) -> None:
663
+ if not runtime.store.redo_defaults(runtime.profile):
664
+ raise click.ClickException("Nothing to redo.")
665
+ runtime.save()
666
+ payload = {"ok": True, "defaults": runtime.profile.defaults}
667
+ if runtime.json_output:
668
+ click.echo(json_dumps(payload, compact=True))
669
+ return
670
+ click.echo("Re-applied the next saved-default state.")
671
+
672
+
673
+ @cli.command()
674
+ @click.pass_obj
675
+ def repl(runtime: CliRuntime) -> None:
676
+ """Start the interactive shell."""
677
+ history_path = runtime.store.home_dir / "history" / f"{runtime.profile_name}.txt"
678
+ skin = ReplSkin("deliberaide-cli", __version__, history_path)
679
+ session = skin.create_prompt_session()
680
+ skin.print_banner()
681
+ while True:
682
+ try:
683
+ line = skin.get_input(session, runtime.profile_name, runtime.profile.base_url)
684
+ except (EOFError, KeyboardInterrupt):
685
+ break
686
+ line = line.strip()
687
+ if not line:
688
+ continue
689
+ if line in {"exit", "quit"}:
690
+ break
691
+ try:
692
+ args = shlex.split(line)
693
+ cli.main(args=args, prog_name="deliberaide-cli", standalone_mode=False, obj=runtime)
694
+ except SystemExit as exc:
695
+ if exc.code not in {0, None}:
696
+ skin.error(f"Command failed with exit code {exc.code}")
697
+ except click.ClickException as exc:
698
+ skin.error(exc.format_message())
699
+ except Exception as exc:
700
+ skin.error(str(exc))
701
+ skin.print_goodbye()
702
+
703
+
704
+ def _store_cli_auth_tokens(
705
+ runtime: CliRuntime,
706
+ *,
707
+ access_cookie_name: str,
708
+ access_token: str,
709
+ refresh_cookie_name: str,
710
+ refresh_token: str,
711
+ ) -> None:
712
+ hostname = urlparse(runtime.profile.base_url).hostname or ""
713
+ runtime.backend.client.cookies.set(
714
+ access_cookie_name,
715
+ access_token,
716
+ domain=hostname,
717
+ path="/",
718
+ )
719
+ runtime.backend.client.cookies.set(
720
+ refresh_cookie_name,
721
+ refresh_token,
722
+ domain=hostname,
723
+ path="/",
724
+ )
725
+ runtime.save()
726
+
727
+
728
+ def _login_with_credentials(runtime: CliRuntime, email: str, password: str) -> None:
729
+ response = runtime.backend.request(
730
+ "POST",
731
+ "/api/v1/auth/login",
732
+ json_body={"email": email, "password": password},
733
+ allow_refresh=False,
734
+ )
735
+ runtime.save()
736
+ decoded = decode_response(response)
737
+ if not response.is_success:
738
+ raise click.ClickException(_error_detail(decoded))
739
+
740
+ if runtime.json_output:
741
+ _emit_result(
742
+ runtime,
743
+ _response_envelope(
744
+ OperationSpec(
745
+ kind="http",
746
+ group="auth",
747
+ command_name="login",
748
+ operation_key="auth.login",
749
+ method="POST",
750
+ path="/api/v1/auth/login",
751
+ route_name="login",
752
+ ),
753
+ response,
754
+ decoded,
755
+ ),
756
+ success=True,
757
+ )
758
+ return
759
+
760
+ click.echo("Signed in successfully.")
761
+
762
+
763
+ def _login_with_browser(
764
+ runtime: CliRuntime,
765
+ *,
766
+ open_browser: bool,
767
+ timeout_seconds: float,
768
+ poll_interval: float | None,
769
+ ) -> None:
770
+ start_response = runtime.backend.request(
771
+ "POST",
772
+ "/api/v1/auth/cli/sessions",
773
+ allow_refresh=False,
774
+ )
775
+ start_decoded = decode_response(start_response)
776
+ if not start_response.is_success:
777
+ raise click.ClickException(_error_detail(start_decoded))
778
+
779
+ payload = start_decoded.value
780
+ verification_url = payload["verification_url"]
781
+ poll_path = payload["poll_path"]
782
+ interval_seconds = float(payload.get("interval_seconds") or 2)
783
+ effective_interval = poll_interval if poll_interval is not None else interval_seconds
784
+
785
+ if open_browser:
786
+ webbrowser.open(verification_url, new=2)
787
+
788
+ if not runtime.json_output:
789
+ click.echo("Browser sign-in started.")
790
+ click.echo(f"Open this page if it does not launch automatically: {verification_url}")
791
+
792
+ deadline = time.time() + timeout_seconds
793
+ while time.time() < deadline:
794
+ poll_response = runtime.backend.request(
795
+ "GET",
796
+ poll_path,
797
+ allow_refresh=False,
798
+ )
799
+ poll_decoded = decode_response(poll_response)
800
+ if not poll_response.is_success:
801
+ raise click.ClickException(_error_detail(poll_decoded))
802
+
803
+ poll_payload = poll_decoded.value
804
+ status_value = poll_payload["status"]
805
+ if status_value == "approved":
806
+ _store_cli_auth_tokens(
807
+ runtime,
808
+ access_cookie_name=poll_payload["access_cookie_name"],
809
+ access_token=poll_payload["access_token"],
810
+ refresh_cookie_name=poll_payload["refresh_cookie_name"],
811
+ refresh_token=poll_payload["refresh_token"],
812
+ )
813
+ if runtime.json_output:
814
+ click.echo(json_dumps({
815
+ "ok": True,
816
+ "status": "approved",
817
+ "message": poll_payload.get("message"),
818
+ }, compact=True))
819
+ else:
820
+ click.echo("Browser sign-in completed.")
821
+ return
822
+ if status_value in {"expired", "not_found", "consumed"}:
823
+ raise click.ClickException(poll_payload.get("message") or "Browser sign-in did not complete.")
824
+ time.sleep(max(effective_interval, 0.2))
825
+
826
+ raise click.ClickException("Timed out waiting for browser sign-in approval.")
827
+
828
+
829
+ def _install_custom_auth_commands() -> None:
830
+ auth_group = cli.commands.get("auth")
831
+ if not isinstance(auth_group, click.Group):
832
+ return
833
+
834
+ auth_group.commands.pop("login", None)
835
+
836
+ @click.command("login")
837
+ @click.option("--email", default=None, help="Direct sign-in email. If omitted, browser sign-in is used.")
838
+ @click.option("--password", default=None, hide_input=True, help="Direct sign-in password.")
839
+ @click.option("--open-browser/--no-open-browser", default=True, show_default=True, help="Open the verification page automatically for browser sign-in.")
840
+ @click.option("--timeout-seconds", type=float, default=300.0, show_default=True, help="How long to wait for browser approval.")
841
+ @click.option("--poll-interval", type=float, default=None, help="Override the server-provided poll interval in seconds.")
842
+ @click.pass_obj
843
+ def auth_login(
844
+ runtime: CliRuntime,
845
+ email: str | None,
846
+ password: str | None,
847
+ open_browser: bool,
848
+ timeout_seconds: float,
849
+ poll_interval: float | None,
850
+ ) -> None:
851
+ if bool(email) != bool(password):
852
+ raise click.ClickException("Provide both --email and --password, or neither.")
853
+ if email and password:
854
+ _login_with_credentials(runtime, email, password)
855
+ return
856
+ _login_with_browser(
857
+ runtime,
858
+ open_browser=open_browser,
859
+ timeout_seconds=timeout_seconds,
860
+ poll_interval=poll_interval,
861
+ )
862
+
863
+ auth_group.add_command(auth_login)
864
+
865
+
866
+ def _parameter_help(parameter: Any) -> str:
867
+ required = "required" if parameter.required else "optional"
868
+ return f"{parameter.location} parameter ({required})"
869
+
870
+
871
+ def _field_help(field: FieldSpec) -> str:
872
+ required = "required" if field.required else "optional"
873
+ suffix = "file field" if field.is_file else "body field"
874
+ return f"{suffix} ({required})"
875
+
876
+
877
+ def build_http_command(operation: OperationSpec) -> click.Command:
878
+ params: list[click.Parameter] = []
879
+ existing_names: set[str] = set()
880
+ body_bindings: dict[str, FieldSpec] = {}
881
+
882
+ for parameter in operation.parameters:
883
+ option_name = f"--{parameter.cli_name.replace('_', '-')}"
884
+ params.append(
885
+ click.Option([option_name, parameter.cli_name], default=None, help=_parameter_help(parameter))
886
+ )
887
+ existing_names.add(parameter.cli_name)
888
+
889
+ if operation.request_body is not None:
890
+ for field in operation.request_body.fields:
891
+ internal_key = field.cli_name
892
+ option_label = field.cli_name
893
+ if option_label in existing_names:
894
+ internal_key = f"body__{field.cli_name}"
895
+ option_label = f"body-{field.cli_name}"
896
+ option_name = f"--{option_label.replace('_', '-')}"
897
+ kwargs: dict[str, Any] = {"default": None, "help": _field_help(field)}
898
+ if field.is_file:
899
+ kwargs["type"] = click.Path(exists=True, dir_okay=False, path_type=Path)
900
+ else:
901
+ kwargs["type"] = str
902
+ if field.allows_multiple:
903
+ kwargs["multiple"] = True
904
+ kwargs["default"] = ()
905
+ params.append(click.Option([option_name, internal_key], **kwargs))
906
+ body_bindings[internal_key] = field
907
+ existing_names.add(option_label)
908
+
909
+ params.extend(
910
+ [
911
+ click.Option(["--body", "body"], default=None, help="Raw JSON request body."),
912
+ click.Option(["--body-file", "body_file"], type=click.Path(exists=True, dir_okay=False, path_type=Path), default=None, help="Load a JSON request body from a file."),
913
+ click.Option(["--set", "set_values"], multiple=True, help="Set a top-level request field as KEY=VALUE."),
914
+ click.Option(["--set-file", "set_files"], multiple=True, help="Set a top-level request field from a file as KEY=PATH."),
915
+ click.Option(["--header", "extra_headers"], multiple=True, help="Add a request header as KEY=VALUE."),
916
+ click.Option(["--download", "download"], type=click.Path(path_type=Path), default=None, help="Save a binary response to a file path."),
917
+ ]
918
+ )
919
+
920
+ @click.pass_obj
921
+ def callback(runtime: CliRuntime, **kwargs: Any) -> None:
922
+ invoke_http_operation(runtime, operation, body_bindings, kwargs)
923
+
924
+ return click.Command(
925
+ operation.command_name,
926
+ params=params,
927
+ callback=callback,
928
+ help=f"{operation.method} {operation.path}",
929
+ )
930
+
931
+
932
+ def build_websocket_command(operation: OperationSpec) -> click.Command:
933
+ params: list[click.Parameter] = []
934
+ for parameter in operation.parameters:
935
+ option_name = f"--{parameter.cli_name.replace('_', '-')}"
936
+ params.append(
937
+ click.Option([option_name, parameter.cli_name], default=None, help=_parameter_help(parameter))
938
+ )
939
+
940
+ params.extend(
941
+ [
942
+ click.Option(["--message", "messages"], multiple=True, help="Send a raw text message after connecting."),
943
+ click.Option(["--message-json", "json_messages"], multiple=True, help="Send a JSON-encoded message after connecting."),
944
+ click.Option(["--receive", "receive_count"], type=int, default=1, show_default=True, help="How many messages to read before closing."),
945
+ click.Option(["--stdin", "stdin_mode"], is_flag=True, help="Read outgoing messages from stdin until EOF."),
946
+ click.Option(["--header", "extra_headers"], multiple=True, help="Add a WebSocket header as KEY=VALUE."),
947
+ ]
948
+ )
949
+
950
+ @click.pass_obj
951
+ def callback(runtime: CliRuntime, **kwargs: Any) -> None:
952
+ invoke_websocket_operation(runtime, operation, kwargs)
953
+
954
+ return click.Command(
955
+ operation.command_name,
956
+ params=params,
957
+ callback=callback,
958
+ help=f"WS {operation.path}",
959
+ )
960
+
961
+
962
+ def register_dynamic_commands(root: click.Group) -> None:
963
+ groups: dict[str, click.Group] = {}
964
+ for operation in MANIFEST.http_operations:
965
+ group = groups.setdefault(operation.group, click.Group(operation.group))
966
+ group.add_command(build_http_command(operation))
967
+ ws_group = click.Group("ws")
968
+ for operation in MANIFEST.websocket_operations:
969
+ ws_group.add_command(build_websocket_command(operation))
970
+ groups["ws"] = ws_group
971
+ for name, group in sorted(groups.items()):
972
+ if name not in root.commands:
973
+ root.add_command(group)
974
+
975
+
976
+ register_dynamic_commands(cli)
977
+ _install_custom_auth_commands()
978
+
979
+
980
+ def main() -> None:
981
+ cli.main(prog_name="deliberaide-cli")
982
+
983
+
984
+ if __name__ == "__main__":
985
+ main()