ms-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.
Files changed (67) hide show
  1. ad_cli/__init__.py +6 -0
  2. ad_cli/__main__.py +6 -0
  3. ad_cli/auth.py +351 -0
  4. ad_cli/cli.py +278 -0
  5. ad_cli/discovery.py +243 -0
  6. ad_cli/dynamic.py +816 -0
  7. ad_cli/errors.py +45 -0
  8. ad_cli/http.py +424 -0
  9. ad_cli/invoke.py +652 -0
  10. ad_cli/main.py +703 -0
  11. cann_cli/__init__.py +6 -0
  12. cann_cli/__main__.py +6 -0
  13. cann_cli/auth.py +351 -0
  14. cann_cli/cli.py +278 -0
  15. cann_cli/discovery.py +243 -0
  16. cann_cli/dynamic.py +816 -0
  17. cann_cli/errors.py +45 -0
  18. cann_cli/http.py +424 -0
  19. cann_cli/invoke.py +652 -0
  20. cann_cli/main.py +703 -0
  21. ms_cli/__init__.py +6 -0
  22. ms_cli/__main__.py +6 -0
  23. ms_cli/auth.py +351 -0
  24. ms_cli/cli.py +278 -0
  25. ms_cli/discovery.py +243 -0
  26. ms_cli/dynamic.py +816 -0
  27. ms_cli/errors.py +45 -0
  28. ms_cli/http.py +424 -0
  29. ms_cli/invoke.py +652 -0
  30. ms_cli/main.py +703 -0
  31. ms_cli-0.2.0.dist-info/METADATA +444 -0
  32. ms_cli-0.2.0.dist-info/RECORD +67 -0
  33. ms_cli-0.2.0.dist-info/WHEEL +5 -0
  34. ms_cli-0.2.0.dist-info/entry_points.txt +2 -0
  35. ms_cli-0.2.0.dist-info/licenses/LICENSE +18 -0
  36. ms_cli-0.2.0.dist-info/top_level.txt +5 -0
  37. oed_cli/__init__.py +6 -0
  38. oed_cli/__main__.py +6 -0
  39. oed_cli/auth.py +1629 -0
  40. oed_cli/cli.py +297 -0
  41. oed_cli/defaults.toml +44 -0
  42. oed_cli/discovery.py +243 -0
  43. oed_cli/dynamic.py +816 -0
  44. oed_cli/errors.py +45 -0
  45. oed_cli/http.py +423 -0
  46. oed_cli/invoke.py +651 -0
  47. oed_cli/main.py +782 -0
  48. ogd_cli/__init__.py +6 -0
  49. ogd_cli/__main__.py +6 -0
  50. ogd_cli/auth.py +351 -0
  51. ogd_cli/cli.py +278 -0
  52. ogd_cli/discovery.py +243 -0
  53. ogd_cli/dynamic.py +816 -0
  54. ogd_cli/errors.py +45 -0
  55. ogd_cli/http.py +424 -0
  56. ogd_cli/invoke.py +652 -0
  57. ogd_cli/main.py +703 -0
  58. oud_cli/__init__.py +6 -0
  59. oud_cli/__main__.py +6 -0
  60. oud_cli/auth.py +351 -0
  61. oud_cli/cli.py +278 -0
  62. oud_cli/discovery.py +243 -0
  63. oud_cli/dynamic.py +816 -0
  64. oud_cli/errors.py +45 -0
  65. oud_cli/http.py +424 -0
  66. oud_cli/invoke.py +652 -0
  67. oud_cli/main.py +703 -0
oud_cli/invoke.py ADDED
@@ -0,0 +1,652 @@
1
+ """Run a real :class:`Operation` against its backend.
2
+
3
+ This module is what the CLI dispatches to when a user runs
4
+ ``oud <service> <method> --params ... --json ...``. It fills path/query
5
+ params on the OpenAPI ``paths`` template, attaches the JSON body, and
6
+ sends the request through the production gateway via
7
+ ``oud_cli.http.get_request``.
8
+
9
+ URL construction note: the spec's ``x-apigateway-backend.httpEndpoints``
10
+ block is parsed for ``method`` / ``scheme`` but **not** trusted for the
11
+ host — those ``address`` values are routinely staging hosts
12
+ (``*.test.osinfra.cn``) that CloudWAF blocks. The runtime URL is built
13
+ as ``op.base_url + op.path``, where ``op.base_url`` was filled in by
14
+ :func:`oud_cli.dynamic.resolve_runtime_gateway` from the discovery feed
15
+ (``ServiceMeta.base_url``). ``op.path`` is the OpenAPI ``paths`` key
16
+ (e.g. ``/cve-security-notice-server/securitynotice/getByCveId``).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import datetime as _dt
22
+ from typing import Any
23
+ from urllib.parse import urlparse
24
+
25
+ import httpx
26
+
27
+ from . import http as http_mod
28
+ from .auth import read_token
29
+ from .discovery import current_community
30
+ from .dynamic import Operation, coerce_param_types, to_flag
31
+ from .errors import NetworkError, UpstreamError, UserError
32
+ from .http import _is_waf_block, _resolve_user_agent
33
+
34
+ # Header values that carry the bearer token / session cookie are redacted in
35
+ # any *echoed* request view (``--dry-run`` and ``include_request``). The real
36
+ # values still go out on the wire — only the round-trip-to-terminal copy is
37
+ # masked, so a shared log / CI trace never leaks a live credential. The scheme
38
+ # (``Bearer``) is kept so the viewer can still tell which auth style is in use.
39
+ _ECHO_REDACTED_HEADERS = {"authorization", "cookie"}
40
+
41
+
42
+ def _mask_echo_headers(headers: dict[str, str]) -> dict[str, str]:
43
+ """Return a copy of ``headers`` with credential-bearing values redacted.
44
+
45
+ ``Authorization: Bearer <token>`` → ``Authorization: Bearer <stored>`` and
46
+ ``Cookie: <cookie>`` → ``Cookie: <stored>``. Other headers pass through.
47
+ Only used to build the echoed request view, never the on-the-wire request.
48
+ """
49
+
50
+ masked: dict[str, str] = {}
51
+ for name, value in headers.items():
52
+ if name.lower() in _ECHO_REDACTED_HEADERS:
53
+ if name.lower() == "authorization" and value.lower().startswith("bearer "):
54
+ masked[name] = "Bearer <stored>"
55
+ else:
56
+ masked[name] = "<stored>"
57
+ else:
58
+ masked[name] = value
59
+ return masked
60
+
61
+
62
+ def _fill_path(template: str, params: dict[str, Any]) -> tuple[str, list[str]]:
63
+ """Substitute ``{name}`` placeholders in ``template`` from ``params``.
64
+
65
+ Returns the rendered path and the list of placeholder names that were
66
+ not provided, so the caller can raise a precise error.
67
+
68
+ Huawei APIG marks required path params with a trailing ``+`` in the
69
+ template (``/t/{id+}``); the ``+`` is a spec-side marker that never
70
+ appears in the real request URL or in the declared
71
+ ``parameters[].name``. Strip it so the lookup matches what the
72
+ caller actually provided under ``--<flag>`` / ``--params``.
73
+ """
74
+
75
+ missing: list[str] = []
76
+ parts: list[str] = []
77
+ rest = template
78
+ while True:
79
+ head, sep, chunk = rest.partition("{")
80
+ if not sep:
81
+ parts.append(head)
82
+ break
83
+ name_end = chunk.find("}")
84
+ if name_end == -1:
85
+ parts.append(head + sep + chunk)
86
+ break
87
+ raw_name = chunk[:name_end]
88
+ name = raw_name.rstrip("+")
89
+ parts.append(head)
90
+ if name in params:
91
+ parts.append(str(params[name]))
92
+ else:
93
+ missing.append(name)
94
+ parts.append("{" + raw_name + "}")
95
+ rest = chunk[name_end + 1 :]
96
+ return "".join(parts), missing
97
+
98
+
99
+ def _select_params(
100
+ op: Operation, raw: dict[str, Any] | None
101
+ ) -> tuple[dict, dict, list[str]]:
102
+ """Split ``raw`` into (path_params, query_params, unused_keys)."""
103
+
104
+ raw = raw or {}
105
+ path_names = {p["name"] for p in op.path_params}
106
+ query_names = {p.get("name") for p in op.query_params}
107
+ declared = path_names | query_names
108
+
109
+ path_params = {k: raw[k] for k in path_names if k in raw}
110
+ query_params = {k: raw[k] for k in raw if k in query_names and k not in path_params}
111
+ unused = sorted(k for k in raw if k not in declared)
112
+ return path_params, query_params, unused
113
+
114
+
115
+ def _body_field_summary(
116
+ schema: dict[str, Any] | None,
117
+ ) -> list[dict[str, Any]]:
118
+ """Project a resolved body schema down to ``[{name, type, required}]``.
119
+
120
+ Listing views use this so the per-operation summary stays compact
121
+ while still telling an agent which fields exist and which are
122
+ mandatory. The full schema is exposed separately under
123
+ ``body_schema`` on ``oud <service> <op> --help``.
124
+ """
125
+
126
+ if not isinstance(schema, dict):
127
+ return []
128
+ properties = schema.get("properties") or {}
129
+ required = set(schema.get("required") or [])
130
+ out: list[dict[str, Any]] = []
131
+ for name, prop in properties.items():
132
+ if not isinstance(prop, dict):
133
+ continue
134
+ entry: dict[str, Any] = {
135
+ "name": name,
136
+ "type": prop.get("type", "object"),
137
+ "required": name in required,
138
+ }
139
+ if prop.get("description"):
140
+ entry["description"] = prop["description"]
141
+ out.append(entry)
142
+ return out
143
+
144
+
145
+ def _render_response(resp: httpx.Response) -> Any:
146
+ """Parse the JSON body of ``resp``, returning a wrapped string for non-JSON.
147
+
148
+ Non-JSON bodies (HTML WAF block page, plain-text traceback, gateway
149
+ maintenance page) are surfaced verbatim under ``_non_json_body`` so
150
+ agents can read the full error instead of guessing. The body goes on
151
+ stdout as JSON, so callers piping through ``| jq`` still see one
152
+ well-formed JSON object per command.
153
+ """
154
+
155
+ if not resp.content:
156
+ return None
157
+ try:
158
+ return resp.json()
159
+ except Exception:
160
+ return {
161
+ "_non_json_body": resp.text,
162
+ "_content_type": resp.headers.get("content-type", ""),
163
+ }
164
+
165
+
166
+ # Api-Key / Api-Username are Discourse auth headers that the gateway (APIG)
167
+ # injects during its header conversion. oud must neither send them nor let
168
+ # callers supply them — surfacing them makes agents hunt for credentials that
169
+ # are already handled upstream.
170
+ GATEWAY_MANAGED_PARAMS = frozenset({"Api-Key", "Api-Username"})
171
+
172
+
173
+ def _reject_gateway_managed_params(params: dict[str, Any] | None) -> None:
174
+ """Refuse Api-Key / Api-Username supplied by the caller.
175
+
176
+ ``forum`` authenticates at the gateway layer; the spec still declares
177
+ these as required header params, so agents reading the raw spec keep
178
+ trying to "fill" them. An explicit error is the strongest signal that
179
+ the value is injected upstream and must not be supplied.
180
+ """
181
+
182
+ supplied = sorted(k for k in (params or {}) if k in GATEWAY_MANAGED_PARAMS)
183
+ if not supplied:
184
+ return
185
+ raise UserError(
186
+ f"{', '.join(supplied)} are injected by the gateway and must not be supplied",
187
+ kind="gateway_managed_param",
188
+ hint=(
189
+ "Api-Key / Api-Username are auto-filled by oud as placeholder "
190
+ "headers on every forum call, then converted by the gateway — "
191
+ "do not supply them."
192
+ ),
193
+ )
194
+
195
+
196
+ def _inject_ag_token(op: Operation, query_params: dict[str, Any]) -> None:
197
+ """Auto-fill the ``access_token`` query param for AtomGit operations.
198
+
199
+ ``ag`` authenticates every request through the ``access_token`` query
200
+ parameter declared on its spec (用户授权码). When the caller didn't
201
+ pass one explicitly, fall back to the locally stored token from
202
+ ``oud ag login``. A required token that isn't available anywhere
203
+ raises a hint instead of failing inside the gateway; optional ones
204
+ simply go without.
205
+ """
206
+
207
+ declared = next(
208
+ (p for p in op.query_params if p.get("name") == "access_token"), None
209
+ )
210
+ if op.service_name != "ag" or declared is None or "access_token" in query_params:
211
+ return
212
+ token = read_token("ag")
213
+ if token:
214
+ query_params["access_token"] = token
215
+ elif declared.get("required"):
216
+ raise UserError(
217
+ "this AtomGit operation requires an access_token",
218
+ kind="ag_token_missing",
219
+ hint="Store one with `oud ag login`, or pass `--access-token <pat>`.",
220
+ )
221
+
222
+
223
+ def _normalize_result_root(op: Operation, path_params: dict[str, Any]) -> list[str]:
224
+ """Auto-fix the ``eulermaker getJobLog`` ``result_root`` path param.
225
+
226
+ The jobs search API returns ``result_root`` as a relative path that the
227
+ spec requires to end with ``/dmesg``. Agents routinely pass the raw value
228
+ (missing the trailing ``/dmesg``) and often prepend a stray ``/``. Only
229
+ this one known param is rewritten — no other call is silently mutated.
230
+ Returns human-readable notes describing each applied fix.
231
+ """
232
+ # TODO: upgrade to a parameter-correction module so this becomes a generic
233
+ # hook instead of a hard-coded special case for eulermaker.getJobLog.
234
+ if op.service_name != "eulermaker" or op.operation_id != "getJobLog":
235
+ return []
236
+ value = path_params.get("result_root")
237
+ if not isinstance(value, str):
238
+ return []
239
+ notes: list[str] = []
240
+ fixed = value.lstrip("/")
241
+ if fixed != value:
242
+ notes.append("result_root: stripped leading '/'")
243
+ if not fixed.endswith("/dmesg"):
244
+ fixed += "/dmesg"
245
+ notes.append("result_root: appended '/dmesg'")
246
+ if fixed != value:
247
+ path_params["result_root"] = fixed
248
+ return notes
249
+
250
+
251
+ def _reject_body_fields_via_params(op: Operation, unused: list[str]) -> None:
252
+ """Turn a common misuse into an actionable error instead of an opaque 400.
253
+
254
+ ``--params`` only carries query/path parameters. Body fields passed that
255
+ way land in ``unused`` and the request goes out with ``body: null``, which
256
+ the gateway rejects with a generic 400. When those keys line up with the
257
+ operation's request-body schema, raise a hint that names the right flag.
258
+ """
259
+
260
+ if op.body_schema is None or not unused:
261
+ return
262
+ body_props = set(op.body_schema.get("properties") or {})
263
+ body_keys = sorted(k for k in unused if k in body_props)
264
+ if not body_keys:
265
+ return
266
+ raise UserError(
267
+ f"{', '.join(body_keys)} match request-body fields for this operation "
268
+ "but no body was sent",
269
+ kind="body_fields_via_params",
270
+ hint=(
271
+ "`--params` only covers query/path parameters; request bodies go "
272
+ f"through `--json '{{...}}'`. See `oud <service> {op.display_name} --help`."
273
+ ),
274
+ )
275
+
276
+
277
+ def _reject_insecure_base_url(base_url: str) -> None:
278
+ """Raise if ``base_url`` has an explicit non-https scheme.
279
+
280
+ A poisoned discovery cache could set ``base_url`` to ``http://...``, which
281
+ would exfiltrate the Bearer token / ag PAT over plaintext (issue #22).
282
+ An empty / scheme-less value (legacy ``$APIG_GROUP_ENTRY_URL`` placeholder
283
+ or an empty feed entry) is intentionally NOT rejected — it flows through
284
+ and fails at HTTP time per the ``resolve_runtime_gateway`` contract.
285
+ """
286
+
287
+ scheme = urlparse(base_url or "").scheme.lower()
288
+ if scheme and scheme != "https":
289
+ raise UserError(
290
+ f"runtime base_url uses insecure scheme '{scheme}://': {base_url!r}",
291
+ kind="insecure_base_url",
292
+ hint=(
293
+ "The local discovery cache may be poisoned. Run "
294
+ "`oud cache clear` then retry to refetch the gateway feed."
295
+ ),
296
+ )
297
+
298
+
299
+ def call_operation(
300
+ op: Operation,
301
+ *,
302
+ params: dict[str, Any] | None = None,
303
+ body: Any = None,
304
+ dry_run: bool = False,
305
+ timeout: float = 30.0,
306
+ include_request: bool = False,
307
+ user_agent: str | None = None,
308
+ token: str | None = None,
309
+ cookie: str | None = None,
310
+ ) -> dict[str, Any]:
311
+ """Invoke ``op`` and return a structured JSON dict suitable for stdout.
312
+
313
+ ``ok`` is ``True`` for any 2xx/3xx response. Non-success still surfaces
314
+ the body and status under ``response`` / ``status``; the caller is
315
+ responsible for the exit code.
316
+
317
+ ``user_agent`` overrides the default User-Agent header; falls back to
318
+ ``OUD_USER_AGENT`` env, then the bundled default.
319
+
320
+ ``token`` adds an ``Authorization: Bearer <token>`` header (only when set).
321
+ ``cookie`` adds a ``Cookie: <cookie>`` header (only when set). Both flow
322
+ into the request envelope (and the ``dry_run`` view) the same way
323
+ ``user_agent`` does.
324
+ """
325
+
326
+ path_params, query_params, unused = _select_params(op, params)
327
+ _reject_gateway_managed_params(params)
328
+ query_params = coerce_param_types(op, query_params)
329
+ param_corrections = _normalize_result_root(op, path_params)
330
+ if body is None:
331
+ _reject_body_fields_via_params(op, unused)
332
+ # An operation that declares a JSON requestBody expects a JSON body on
333
+ # the wire. When the caller omits ``--json`` (body optional, or
334
+ # required and the backend will surface the missing-field error), fall
335
+ # back to an empty object so the request still carries
336
+ # ``Content-Type: application/json``. Without it the APIG gateway
337
+ # rejects bodyless POSTs whose API definition declares an
338
+ # ``application/json`` body with ``APIG.0602 invalid content type``.
339
+ if op.body_schema is not None:
340
+ body = {}
341
+
342
+ filled_path, missing = _fill_path(op.path, path_params)
343
+ if missing:
344
+ raise UserError(
345
+ f"missing path params: {missing}",
346
+ kind="missing_path_param",
347
+ hint=f"Provide them via --params: {', '.join(missing)}",
348
+ )
349
+
350
+ query_params = {k: v for k, v in query_params.items() if v is not None}
351
+ _inject_ag_token(op, query_params)
352
+ url = f"{op.base_url}{filled_path}"
353
+
354
+ # Cache-poisoning guard (issue #22): the discovery feed's ``base_url`` is
355
+ # the sole source of the runtime host, so a poisoned cache that rewrites
356
+ # it to ``http://evil.com`` would exfiltrate the Bearer token / ag PAT in
357
+ # plaintext (httpx sends over http://). Reject any non-empty, non-https
358
+ # scheme here. An empty scheme (legacy ``$APIG_GROUP_ENTRY_URL`` placeholder
359
+ # / empty feed value) is left to fail at HTTP time per the
360
+ # ``resolve_runtime_gateway`` passthrough contract — only an explicit
361
+ # insecure scheme is hard-rejected, never silently rewritten.
362
+ _reject_insecure_base_url(op.base_url)
363
+
364
+ # Resolve user_agent once so both the request envelope and the HTTP layer
365
+ # see the same final value (no flag → env → default).
366
+ user_agent = _resolve_user_agent(user_agent)
367
+
368
+ # Discourse (forum) authenticates via Api-Key / Api-Username headers. oud
369
+ # fills them with the gateway's expected placeholder — the APIG header
370
+ # conversion swaps them for the real credentials at the edge, so oud MUST
371
+ # send them or the gateway rejects the call. Callers never supply values
372
+ # themselves; _reject_gateway_managed_params enforces that.
373
+ api_headers: dict[str, str] = {}
374
+ if op.service_name == "forum":
375
+ api_headers = {"Api-Key": "oud-placeholder", "Api-Username": "oud-placeholder"}
376
+
377
+ request_headers: dict[str, str] = {"User-Agent": user_agent, **api_headers}
378
+ if token:
379
+ request_headers["Authorization"] = f"Bearer {token}"
380
+ # Plaintext identity/routing headers for the APIG custom-auth flow.
381
+ # NOT a secret — ``source`` declares the calling client, ``target``
382
+ # tells APIG which per-service header rewrite to apply, and
383
+ # ``community`` selects the per-community backend credentials (e.g.
384
+ # the etherpad api key map). Names are deliberately community-agnostic
385
+ # so all community CLIs (oud / oed / ogd / ad / cann) emit the same
386
+ # contract. Emitted for ALL service calls (token present or not):
387
+ # anonymous services like etherpad rely on ``x-community`` for the
388
+ # gateway to pick the pre-configured per-community api key — without
389
+ # it the gateway returns 401. Authorization (when a token is sent) is
390
+ # done by the Bearer token + server-side role lookup; the previous
391
+ # HMAC-signed ``x-secret-token`` was removed (a secret shipped in a
392
+ # distributed CLI cannot be kept secret). Only emitted when
393
+ # service_name is meaningful (empty = discovery / spec fetch — public).
394
+ if op.service_name:
395
+ request_headers["x-source"] = "oud-cli"
396
+ request_headers["x-target"] = op.service_name
397
+ request_headers["x-community"] = current_community()
398
+ if cookie:
399
+ request_headers["Cookie"] = cookie
400
+ if body is not None:
401
+ request_headers["Content-Type"] = "application/json"
402
+ # Mask credentials in any echoed request view (dry-run / include_request):
403
+ # the real token still goes out on the wire, it just never round-trips
404
+ # back to the terminal. ``query.access_token`` (ag PAT passed as a param)
405
+ # and the credential-bearing headers (Authorization / Cookie) are both
406
+ # redacted — the previous version masked the query but leaked the
407
+ # ``Authorization: Bearer <token>`` header verbatim into --dry-run output.
408
+ request_view: dict[str, Any] = {
409
+ "method": op.backend.method,
410
+ "url": url,
411
+ "query": {
412
+ k: ("<stored>" if k == "access_token" else v) for k, v in query_params.items()
413
+ },
414
+ "headers": _mask_echo_headers({**request_headers, **api_headers}),
415
+ "body": body,
416
+ }
417
+
418
+ if dry_run:
419
+ out = {
420
+ "ok": True,
421
+ "dry_run": True,
422
+ "service": op.service_name,
423
+ "operation": op.display_name,
424
+ "method": op.backend.method,
425
+ "url": url,
426
+ "request": request_view,
427
+ "note": "request was not sent.",
428
+ }
429
+ if op.display_name != op.operation_id:
430
+ out["operation_id_raw"] = op.operation_id
431
+ if param_corrections:
432
+ out["param_corrections"] = param_corrections
433
+ return out
434
+
435
+ resp = http_mod.get_request(
436
+ op.backend.method,
437
+ url,
438
+ params=query_params if query_params else None,
439
+ body=body,
440
+ headers=api_headers,
441
+ timeout=timeout,
442
+ user_agent=user_agent,
443
+ token=token,
444
+ cookie=cookie,
445
+ service_name=op.service_name,
446
+ )
447
+
448
+ if _is_waf_block(resp.text):
449
+ raise NetworkError(
450
+ f"Backend WAF blocked {op.backend.method} {url}",
451
+ kind="waf_block",
452
+ hint=(
453
+ "Some APIG backends reject the bundled oud/x.y.z User-Agent. "
454
+ "Retry with `--user-agent 'Mozilla/5.0 ...'` or set "
455
+ "OUD_USER_AGENT in the environment."
456
+ ),
457
+ )
458
+
459
+ if resp.status_code == 401:
460
+ raise UpstreamError(
461
+ f"{op.backend.method} {url} returned 401",
462
+ kind="unauthorized",
463
+ hint=(
464
+ "Backend returned 401. If this operation takes a token, run "
465
+ "`oud ag login --status` to check the stored PAT, re-login with `oud ag login`, "
466
+ "or pass `--access-token <pat>`; otherwise the endpoint itself requires "
467
+ "gateway-side credentials (not an AtomGit PAT)."
468
+ ),
469
+ )
470
+
471
+ # Capture backend-rotated session cookies (Set-Cookie) so subsequent
472
+ # requests pick them up automatically. Only done for 2xx/3xx — error
473
+ # responses rarely carry a meaningful rotation.
474
+ if 200 <= resp.status_code < 400 and token:
475
+ try:
476
+ from .auth import update_auth_from_response_headers
477
+
478
+ update_auth_from_response_headers(resp.headers)
479
+ except Exception:
480
+ # Cookie capture is best-effort; never fail the call because of it.
481
+ pass
482
+
483
+ out = {
484
+ "ok": 200 <= resp.status_code < 400,
485
+ "service": op.service_name,
486
+ "operation": op.display_name,
487
+ "method": op.backend.method,
488
+ "url": url,
489
+ "status": resp.status_code,
490
+ "response": _render_response(resp),
491
+ }
492
+ if include_request:
493
+ out["request"] = request_view
494
+ if op.display_name != op.operation_id:
495
+ out["operation_id_raw"] = op.operation_id
496
+ if param_corrections:
497
+ out["param_corrections"] = param_corrections
498
+ if unused:
499
+ out["unused_params"] = unused
500
+ return out
501
+
502
+
503
+ def describe_operation(op: Operation) -> dict[str, Any]:
504
+ """Render a single :class:`Operation` for ``oud <service>`` listing."""
505
+
506
+ rendered, _missing = _fill_path(op.path, {})
507
+ out: dict[str, Any] = {
508
+ "operation_id": op.display_name,
509
+ "method": op.http_method,
510
+ "path": op.path,
511
+ "url": f"{op.base_url}{rendered}",
512
+ "backend_declared": (
513
+ f"{op.backend.scheme}://{op.backend.address}{op.backend.path}"
514
+ if op.backend.address
515
+ else None
516
+ ),
517
+ "summary": op.summary,
518
+ "description": op.description,
519
+ "path_params": [p["name"] for p in op.path_params],
520
+ "query_params": [p["name"] for p in op.query_params],
521
+ "has_body": op.body_schema is not None,
522
+ "body_required": op.body_required,
523
+ }
524
+ if op.body_schema is not None:
525
+ out["body_required_fields"] = _body_field_summary(op.body_schema)
526
+ if op.display_name != op.operation_id:
527
+ out["operation_id_raw"] = op.operation_id
528
+ return out
529
+
530
+
531
+ def describe_service(service, ops: list) -> dict[str, Any]:
532
+ """Bundle service metadata + operations into one JSON document."""
533
+
534
+ return {
535
+ "service": {
536
+ "name": service.name,
537
+ "service_name": service.service_name,
538
+ "community": service.community,
539
+ "title": service.title,
540
+ "version": service.version,
541
+ "base_url": service.base_url,
542
+ },
543
+ "operations": [describe_operation(op) for op in ops],
544
+ "generated_at": _dt.datetime.now(_dt.timezone.utc).isoformat(),
545
+ }
546
+
547
+
548
+ def describe_operation_help(op: Operation, service) -> dict[str, Any]:
549
+ """Render ``oud <service> <operation> --help``: every per-parameter flag
550
+ plus a copy-pasteable usage example."""
551
+
552
+ rendered, _missing = _fill_path(op.path, {})
553
+ params: list[dict[str, Any]] = []
554
+ for p in op.parameters:
555
+ if p.get("in") not in {"query", "path"}:
556
+ continue
557
+ flag_stem = to_flag(p["name"])
558
+ schema = p.get("schema") or {}
559
+ entry: dict[str, Any] = {
560
+ "name": p["name"],
561
+ "in": p["in"],
562
+ "required": bool(p.get("required")),
563
+ "flag": f"--{flag_stem}",
564
+ "alt_flag": f"--{p['name']}",
565
+ "type": schema.get("type", "string"),
566
+ }
567
+ if p.get("description"):
568
+ entry["description"] = p["description"]
569
+ params.append(entry)
570
+
571
+ name = op.display_name
572
+ out: dict[str, Any] = {
573
+ "ok": True,
574
+ "help_for": name,
575
+ "service": {
576
+ "name": service.name,
577
+ "service_name": service.service_name,
578
+ "title": service.title,
579
+ },
580
+ "method": op.http_method,
581
+ "path": op.path,
582
+ "url": f"{op.base_url}{rendered}",
583
+ "summary": op.summary,
584
+ "description": op.description,
585
+ "has_body": op.body_schema is not None,
586
+ "body_required": op.body_required,
587
+ "parameters": params,
588
+ "usage": _usage_example(op),
589
+ "examples": _usage_examples(op),
590
+ }
591
+ if name != op.operation_id:
592
+ out["operation_id_raw"] = op.operation_id
593
+ if op.body_schema is not None:
594
+ out["body_required_fields"] = _body_field_summary(op.body_schema)
595
+ out["body_schema"] = op.body_schema
596
+ return out
597
+
598
+
599
+ def _usage_example(op: Operation) -> str:
600
+ """Single-line copy-pasteable invocation string."""
601
+
602
+ parts = [f"oud <service> {op.display_name}"]
603
+ for p in op.parameters:
604
+ if p.get("in") not in {"query", "path"}:
605
+ continue
606
+ flag = f"--{to_flag(p['name'])} <value>"
607
+ parts.append(flag if p.get("required") else f"[{flag}]")
608
+ if op.body_schema is not None:
609
+ parts.append("--json '{...}'")
610
+ parts.append("[--dry-run]")
611
+ return " ".join(parts)
612
+
613
+
614
+ def _usage_examples(op: Operation) -> list[str]:
615
+ """A couple of ready-to-paste example commands.
616
+
617
+ The ``--params`` example only makes sense when the operation declares
618
+ query/path params. A body-only operation gets a ``--json`` example
619
+ instead — otherwise agents get steered into sending body fields via
620
+ ``--params``, which silently drops them (``--params`` never carries a
621
+ request body).
622
+ """
623
+
624
+ name = op.display_name
625
+ examples: list[str] = []
626
+ has_params = any(p.get("in") in {"query", "path"} for p in op.parameters)
627
+ required = [
628
+ p
629
+ for p in op.parameters
630
+ if p.get("in") in {"query", "path"} and p.get("required")
631
+ ]
632
+
633
+ if required:
634
+ cmd = f"oud <service> {name}"
635
+ cmd += "".join(f" --{to_flag(p['name'])} <value>" for p in required)
636
+ cmd += " [--dry-run]"
637
+ examples.append(cmd)
638
+ if op.body_schema is not None:
639
+ examples.append(f"oud <service> {name} --json '{{\"...\"}}'")
640
+ if has_params:
641
+ examples.append(f"oud <service> {name} --params '{name}_PARAMS_JSON'")
642
+ if not examples:
643
+ examples.append(f"oud <service> {name} [--dry-run]")
644
+ return examples
645
+
646
+
647
+ __all__ = [
648
+ "call_operation",
649
+ "describe_operation",
650
+ "describe_operation_help",
651
+ "describe_service",
652
+ ]