pal-found-cli 0.1.2__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 (89) hide show
  1. pal_found_cli/__init__.py +1 -0
  2. pal_found_cli/_version.py +24 -0
  3. pal_found_cli/admin/__init__.py +2 -0
  4. pal_found_cli/admin/scripts/__init__.py +2 -0
  5. pal_found_cli/admin/scripts/pal_found_admin_cli.py +600 -0
  6. pal_found_cli/aip_agents/__init__.py +1 -0
  7. pal_found_cli/aip_agents/metadata-allow-list.md +20 -0
  8. pal_found_cli/aip_agents/scripts/__init__.py +1 -0
  9. pal_found_cli/aip_agents/scripts/pal_found_aip_agents_cli.py +704 -0
  10. pal_found_cli/audit/__init__.py +1 -0
  11. pal_found_cli/audit/metadata-allow-list.md +4 -0
  12. pal_found_cli/audit/scripts/__init__.py +1 -0
  13. pal_found_cli/audit/scripts/pal_found_audit_cli.py +387 -0
  14. pal_found_cli/checkpoints/__init__.py +9 -0
  15. pal_found_cli/checkpoints/metadata-allow-list.md +7 -0
  16. pal_found_cli/checkpoints/scripts/__init__.py +1 -0
  17. pal_found_cli/checkpoints/scripts/pal_found_checkpoints_cli.py +527 -0
  18. pal_found_cli/common/__init__.py +56 -0
  19. pal_found_cli/common/access_control_guard.py +591 -0
  20. pal_found_cli/common/async_client_factory.py +161 -0
  21. pal_found_cli/common/auth_provider.py +82 -0
  22. pal_found_cli/common/binary_download_handler.py +288 -0
  23. pal_found_cli/common/config_loader.py +388 -0
  24. pal_found_cli/common/error_serializer.py +412 -0
  25. pal_found_cli/common/log_setup.py +241 -0
  26. pal_found_cli/common/metadata-allow-list.md +169 -0
  27. pal_found_cli/common/output_formatter.py +267 -0
  28. pal_found_cli/common/pagination_helper.py +212 -0
  29. pal_found_cli/common/retry.py +617 -0
  30. pal_found_cli/common/sdk_error_utils.py +112 -0
  31. pal_found_cli/common/session_manager.py +461 -0
  32. pal_found_cli/common/tracing_provider.py +107 -0
  33. pal_found_cli/connectivity/__init__.py +9 -0
  34. pal_found_cli/connectivity/metadata-allow-list.md +24 -0
  35. pal_found_cli/connectivity/scripts/__init__.py +1 -0
  36. pal_found_cli/connectivity/scripts/pal_found_connectivity_cli.py +720 -0
  37. pal_found_cli/data_health/__init__.py +9 -0
  38. pal_found_cli/data_health/metadata-allow-list.md +10 -0
  39. pal_found_cli/data_health/scripts/__init__.py +1 -0
  40. pal_found_cli/data_health/scripts/pal_found_data_health_cli.py +458 -0
  41. pal_found_cli/datasets/__init__.py +1 -0
  42. pal_found_cli/datasets/scripts/__init__.py +1 -0
  43. pal_found_cli/datasets/scripts/pal_found_datasets_cli.py +732 -0
  44. pal_found_cli/filesystem/__init__.py +2 -0
  45. pal_found_cli/filesystem/scripts/__init__.py +2 -0
  46. pal_found_cli/filesystem/scripts/pal_found_filesystem_cli.py +659 -0
  47. pal_found_cli/functions/__init__.py +2 -0
  48. pal_found_cli/functions/scripts/__init__.py +2 -0
  49. pal_found_cli/functions/scripts/pal_found_functions_cli.py +389 -0
  50. pal_found_cli/language_models/__init__.py +1 -0
  51. pal_found_cli/language_models/metadata-allow-list.md +6 -0
  52. pal_found_cli/language_models/scripts/__init__.py +1 -0
  53. pal_found_cli/language_models/scripts/pal_found_language_models_cli.py +342 -0
  54. pal_found_cli/media_sets/__init__.py +9 -0
  55. pal_found_cli/media_sets/metadata-allow-list.md +23 -0
  56. pal_found_cli/media_sets/scripts/__init__.py +1 -0
  57. pal_found_cli/media_sets/scripts/pal_found_media_sets_cli.py +642 -0
  58. pal_found_cli/models/__init__.py +5 -0
  59. pal_found_cli/models/metadata-allow-list.md +27 -0
  60. pal_found_cli/models/scripts/__init__.py +1 -0
  61. pal_found_cli/models/scripts/pal_found_models_cli.py +714 -0
  62. pal_found_cli/ontologies/__init__.py +1 -0
  63. pal_found_cli/ontologies/scripts/__init__.py +1 -0
  64. pal_found_cli/ontologies/scripts/pal_found_ontologies_cli.py +1225 -0
  65. pal_found_cli/orchestration/__init__.py +9 -0
  66. pal_found_cli/orchestration/metadata-allow-list.md +24 -0
  67. pal_found_cli/orchestration/scripts/__init__.py +1 -0
  68. pal_found_cli/orchestration/scripts/pal_found_orchestration_cli.py +640 -0
  69. pal_found_cli/sql_queries/__init__.py +9 -0
  70. pal_found_cli/sql_queries/metadata-allow-list.md +9 -0
  71. pal_found_cli/sql_queries/scripts/__init__.py +1 -0
  72. pal_found_cli/sql_queries/scripts/pal_found_sql_queries_cli.py +514 -0
  73. pal_found_cli/streams/__init__.py +9 -0
  74. pal_found_cli/streams/metadata-allow-list.md +19 -0
  75. pal_found_cli/streams/scripts/__init__.py +1 -0
  76. pal_found_cli/streams/scripts/pal_found_streams_cli.py +615 -0
  77. pal_found_cli/third_party_applications/__init__.py +9 -0
  78. pal_found_cli/third_party_applications/metadata-allow-list.md +13 -0
  79. pal_found_cli/third_party_applications/scripts/__init__.py +1 -0
  80. pal_found_cli/third_party_applications/scripts/pal_found_third_party_applications_cli.py +547 -0
  81. pal_found_cli/widgets/__init__.py +9 -0
  82. pal_found_cli/widgets/metadata-allow-list.md +12 -0
  83. pal_found_cli/widgets/scripts/__init__.py +1 -0
  84. pal_found_cli/widgets/scripts/pal_found_widgets_cli.py +571 -0
  85. pal_found_cli-0.1.2.dist-info/METADATA +74 -0
  86. pal_found_cli-0.1.2.dist-info/RECORD +89 -0
  87. pal_found_cli-0.1.2.dist-info/WHEEL +5 -0
  88. pal_found_cli-0.1.2.dist-info/entry_points.txt +19 -0
  89. pal_found_cli-0.1.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,527 @@
1
+ #!/usr/bin/env python3
2
+ """Foundry Checkpoints CLI - 3 canonical Checkpoints API v2 operations.
3
+
4
+ Exposes exactly 3 public ``foundry_sdk.v2.checkpoints`` operations as CLI
5
+ subcommands through the single ``Record`` client path:
6
+
7
+ - record (3): get, get-batch, search
8
+
9
+ ``record search`` returns a ``SearchCheckpointRecordsResponse`` with a
10
+ ``next_page_token`` cursor and is the only paged operation; it routes
11
+ through ``PaginationHelper`` and accepts ``--page-size``, ``--page-token``,
12
+ ``--all``, and ``--max-pages``. ``record get`` and ``record get-batch`` have
13
+ no cursor and expose no pagination flags.
14
+
15
+ All three operations are semantic reads. ``record get_batch`` and
16
+ ``record search`` use POST but read only; the namespace has zero write
17
+ operations. The packaged metadata-only policy permits all 3 operations.
18
+
19
+ Usage: pal-found-checkpoints <resource> <operation> [options]
20
+ Output: JSON/TOON on stdout, NDJSON diagnostics on stderr (ADR-004, ADR-005).
21
+ Exit codes per ADR-001 taxonomy.
22
+ Access control: AccessControlGuard before client construction (SRS 4.2,
23
+ ADR-007). Retry: transient conditions only per ADR-002. All three operations
24
+ are safe to retry (no mutating or billable side effects).
25
+ Tracing: SDK-native B3 via invocation_scope; include_attribution=False
26
+ (namespace is outside FR-ATTR-4 scope).
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import asyncio
33
+ import json
34
+ import logging
35
+ import sys
36
+ from pathlib import Path
37
+ from typing import Any, NoReturn
38
+
39
+ from pal_found_cli.common.access_control_guard import (
40
+ AccessControlError,
41
+ AccessControlGuard,
42
+ )
43
+ from pal_found_cli.common.async_client_factory import AsyncClientFactory
44
+ from pal_found_cli.common.config_loader import ConfigLoader, ConfigurationError
45
+ from pal_found_cli.common.error_serializer import (
46
+ EXIT_ACCESS_CONTROL,
47
+ EXIT_AUTH,
48
+ EXIT_CONFIGURATION,
49
+ EXIT_NOT_FOUND,
50
+ EXIT_PERMISSION_DENIED,
51
+ EXIT_RATE_LIMIT,
52
+ EXIT_SERVER_ERROR,
53
+ EXIT_SUCCESS,
54
+ EXIT_TIMEOUT,
55
+ EXIT_USER_INPUT,
56
+ ErrorSerializer,
57
+ )
58
+ from pal_found_cli.common.log_setup import LogSetup
59
+ from pal_found_cli.common.output_formatter import OutputFormatter
60
+ from pal_found_cli.common.pagination_helper import HARD_MAX_BATCH_PAGES, PaginationHelper
61
+ from pal_found_cli.common.retry import RetryHandler
62
+ from pal_found_cli.common.sdk_error_utils import sdk_exception_exit_code, sdk_http_status
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+ OperationSpec = dict[str, Any]
67
+
68
+ _METADATA_ALLOWLIST_PATH = (
69
+ Path(__file__).resolve().parents[1] / "metadata-allow-list.md"
70
+ )
71
+
72
+ # ``record search`` is the only cursor-paged operation (DESIGN-019). It
73
+ # returns a SearchCheckpointRecordsResponse with a next_page_token and is
74
+ # driven through with_raw_response + PaginationHelper.
75
+ PAGINATED_OPS: frozenset[tuple[str, str]] = frozenset({("record", "search")})
76
+
77
+
78
+ class CLIInputError(ValueError):
79
+ """A locally generated input error whose message never echoes values."""
80
+
81
+ exit_code = EXIT_USER_INPUT
82
+
83
+
84
+ class _ArgumentParser(argparse.ArgumentParser):
85
+ """Raise parser failures into the structured error boundary."""
86
+
87
+ def error(self, message: str) -> NoReturn:
88
+ raise CLIInputError("Invalid command input")
89
+
90
+
91
+ def _op(
92
+ resource: str,
93
+ operation: str,
94
+ client_path: tuple[str, ...],
95
+ method: str,
96
+ positional: tuple[str, ...] = (),
97
+ required: tuple[str, ...] = (),
98
+ optional: tuple[str, ...] = (),
99
+ *,
100
+ json_args: frozenset[str] = frozenset(),
101
+ list_json_args: frozenset[str] = frozenset(),
102
+ ) -> OperationSpec:
103
+ """Build one operation specification entry."""
104
+ return {
105
+ "resource": resource,
106
+ "operation": operation,
107
+ "client_path": client_path,
108
+ "method": method,
109
+ "positional": positional,
110
+ "required": required,
111
+ "optional": optional,
112
+ "json_args": json_args,
113
+ "list_json_args": list_json_args,
114
+ }
115
+
116
+
117
+ OP_SPECS: tuple[OperationSpec, ...] = (
118
+ _op(
119
+ "record",
120
+ "get",
121
+ ("Record",),
122
+ "get",
123
+ ("record_rid",),
124
+ ),
125
+ _op(
126
+ "record",
127
+ "get_batch",
128
+ ("Record",),
129
+ "get_batch",
130
+ required=("records",),
131
+ list_json_args=frozenset({"records"}),
132
+ ),
133
+ _op(
134
+ "record",
135
+ "search",
136
+ ("Record",),
137
+ "search",
138
+ required=("where",),
139
+ optional=("page_size", "page_token", "sort_direction"),
140
+ json_args=frozenset({"where"}),
141
+ ),
142
+ )
143
+
144
+ OPERATION_BY_RESOURCE: dict[str, dict[str, OperationSpec]] = {}
145
+ for _spec in OP_SPECS:
146
+ OPERATION_BY_RESOURCE.setdefault(_spec["resource"], {})[_spec["operation"]] = _spec
147
+
148
+
149
+ # Structured JSON arguments across the catalog use the ``-json`` flag suffix.
150
+ _JSON_ARG_NAMES: frozenset[str] = frozenset(
151
+ name
152
+ for spec in OP_SPECS
153
+ for name in (*spec["json_args"], *spec["list_json_args"])
154
+ )
155
+
156
+ # Integer-typed SDK options.
157
+ _INT_ARG_NAMES: frozenset[str] = frozenset({"page_size"})
158
+
159
+
160
+ def _common_parser(*, paginated: bool) -> _ArgumentParser:
161
+ """Build operation-level common options."""
162
+ parser = _ArgumentParser(add_help=False)
163
+ parser.add_argument("--timeout", type=int, default=None)
164
+ parser.add_argument("--format", choices=("json", "toon", "auto"), default="auto")
165
+ parser.add_argument("--pretty", action="store_true")
166
+ if paginated:
167
+ parser.add_argument("--page-size", type=int, default=None, dest="page_size")
168
+ parser.add_argument("--page-token", default=None, dest="page_token")
169
+ parser.add_argument("--all", action="store_true", dest="all_pages")
170
+ parser.add_argument("--max-pages", type=int, default=None, dest="max_pages")
171
+ return parser
172
+
173
+
174
+ def _kebab(name: str) -> str:
175
+ """Convert snake_case names to CLI kebab-case."""
176
+ return name.replace("_", "-")
177
+
178
+
179
+ def _add_kwarg(
180
+ parser: argparse.ArgumentParser, arg_name: str, *, required: bool
181
+ ) -> None:
182
+ """Add one named operation argument."""
183
+ if arg_name in _JSON_ARG_NAMES:
184
+ flag = "--" + _kebab(arg_name) + "-json"
185
+ else:
186
+ flag = "--" + _kebab(arg_name)
187
+ kwargs: dict[str, Any] = {"required": required, "default": None, "dest": arg_name}
188
+ if arg_name in _INT_ARG_NAMES:
189
+ kwargs["type"] = int
190
+ parser.add_argument(flag, **kwargs)
191
+
192
+
193
+ def build_parser() -> argparse.ArgumentParser:
194
+ """Build argparse parser with all 3 Checkpoints operations."""
195
+ parser = _ArgumentParser(
196
+ prog="pal-found-checkpoints",
197
+ description="Foundry Checkpoints CLI - 3 Checkpoints API v2 operations",
198
+ )
199
+ subparsers = parser.add_subparsers(dest="resource", help="Resource type")
200
+
201
+ for resource in sorted(OPERATION_BY_RESOURCE):
202
+ res_parser = subparsers.add_parser(_kebab(resource))
203
+ op_sub = res_parser.add_subparsers(dest="operation")
204
+ for operation, spec in sorted(OPERATION_BY_RESOURCE[resource].items()):
205
+ is_paginated = (resource, operation) in PAGINATED_OPS
206
+ op_parser = op_sub.add_parser(
207
+ _kebab(operation), parents=[_common_parser(paginated=is_paginated)]
208
+ )
209
+ for arg_name in spec["positional"]:
210
+ op_parser.add_argument(arg_name)
211
+ for arg_name in spec["required"]:
212
+ _add_kwarg(op_parser, arg_name, required=True)
213
+ for arg_name in spec["optional"]:
214
+ if arg_name in {"page_size", "page_token"} and is_paginated:
215
+ continue
216
+ _add_kwarg(op_parser, arg_name, required=False)
217
+
218
+ return parser
219
+
220
+
221
+ def _spec_for(resource: str, operation: str) -> OperationSpec:
222
+ """Return one catalog operation specification."""
223
+ try:
224
+ return OPERATION_BY_RESOURCE[resource][operation]
225
+ except KeyError as exc:
226
+ raise CLIInputError(f"Unknown operation: {resource}.{operation}") from exc
227
+
228
+
229
+ def _get_client(root_client: Any, client_path: tuple[str, ...]) -> Any:
230
+ """Resolve the exact public nested Checkpoints SDK resource."""
231
+ client = root_client.checkpoints
232
+ for attribute in client_path:
233
+ client = getattr(client, attribute)
234
+ return client
235
+
236
+
237
+ def _required_text(value: Any, *, field: str) -> str:
238
+ """Validate a non-empty string without echoing its value."""
239
+ if not isinstance(value, str) or not value.strip():
240
+ raise CLIInputError(f"{field} must not be empty")
241
+ return value
242
+
243
+
244
+ def _decode_json(value: str, *, field: str) -> Any:
245
+ try:
246
+ return json.loads(value)
247
+ except json.JSONDecodeError as exc:
248
+ raise CLIInputError(f"{field} must contain valid JSON") from exc
249
+
250
+
251
+ def _parse_json_object(value: str, *, field: str) -> dict[str, Any]:
252
+ """Decode one JSON object."""
253
+ result = _decode_json(value, field=field)
254
+ if not isinstance(result, dict):
255
+ raise CLIInputError(f"{field} must be a JSON object")
256
+ return result
257
+
258
+
259
+ def _parse_json_list(value: str, *, field: str) -> list[Any]:
260
+ """Decode one JSON array of request elements."""
261
+ result = _decode_json(value, field=field)
262
+ if not isinstance(result, list):
263
+ raise CLIInputError(f"{field} must be a JSON array")
264
+ return result
265
+
266
+
267
+ def _validate_timeout(value: int) -> int:
268
+ """Validate the effective per-attempt timeout from ADR-002."""
269
+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 3600:
270
+ raise CLIInputError("timeout must be between 1 and 3600 seconds")
271
+ return value
272
+
273
+
274
+ def _validate_inputs(spec: OperationSpec, args: argparse.Namespace) -> None:
275
+ """Validate scalars and decode JSON arguments before client creation."""
276
+ for name in (*spec["positional"], *spec["required"]):
277
+ value = getattr(args, name, None)
278
+ if isinstance(value, str):
279
+ _required_text(value, field=name)
280
+ for name in spec["json_args"]:
281
+ value = getattr(args, name, None)
282
+ if value is not None:
283
+ setattr(args, name, _parse_json_object(value, field=name))
284
+ for name in spec["list_json_args"]:
285
+ value = getattr(args, name, None)
286
+ if value is not None:
287
+ setattr(args, name, _parse_json_list(value, field=name))
288
+
289
+
290
+ def _model_to_dict(value: Any) -> Any:
291
+ """Convert SDK models to JSON-compatible values."""
292
+ if value is None:
293
+ return None
294
+ if isinstance(value, list):
295
+ return [_model_to_dict(item) for item in value]
296
+ if isinstance(value, dict):
297
+ return {key: _model_to_dict(item) for key, item in value.items()}
298
+ for method_name in ("to_dict", "model_dump", "dict"):
299
+ method = getattr(value, method_name, None)
300
+ if callable(method):
301
+ result = method()
302
+ if isinstance(result, dict):
303
+ return {key: _model_to_dict(item) for key, item in result.items()}
304
+ return value
305
+
306
+
307
+ def _build_kwargs(
308
+ spec: OperationSpec, args: argparse.Namespace, timeout: int
309
+ ) -> dict[str, Any]:
310
+ """Build SDK keyword arguments, omitting absent optional values.
311
+
312
+ For cursor-paged operations the page_size/page_token come from the
313
+ PaginationHelper path and are intentionally omitted here.
314
+ """
315
+ is_paginated = (spec["resource"], spec["operation"]) in PAGINATED_OPS
316
+ kwargs: dict[str, Any] = {}
317
+ for name in (*spec["required"], *spec["optional"]):
318
+ if name in {"page_size", "page_token"} and is_paginated:
319
+ continue
320
+ if name == "records":
321
+ continue
322
+ value = getattr(args, name, None)
323
+ if value is not None:
324
+ kwargs[name] = value
325
+ kwargs["request_timeout"] = timeout
326
+ return kwargs
327
+
328
+
329
+ async def _invoke(
330
+ spec: OperationSpec,
331
+ client: Any,
332
+ args: argparse.Namespace,
333
+ timeout: int,
334
+ ) -> Any:
335
+ """Invoke one non-paginated SDK operation."""
336
+ positional = [getattr(args, name) for name in spec["positional"]]
337
+ if spec["method"] == "get_batch":
338
+ # The SDK exposes the batch body as the positional ``body``
339
+ # parameter; the decoded ``--records-json`` list is appended here
340
+ # and never forwarded as a keyword (DESIGN-019).
341
+ positional.append(getattr(args, "records"))
342
+ return await getattr(client, spec["method"])(
343
+ *positional, **_build_kwargs(spec, args, timeout)
344
+ )
345
+
346
+
347
+ async def _fetch_raw_page(
348
+ method: Any,
349
+ *,
350
+ page_size: int,
351
+ page_token: str | None,
352
+ request_timeout: int | None,
353
+ positional: tuple[Any, ...],
354
+ extra_kwargs: dict[str, Any],
355
+ ) -> dict[str, Any]:
356
+ """Fetch exactly one decoded SDK page via with_raw_response."""
357
+ raw_response = await method(
358
+ *positional,
359
+ page_size=page_size,
360
+ page_token=page_token,
361
+ request_timeout=request_timeout,
362
+ **extra_kwargs,
363
+ )
364
+ page = raw_response.decode()
365
+ return {
366
+ "items": list(getattr(page, "data", None) or []),
367
+ "next_page_token": getattr(page, "next_page_token", None),
368
+ }
369
+
370
+
371
+ def _resolve_pagination_flags(args: argparse.Namespace) -> int:
372
+ """Resolve the effective page batch size from --all/--max-pages."""
373
+ if getattr(args, "all_pages", False):
374
+ return HARD_MAX_BATCH_PAGES
375
+ return getattr(args, "max_pages", None) or 1
376
+
377
+
378
+ async def _paginate_operation(
379
+ spec: OperationSpec,
380
+ client: Any,
381
+ args: argparse.Namespace,
382
+ timeout: int,
383
+ ) -> tuple[list[Any], PaginationHelper]:
384
+ """Collect a bounded number of actual server pages."""
385
+ raw_method = getattr(getattr(client, "with_raw_response"), spec["method"])
386
+ batch_pages = _resolve_pagination_flags(args)
387
+ helper = PaginationHelper(
388
+ page_size=getattr(args, "page_size", None),
389
+ page_token=getattr(args, "page_token", None),
390
+ batch_pages=batch_pages,
391
+ )
392
+ positional = tuple(getattr(args, name) for name in spec["positional"])
393
+ extra_kwargs: dict[str, Any] = {}
394
+ for name in (*spec["required"], *spec["optional"]):
395
+ if name in {"page_size", "page_token"}:
396
+ continue
397
+ value = getattr(args, name, None)
398
+ if value is not None:
399
+ extra_kwargs[name] = value
400
+
401
+ async def fetch_page(**page_kwargs: Any) -> dict[str, Any]:
402
+ return await _fetch_raw_page(
403
+ raw_method,
404
+ page_size=page_kwargs["page_size"],
405
+ page_token=page_kwargs.get("page_token"),
406
+ request_timeout=timeout,
407
+ positional=positional,
408
+ extra_kwargs=extra_kwargs,
409
+ )
410
+
411
+ return await helper.paginate(fetch_page), helper
412
+
413
+
414
+ def _serialize_error(exception: BaseException) -> int:
415
+ """Write one privacy-safe ADR-001 error envelope to stdout."""
416
+ serializer = ErrorSerializer()
417
+ status = sdk_http_status(exception)
418
+ declared = getattr(exception, "exit_code", None)
419
+ sdk_exit = sdk_exception_exit_code(exception)
420
+ if isinstance(declared, int) and 1 <= declared <= 9:
421
+ exit_code = declared
422
+ elif sdk_exit is not None:
423
+ exit_code = sdk_exit
424
+ elif status == 401:
425
+ exit_code = EXIT_AUTH
426
+ elif status == 403:
427
+ exit_code = EXIT_PERMISSION_DENIED
428
+ elif status == 404:
429
+ exit_code = EXIT_NOT_FOUND
430
+ elif status == 429:
431
+ exit_code = EXIT_RATE_LIMIT
432
+ elif isinstance(exception, ConfigurationError):
433
+ exit_code = EXIT_CONFIGURATION
434
+ elif isinstance(exception, (TypeError, ValueError)):
435
+ exit_code = EXIT_USER_INPUT
436
+ elif isinstance(exception, TimeoutError):
437
+ exit_code = EXIT_TIMEOUT
438
+ else:
439
+ exit_code = EXIT_SERVER_ERROR
440
+
441
+ safe = isinstance(
442
+ exception,
443
+ (CLIInputError, ConfigurationError, TimeoutError),
444
+ ) or declared in {EXIT_ACCESS_CONTROL, EXIT_CONFIGURATION}
445
+ message = str(exception) if safe else "Checkpoints operation failed"
446
+ envelope = serializer.create_error_envelope(
447
+ exit_code, message, type(exception).__name__, serializer.call_id
448
+ )
449
+ if isinstance(status, int):
450
+ envelope["http_status"] = status
451
+ sys.stdout.write(json.dumps(envelope, default=str) + "\n")
452
+ sys.stdout.flush()
453
+ logger.error(
454
+ "Checkpoints operation failed",
455
+ extra={
456
+ "call_id": serializer.call_id,
457
+ "exception_type": type(exception).__name__,
458
+ "http_status": status,
459
+ },
460
+ )
461
+ return exit_code
462
+
463
+
464
+ async def main() -> int:
465
+ """Run one stateless Foundry Checkpoints invocation."""
466
+ parser = build_parser()
467
+ try:
468
+ args = parser.parse_args()
469
+ if not args.resource or not getattr(args, "operation", None):
470
+ raise CLIInputError("a Checkpoints operation is required")
471
+ except CLIInputError as exc:
472
+ return _serialize_error(exc)
473
+
474
+ try:
475
+ cfg = ConfigLoader()
476
+ cfg.load()
477
+ LogSetup.configure(log_level=cfg.log_level)
478
+
479
+ resource = args.resource.replace("-", "_")
480
+ operation = args.operation.replace("-", "_")
481
+ spec = _spec_for(resource, operation)
482
+ _validate_inputs(spec, args)
483
+ timeout = _validate_timeout(
484
+ args.timeout if args.timeout is not None else cfg.timeout_s
485
+ )
486
+ AccessControlGuard(
487
+ cfg,
488
+ "CHECKPOINTS",
489
+ metadata_allowlist_path=str(_METADATA_ALLOWLIST_PATH),
490
+ ).check(resource, operation)
491
+
492
+ factory = AsyncClientFactory()
493
+ helper: PaginationHelper | None = None
494
+ with factory.invocation_scope(cfg, include_attribution=False):
495
+ root_client = factory.create(cfg, include_attribution=False)
496
+ client = _get_client(root_client, spec["client_path"])
497
+ retry_handler = RetryHandler(timeout_s=timeout)
498
+ if (resource, operation) in PAGINATED_OPS:
499
+ result, helper = await retry_handler.execute(
500
+ _paginate_operation, spec, client, args, timeout
501
+ )
502
+ else:
503
+ result = await retry_handler.execute(
504
+ _invoke, spec, client, args, timeout
505
+ )
506
+
507
+ formatter = OutputFormatter(format_setting=args.format, pretty=args.pretty)
508
+ print(formatter.format(_model_to_dict(result)))
509
+ if helper is not None:
510
+ helper.emit_metadata()
511
+ return EXIT_SUCCESS
512
+ except AccessControlError as exc:
513
+ ErrorSerializer().serialize(exc)
514
+ return EXIT_ACCESS_CONTROL
515
+ except asyncio.CancelledError:
516
+ return _serialize_error(TimeoutError("Operation cancelled"))
517
+ except Exception as exc:
518
+ return _serialize_error(exc)
519
+
520
+
521
+ def console_main() -> int:
522
+ """Run the async CLI through one event-loop boundary."""
523
+ return asyncio.run(main())
524
+
525
+
526
+ if __name__ == "__main__":
527
+ raise SystemExit(console_main())
@@ -0,0 +1,56 @@
1
+ """Shared infrastructure components for Foundry CLI skills."""
2
+
3
+ from pal_found_cli.common.async_client_factory import AsyncClientFactory
4
+ from pal_found_cli.common.auth_provider import AuthProvider
5
+ from pal_found_cli.common.binary_download_handler import (
6
+ BinaryDownloadHandler,
7
+ DownloadError,
8
+ DownloadResult,
9
+ InvalidDownloadError,
10
+ )
11
+ from pal_found_cli.common.config_loader import ConfigLoader, ConfigurationError
12
+ from pal_found_cli.common.error_serializer import ErrorSerializer
13
+ from pal_found_cli.common.log_setup import LogSetup
14
+ from pal_found_cli.common.output_formatter import OutputFormatter
15
+ from pal_found_cli.common.retry import RetryHandler
16
+ from pal_found_cli.common.session_manager import (
17
+ InvalidSessionAliasError,
18
+ SessionAliasConflictError,
19
+ SessionCorruptionError,
20
+ SessionError,
21
+ SessionManager,
22
+ SessionNotFoundError,
23
+ SessionPersistenceError,
24
+ SessionState,
25
+ )
26
+ from pal_found_cli.common.tracing_provider import (
27
+ B3Context,
28
+ InvalidTraceContextError,
29
+ TracingProvider,
30
+ )
31
+
32
+ __all__ = [
33
+ "AsyncClientFactory",
34
+ "AuthProvider",
35
+ "B3Context",
36
+ "BinaryDownloadHandler",
37
+ "ConfigLoader",
38
+ "ConfigurationError",
39
+ "DownloadError",
40
+ "DownloadResult",
41
+ "ErrorSerializer",
42
+ "InvalidDownloadError",
43
+ "InvalidSessionAliasError",
44
+ "InvalidTraceContextError",
45
+ "LogSetup",
46
+ "OutputFormatter",
47
+ "RetryHandler",
48
+ "SessionAliasConflictError",
49
+ "SessionCorruptionError",
50
+ "SessionError",
51
+ "SessionManager",
52
+ "SessionNotFoundError",
53
+ "SessionPersistenceError",
54
+ "SessionState",
55
+ "TracingProvider",
56
+ ]