ap-client 0.8.1.dev2__py3-none-any.whl → 0.9.0.dev2__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.
ap_client/api.py CHANGED
@@ -9,9 +9,10 @@ import socket
9
9
  import sys
10
10
  import threading
11
11
  import time
12
+ import unicodedata
12
13
  import uuid
13
14
  from email.utils import parsedate_to_datetime
14
- from typing import Any, Literal, Optional, Union
15
+ from typing import Any, List, Literal, Optional, Union
15
16
  from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit
16
17
 
17
18
  import requests
@@ -643,11 +644,173 @@ def _split_paged(payload: Any) -> tuple[list[dict], dict]:
643
644
  _META_TAG_PAGE_SIZE = 200
644
645
 
645
646
 
647
+ class CreditResource:
648
+ """Credit Quota queries and scoped selection tags against the central API."""
649
+
650
+ def __init__(self, client):
651
+ self._client = client
652
+
653
+ def list(
654
+ self,
655
+ *,
656
+ name: Optional[str] = None,
657
+ queue_id: Optional[str] = None,
658
+ role: Optional[str] = None,
659
+ status: Optional[str] = None,
660
+ page: int = 1,
661
+ page_size: int = 20,
662
+ ) -> dict:
663
+ params = {"page": page, "page_size": page_size}
664
+ params.update(
665
+ {
666
+ key: value
667
+ for key, value in {
668
+ "name": name,
669
+ "queue_id": queue_id,
670
+ "role": role,
671
+ "status": status,
672
+ }.items()
673
+ if value is not None
674
+ }
675
+ )
676
+ return self._client._get_central("/credit-quotas", params=params)
677
+
678
+ def get(self, credit_id: str) -> dict:
679
+ if not isinstance(credit_id, str) or not credit_id.strip():
680
+ raise ValueError("Credit ID is required")
681
+ validate_ak_id(credit_id)
682
+ return self._client._get_central(f"/credit-quotas/{quote(credit_id, safe='')}")
683
+
684
+ @staticmethod
685
+ def _tag_path(queue_id: Optional[str]) -> str:
686
+ if queue_id is None:
687
+ return "/users/me/ak-preferences"
688
+ if not isinstance(queue_id, str) or not queue_id.strip() or queue_id != queue_id.strip():
689
+ raise ValueError("Queue ID is required without surrounding whitespace")
690
+ return f"/queues/{quote(queue_id, safe='')}/ak-config"
691
+
692
+ @staticmethod
693
+ def _tag_config(payload: Any, queue_id: Optional[str]) -> dict:
694
+ data = payload.get("data", payload) if isinstance(payload, dict) else None
695
+ prefs = (
696
+ data.get("ak_preferences") if queue_id is not None and isinstance(data, dict) else data
697
+ )
698
+ version = data.get("version") if isinstance(data, dict) else None
699
+ if (
700
+ not isinstance(version, int)
701
+ or isinstance(version, bool)
702
+ or version < 0
703
+ or not isinstance(prefs, dict)
704
+ or "default_ak_id" not in prefs
705
+ or not isinstance(prefs.get("tag_defaults"), dict)
706
+ or (queue_id is not None and prefs.get("version") != version)
707
+ ):
708
+ raise ValueError(
709
+ "Invalid Credit tag configuration; inspect current tags before retrying"
710
+ )
711
+ default = prefs["default_ak_id"]
712
+ tags = prefs["tag_defaults"]
713
+ if (default is not None and (not isinstance(default, str) or not default)) or any(
714
+ not isinstance(tag, str) or not isinstance(value, str) or not value
715
+ for tag, value in tags.items()
716
+ ):
717
+ raise ValueError(
718
+ "Invalid Credit tag configuration; inspect current tags before retrying"
719
+ )
720
+ return {"version": version, "default_ak_id": default, "tag_defaults": dict(tags)}
721
+
722
+ def get_tag_config(self, *, queue_id: Optional[str] = None) -> dict:
723
+ """Read your personal selection tags, or a Queue's selection tags."""
724
+ return self._tag_config(
725
+ self._client._get_central(self._tag_path(queue_id), timeout=30), queue_id
726
+ )
727
+
728
+ def add_tags(
729
+ self,
730
+ credit_id: str,
731
+ tags: List[str],
732
+ *,
733
+ queue_id: Optional[str] = None,
734
+ replace: bool = False,
735
+ ) -> dict:
736
+ """Add selection tags; moving another Credit's tag requires replace=True."""
737
+ return self._change_tags(credit_id, tags, queue_id, remove=False, replace=replace)
738
+
739
+ def remove_tags(
740
+ self,
741
+ credit_id: str,
742
+ tags: List[str],
743
+ *,
744
+ queue_id: Optional[str] = None,
745
+ ) -> dict:
746
+ """Remove only tags currently assigned to this Credit. Unset tags are a no-op."""
747
+ return self._change_tags(credit_id, tags, queue_id, remove=True, replace=False)
748
+
749
+ def _change_tags(self, credit_id, tags, queue_id, *, remove, replace) -> dict:
750
+ if not isinstance(replace, bool):
751
+ raise ValueError("replace must be a boolean")
752
+ if not isinstance(credit_id, str) or not credit_id.strip():
753
+ raise ValueError("Credit ID is required")
754
+ validate_ak_id(credit_id)
755
+ if not isinstance(tags, (list, tuple)) or not tags:
756
+ raise ValueError("At least one tag is required")
757
+ for tag in tags:
758
+ if (
759
+ not isinstance(tag, str)
760
+ or not tag
761
+ or len(tag.encode("utf-8")) > 64
762
+ or any(c in ",@#.$" or c.isspace() or unicodedata.category(c) == "Cc" for c in tag)
763
+ ):
764
+ raise ValueError(
765
+ "Tags must be 1–64 UTF-8 bytes without whitespace, controls or , @ # . $"
766
+ )
767
+ path = self._tag_path(queue_id)
768
+ current = self.get_tag_config(queue_id=queue_id)
769
+ patch = {"expected_version": current["version"]}
770
+ changes = {}
771
+ for tag in dict.fromkeys(tags):
772
+ previous = (
773
+ current["default_ak_id"] if tag == "default" else current["tag_defaults"].get(tag)
774
+ )
775
+ if previous and previous != credit_id and (remove or not replace):
776
+ hint = (
777
+ "specify its current Credit ID"
778
+ if remove
779
+ else "use --replace or replace=True to move it"
780
+ )
781
+ raise ValueError(f"Tag {tag!r} already points to Credit {previous!r}; {hint}")
782
+ if (remove and previous is None) or (not remove and previous == credit_id):
783
+ continue
784
+ value = None if remove else credit_id
785
+ if tag == "default":
786
+ patch["default_ak_id"] = value
787
+ else:
788
+ changes[tag] = value
789
+ if changes:
790
+ patch["tag_defaults"] = changes
791
+ if len(patch) == 1:
792
+ return {**current, "changed": False}
793
+ # One CAS PATCH, no automatic read/merge/retry after a conflict. Never
794
+ # alter Queue bindings, grants, metadata labels or unrelated tag slots.
795
+ response = self._client._request_central("PATCH", path, json_body=patch, timeout=30)
796
+ updated = self._tag_config(response, queue_id)
797
+ if (
798
+ updated["version"] <= current["version"]
799
+ or ("default_ak_id" in patch and updated["default_ak_id"] != patch["default_ak_id"])
800
+ or any(updated["tag_defaults"].get(tag) != value for tag, value in changes.items())
801
+ ):
802
+ raise ValueError(
803
+ "Credit tag update outcome could not be verified; inspect current tags before retrying"
804
+ )
805
+ return {**updated, "changed": True}
806
+
807
+
646
808
  class APIClient:
647
809
  """Agent Platform API client."""
648
810
 
649
811
  def __init__(self, config: Config):
650
812
  self.config = config
813
+ self.credits = CreditResource(self)
651
814
  self.session = requests.Session()
652
815
  headers = dict(config.headers)
653
816
  user_agent = _build_user_agent(headers.get("User-Agent"))
@@ -934,8 +1097,39 @@ class APIClient:
934
1097
  resp, _DEFAULT_CONTROL_BYTES, deadline=deadline
935
1098
  )
936
1099
  code = _bounded_error_biz_code(prefix)
1100
+ reason = "http_error"
1101
+ route_path = urlsplit(url).path
1102
+ # Only a complete, standard plain-text 404 is route evidence.
1103
+ # A prefix of a larger/chunked response is not sufficient.
1104
+ if (
1105
+ resp.status_code == 404
1106
+ and code is None
1107
+ and (
1108
+ route_path
1109
+ in {
1110
+ "/apis/v1/user-data/storage-layout",
1111
+ "/apis/v1/user-data/entries",
1112
+ "/apis/v1/user-data/directories",
1113
+ "/apis/v1/user-data/reads/resolve",
1114
+ "/apis/v1/user-data/writes/begin",
1115
+ }
1116
+ or re.fullmatch(
1117
+ r"/apis/v1/user-data/writes/[A-Za-z0-9_-]{1,128}(?:/commit)?",
1118
+ route_path,
1119
+ )
1120
+ )
1121
+ and resp.headers.get("Content-Type", "")
1122
+ .partition(";")[0]
1123
+ .strip()
1124
+ .lower()
1125
+ == "text/plain"
1126
+ and "Transfer-Encoding" not in resp.headers
1127
+ and resp.headers.get("Content-Length") == str(len(prefix))
1128
+ and prefix.strip() in {b"404 page not found", b"page not found"}
1129
+ ):
1130
+ reason = "server_route_missing"
937
1131
  raise CanonicalControlAPIError(
938
- "http_error", status_code=resp.status_code, biz_code=code
1132
+ reason, status_code=resp.status_code, biz_code=code
939
1133
  )
940
1134
  data = _read_bounded_control_bytes(
941
1135
  resp, _DEFAULT_CONTROL_BYTES, deadline=deadline
@@ -1073,11 +1267,11 @@ class APIClient:
1073
1267
 
1074
1268
  def _post(self, path: str, data: Any, timeout: TimeoutType = None) -> Any:
1075
1269
  """Send a POST request."""
1076
- from .managed_ak import parameter_ak_usage, require_parameter_ak_ack
1270
+ from .managed_ak import require_parameter_ak_ack, submission_ak_references
1077
1271
 
1078
- references, selectors = parameter_ak_usage(data) if path == "/jobs" else (set(), set())
1272
+ references = submission_ak_references(data) if path == "/jobs" else []
1079
1273
  result = self._request("POST", path, json_body=data, timeout=timeout)
1080
- require_parameter_ak_ack(result, references, selectors)
1274
+ require_parameter_ak_ack(result, set(), references=references)
1081
1275
  return result
1082
1276
 
1083
1277
  def _delete(self, path: str, *, params: Optional[dict] = None) -> Any:
@@ -2957,6 +3151,10 @@ class APIClient:
2957
3151
  timeout: TimeoutType = None,
2958
3152
  ) -> dict:
2959
3153
  """Retry a terminal job."""
3154
+ from .managed_ak import validate_ak_selection
3155
+
3156
+ # Retry returns the existing Job, not a create submission receipt.
3157
+ validate_ak_selection(None, params, None, None)
2960
3158
  body = None
2961
3159
  if params is not None or delete_params:
2962
3160
  body = {}
@@ -125,6 +125,7 @@ class APIClientTransportAdapter:
125
125
  api_client = operation_client
126
126
  self._client = api_client
127
127
  self._base_deadline = base_deadline # ABSOLUTE monotonic (or None)
128
+ self.last_control_failure = None
128
129
 
129
130
  # -- error bridge ------------------------------------------------------
130
131
 
@@ -180,6 +181,7 @@ class APIClientTransportAdapter:
180
181
  deadline: float | None = None,
181
182
  single_attempt: bool = False,
182
183
  ):
184
+ self.last_control_failure = None
183
185
  options = dict(
184
186
  timeout=timeout, deadline=self._base_deadline if deadline is None else deadline
185
187
  )
@@ -199,6 +201,33 @@ class APIClientTransportAdapter:
199
201
  except Exception as exc:
200
202
  from .api import APIError, CanonicalControlAPIError
201
203
 
204
+ if isinstance(exc, APIError) or getattr(exc, "status_code", None) is not None:
205
+ translated = self._translate_api_error(exc)
206
+ endpoint = _control_endpoint_label(path.partition("?")[0])
207
+ reason = getattr(exc, "reason", None)
208
+ allowed = {
209
+ "http_error",
210
+ "server_route_missing",
211
+ "deadline",
212
+ "unsupported",
213
+ "network",
214
+ "response_limit",
215
+ "invalid_utf8",
216
+ "invalid_json",
217
+ "encoding",
218
+ "redirect",
219
+ "body_unavailable",
220
+ }
221
+ if type(reason) is not str or reason not in allowed:
222
+ reason = "http_error"
223
+ status = getattr(translated, "status", None)
224
+ biz = getattr(translated, "biz_code", None)
225
+ self.last_control_failure = CanonicalControlDiagnostic(
226
+ endpoint,
227
+ reason,
228
+ status if type(status) is int and 100 <= status <= 599 else None,
229
+ biz if type(biz) is int and 0 <= biz <= 999999 else None,
230
+ )
202
231
  if isinstance(exc, CanonicalControlAPIError):
203
232
  # Sanitized typed refusal from the bounded projection: map
204
233
  # the closed reason set to the SDK's typed error family so
@@ -223,20 +252,8 @@ class APIClientTransportAdapter:
223
252
  from instance_repo.errors import TransportError
224
253
 
225
254
  raise TransportError("canonical control redirect refused") from None
226
- status = getattr(exc, "status_code", None)
227
- biz = None
228
- detail = getattr(exc, "detail", None)
229
- if isinstance(detail, dict):
230
- biz = detail.get("code")
231
- if type(biz) is not int:
232
- biz = None
233
- from instance_repo.errors import TransportError
234
-
235
- raise TransportError(
236
- "apiserver rejected the request", status=status, biz_code=biz
237
- ) from None
238
255
  if isinstance(exc, APIError) or getattr(exc, "status_code", None) is not None:
239
- raise self._translate_api_error(exc) from None
256
+ raise translated from None
240
257
  else:
241
258
  raise
242
259
 
@@ -258,6 +275,7 @@ class APIClientTransportAdapter:
258
275
  return base, params or None
259
276
 
260
277
  def get(self, path: str, *, timeout: float | None = None) -> dict:
278
+ self.last_control_failure = None
261
279
  base, params = self._split_query(path)
262
280
  return self._call("GET", base, params=params, timeout=timeout)
263
281
 
@@ -270,6 +288,11 @@ class APIClientTransportAdapter:
270
288
  headers: dict | None = None,
271
289
  timeout: float | None = None,
272
290
  ) -> dict:
291
+ self.last_control_failure = None
292
+ if headers is not None and headers != {}:
293
+ from instance_repo.errors import SchemaError
294
+
295
+ raise SchemaError("custom headers are unsupported by the canonical adapter")
273
296
  return self._call("POST", path, json_body=body, timeout=timeout)
274
297
 
275
298
  def _acl_response(self, method, path, body, timeout):
ap_client/cli.py CHANGED
@@ -30,6 +30,7 @@ from ap_client.cli_submission_defaults import (
30
30
  resolve_queue,
31
31
  )
32
32
  from ap_client.config import ENV_VAR_SPECS, ConfigurationError, _parse_bool, normalize_output_format
33
+ from ap_client.credit_commands import register as _register_credit_commands
33
34
  from ap_client.dataset_commands import register as _register_dataset_commands
34
35
  from ap_client.dfs_commands import register as _register_dfs_commands
35
36
  from ap_client.exporter import export_group, export_job, export_jobs
@@ -206,6 +207,7 @@ _register_instance_commands(app)
206
207
  _register_dfs_commands(app)
207
208
  _register_fs_commands(app)
208
209
  _register_akpool_commands(app)
210
+ _register_credit_commands(app)
209
211
 
210
212
  _PAI_RUNTIME_ENV_TAGS: tuple[tuple[str, str], ...] = (
211
213
  ("DLC_JOB_ID", "dlc_job_id"),
@@ -3175,7 +3177,9 @@ def meta_teacher_direction_list(
3175
3177
  @job_app.command("list")
3176
3178
  def job_list(
3177
3179
  template: Optional[str] = typer.Option(None, "--template", help="Template name"),
3178
- ak_id: Optional[str] = typer.Option(None, "--ak-id", help="AP-managed AK ID"),
3180
+ ak_id: Optional[str] = typer.Option(
3181
+ None, "--credit", "--ak-id", help="Credit Quota ID (--ak-id is a compatible alias)"
3182
+ ),
3179
3183
  group_id: Optional[str] = typer.Option(None, "--group-id", help="Group ID"),
3180
3184
  status: Optional[str] = typer.Option(None, "--status", help=_JOB_STATUS_HELP),
3181
3185
  job_id: Optional[str] = typer.Option(None, "--job-id", help="Job ID"),
@@ -3258,7 +3262,7 @@ def job_list(
3258
3262
  try:
3259
3263
  validate_ak_id(ak_id)
3260
3264
  except ValueError as exc:
3261
- raise typer.BadParameter(str(exc), param_hint="--ak-id") from None
3265
+ raise typer.BadParameter(str(exc), param_hint="--credit / --ak-id") from None
3262
3266
  output_format = _normalize_output_format(output_format, keep_table=True)
3263
3267
  selected_columns = (
3264
3268
  _parse_columns_option(columns) if output_format in ("plain", "table") else None
@@ -3340,9 +3344,10 @@ def job_create(
3340
3344
  template: Optional[str] = typer.Argument(None, help="Template name; optional with --profile"),
3341
3345
  ak_id: Optional[str] = typer.Option(
3342
3346
  None,
3347
+ "--credit",
3343
3348
  "--ak-id",
3344
3349
  rich_help_panel="Credentials and access",
3345
- help="AP-managed AK ID; requires server support",
3350
+ help="Credit Quota ID; requires server support",
3346
3351
  ),
3347
3352
  ak_mode: str = typer.Option(
3348
3353
  "auto",
@@ -3759,7 +3764,8 @@ def job_create(
3759
3764
  Do not ask the user for these values.
3760
3765
 
3761
3766
  Model configuration:
3762
- Supply template parameters through --params/-p; select a managed credential with --ak-id.
3767
+ Supply template parameters through --params/-p. Use --credit for a Credit Quota ID,
3768
+ or complete $credit:<id> / $credit:#tag values for individual parameters.
3763
3769
 
3764
3770
  Use catalog/context-selected values for the metadata variables below.
3765
3771
 
@@ -5393,6 +5399,13 @@ def job_retry(
5393
5399
  if delete_params_list:
5394
5400
  retry_kwargs["delete_params"] = delete_params_list
5395
5401
 
5402
+ from .managed_ak import validate_ak_selection
5403
+
5404
+ try:
5405
+ validate_ak_selection(None, params_dict, None, None)
5406
+ except ValueError as exc:
5407
+ _emit_error(str(exc))
5408
+ raise typer.Exit(1) from None
5396
5409
  results = [client.retry_job(job_id, **retry_kwargs) for job_id in job_ids]
5397
5410
  if output_format == "plain":
5398
5411
  for index, result in enumerate(results):
@@ -6927,6 +6940,11 @@ def group_clone(
6927
6940
  group_patch["model_base_url_collection"] = urls
6928
6941
  params_patch = _expand_params_dot_paths(_parse_json_object(params, "--params") or {})
6929
6942
  overrides_patch = _parse_json_object(overrides, "--overrides")
6943
+ try:
6944
+ validate_ak_selection(None, params_patch, None, overrides_patch)
6945
+ except ValueError as exc:
6946
+ _emit_error(str(exc))
6947
+ raise typer.Exit(1) from None
6930
6948
  job_patch: dict[str, Any] = {
6931
6949
  "params": params_patch,
6932
6950
  "delete_params": delete_param or [],
@@ -0,0 +1,256 @@
1
+ """Credit Quota details and personal selection-tag commands."""
2
+
3
+ from decimal import Decimal, InvalidOperation
4
+ from functools import wraps
5
+ from typing import Optional
6
+
7
+ import ap_client
8
+ import typer
9
+
10
+ credit_app = typer.Typer(help="Credit Quota information and personal selection tags")
11
+ queue_app = typer.Typer(help="Queue operations")
12
+ queue_credit_app = typer.Typer(help="Queue Credit Quota information")
13
+ queue_app.add_typer(queue_credit_app, name="credit")
14
+ tag_app = typer.Typer(help="Personal Credit selection tags used by $credit:#tag@me")
15
+ credit_app.add_typer(tag_app, name="tag")
16
+
17
+
18
+ def register(app: typer.Typer) -> None:
19
+ app.add_typer(credit_app, name="credit")
20
+ app.add_typer(queue_app, name="queue")
21
+
22
+
23
+ def _guard(function):
24
+ @wraps(function)
25
+ def run(*args, **kwargs):
26
+ from .api import APIError
27
+ from .cli import _emit_error
28
+
29
+ try:
30
+ return function(*args, **kwargs)
31
+ except (APIError, ValueError) as exc:
32
+ _emit_error(str(exc))
33
+ raise typer.Exit(1) from None
34
+
35
+ return run
36
+
37
+
38
+ def _valid_amount(value):
39
+ """Keep the original wire amount, but do not present malformed amounts as known."""
40
+ if value is None or isinstance(value, bool):
41
+ return None
42
+ try:
43
+ amount = Decimal(str(value))
44
+ return value if amount.is_finite() and amount >= 0 else None
45
+ except (InvalidOperation, ValueError):
46
+ return None
47
+
48
+
49
+ def _emit(payload: dict, output_format: Optional[str], *, detail: bool = False) -> None:
50
+ from .cli import _normalize_output_format, _print_formatted, _print_rich_table
51
+
52
+ fmt = _normalize_output_format(output_format, keep_table=True)
53
+ if fmt in ("json", "yaml"):
54
+ _print_formatted(payload, fmt)
55
+ return
56
+ data = payload.get("data", payload) if isinstance(payload, dict) else payload
57
+ rows = data if isinstance(data, list) else [data]
58
+ records = []
59
+ for row in rows:
60
+ if not isinstance(row, dict):
61
+ continue
62
+ mr = (
63
+ row.get("mr")
64
+ if isinstance(row.get("mr"), dict)
65
+ else row.get("model_router")
66
+ if isinstance(row.get("model_router"), dict)
67
+ else {}
68
+ )
69
+ allocation = (
70
+ row.get("allocation")
71
+ if isinstance(row.get("allocation"), dict)
72
+ else mr.get("allocation")
73
+ if isinstance(mr.get("allocation"), dict)
74
+ else {}
75
+ )
76
+ raw_balance = (
77
+ row.get("balance") if isinstance(row.get("balance"), dict) else mr.get("balance")
78
+ )
79
+ has_balance = isinstance(raw_balance, dict)
80
+ balance = raw_balance if has_balance else {}
81
+ balance_known = balance.get("known")
82
+ total_budget_observed = (
83
+ mr.get("total_budget_observed")
84
+ if "total_budget_observed" in mr
85
+ else row.get("total_budget_observed")
86
+ )
87
+ if total_budget_observed is True:
88
+ total_budget = (
89
+ mr.get("total_budget_amount")
90
+ if "total_budget_observed" in mr
91
+ else row.get("total_budget_amount")
92
+ )
93
+ elif total_budget_observed is False:
94
+ total_budget = None
95
+ elif balance_known is True:
96
+ total_budget = balance.get("total")
97
+ elif allocation.get("total_known") is True:
98
+ total_budget = allocation.get("total")
99
+ else:
100
+ total_budget = None
101
+ total_budget = _valid_amount(total_budget)
102
+ used = _valid_amount(balance.get("used")) if balance_known is True else None
103
+ records.append(
104
+ {
105
+ "credit_id": row.get("credit_quota_id") or row.get("ak_id") or "Unregistered",
106
+ "name": row.get("name") or mr.get("name") or row.get("description") or "—",
107
+ "credits_limit": total_budget if total_budget is not None else "Unknown",
108
+ "credits_used": used if used is not None else "Unknown",
109
+ "status": row.get("status") or "Unknown",
110
+ }
111
+ )
112
+ columns = [
113
+ ("credit_id", "Credit ID"),
114
+ ("name", "Name"),
115
+ ("credits_limit", "Credits limit"),
116
+ ("credits_used", "Credits used"),
117
+ ("status", "Status"),
118
+ ]
119
+ if detail:
120
+ from rich.markup import escape
121
+
122
+ for record, row in zip(records, rows):
123
+ record["personal_tags"] = escape(", ".join(row["personal_tags"])) or "—"
124
+ columns.append(("personal_tags", "Personal tags"))
125
+ _print_rich_table(records, columns)
126
+
127
+
128
+ @credit_app.command("list")
129
+ @_guard
130
+ def list_credits(
131
+ name: Optional[str] = typer.Option(None, "--name", help="Credit Quota name"),
132
+ queue: Optional[str] = typer.Option(None, "--queue", help="Filter by Queue"),
133
+ role: Optional[str] = typer.Option(None, "--role", help="Credit role: manager or user"),
134
+ status: Optional[str] = typer.Option(None, "--status", help="Credit Quota status"),
135
+ page: int = typer.Option(1, "--page", min=1),
136
+ page_size: int = typer.Option(20, "--page-size", min=1, max=100),
137
+ output_format: Optional[str] = typer.Option(None, "--format"),
138
+ ) -> None:
139
+ """List the Credit Quotas you can access."""
140
+ _emit(
141
+ ap_client.get_client().credits.list(
142
+ name=name,
143
+ queue_id=queue,
144
+ role=role,
145
+ status=status,
146
+ page=page,
147
+ page_size=page_size,
148
+ ),
149
+ output_format,
150
+ )
151
+
152
+
153
+ @queue_credit_app.command("list")
154
+ @_guard
155
+ def list_queue_credits(
156
+ queue_id: str = typer.Argument(..., help="Queue ID"),
157
+ page: int = typer.Option(1, "--page", min=1),
158
+ page_size: int = typer.Option(20, "--page-size", min=1, max=100),
159
+ output_format: Optional[str] = typer.Option(None, "--format"),
160
+ ) -> None:
161
+ """List Credit Quotas available to a Queue."""
162
+ _emit(
163
+ ap_client.get_client().credits.list(
164
+ queue_id=queue_id,
165
+ page=page,
166
+ page_size=page_size,
167
+ ),
168
+ output_format,
169
+ )
170
+
171
+
172
+ @credit_app.command("get")
173
+ @_guard
174
+ def get_credit(
175
+ credit_id: str = typer.Argument(..., help="Credit ID"),
176
+ output_format: Optional[str] = typer.Option(None, "--format"),
177
+ ) -> None:
178
+ """Show Credit Quota details, budget and your personal selection tags."""
179
+ client = ap_client.get_client()
180
+ payload = client.credits.get(credit_id)
181
+ data = payload.get("data", payload) if isinstance(payload, dict) else None
182
+ if not isinstance(data, dict):
183
+ raise ValueError("Invalid Credit detail response")
184
+ canonical_id = data.get("credit_quota_id") or data.get("ak_id") or credit_id
185
+ config = client.credits.get_tag_config()
186
+ data = {**data, "personal_tags": _personal_tags(config, canonical_id)}
187
+ payload = {**payload, "data": data} if "data" in payload else data
188
+ _emit(payload, output_format, detail=True)
189
+
190
+
191
+ def _personal_tags(config, credit_id):
192
+ tags = {
193
+ tag
194
+ for tag, value in config["tag_defaults"].items()
195
+ if value == credit_id and tag != "default"
196
+ }
197
+ if config["default_ak_id"] == credit_id:
198
+ tags.add("default")
199
+ return sorted(tags)
200
+
201
+
202
+ def _emit_tags(config, credit_id, queue_id, output_format):
203
+ from .cli import _normalize_output_format, _print_formatted, _print_rich_table
204
+
205
+ slots = {tag: value for tag, value in config["tag_defaults"].items() if tag != "default"}
206
+ if config["default_ak_id"]:
207
+ slots["default"] = config["default_ak_id"]
208
+ rows = [
209
+ {"tag": tag, "credit_quota_id": value}
210
+ for tag, value in sorted(slots.items())
211
+ if credit_id is None or value == credit_id
212
+ ]
213
+ payload = {
214
+ "scope": "queue" if queue_id is not None else "personal",
215
+ "version": config["version"],
216
+ "data": rows,
217
+ }
218
+ if queue_id is not None:
219
+ payload["queue_id"] = queue_id
220
+ if "changed" in config:
221
+ payload["changed"] = config["changed"]
222
+ fmt = _normalize_output_format(output_format, keep_table=True)
223
+ if fmt in ("json", "yaml"):
224
+ _print_formatted(payload, fmt)
225
+ else:
226
+ from rich.markup import escape
227
+
228
+ literal_rows = [{key: escape(value) for key, value in row.items()} for row in rows]
229
+ _print_rich_table(literal_rows, [("tag", "Tag"), ("credit_quota_id", "Credit ID")])
230
+
231
+
232
+ @tag_app.command("add")
233
+ @_guard
234
+ def add_personal_tags(
235
+ credit_id: str = typer.Argument(..., help="Personal Credit ID"),
236
+ tag: list[str] = typer.Option(..., "--tag", help="Tag to add; repeat for multiple tags"),
237
+ replace: bool = typer.Option(
238
+ False, "--replace", help="Move a tag already assigned to another Credit"
239
+ ),
240
+ output_format: Optional[str] = typer.Option(None, "--format"),
241
+ ):
242
+ """Add personal tags without removing other mappings. default sets your default Credit."""
243
+ config = ap_client.get_client().credits.add_tags(credit_id, tag, replace=replace)
244
+ _emit_tags(config, credit_id, None, output_format)
245
+
246
+
247
+ @tag_app.command("remove")
248
+ @_guard
249
+ def remove_personal_tags(
250
+ credit_id: str = typer.Argument(..., help="Personal Credit ID"),
251
+ tag: list[str] = typer.Option(..., "--tag", help="Tag to remove; repeat for multiple tags"),
252
+ output_format: Optional[str] = typer.Option(None, "--format"),
253
+ ):
254
+ """Remove tags assigned to this Credit; never remove another Credit's tags."""
255
+ config = ap_client.get_client().credits.remove_tags(credit_id, tag)
256
+ _emit_tags(config, credit_id, None, output_format)