infixspeed-cli 0.0.16__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 (85) hide show
  1. infix_cli/__init__.py +5 -0
  2. infix_cli/__main__.py +6 -0
  3. infix_cli/agent-guide.txt +71 -0
  4. infix_cli/cli_framework.py +96 -0
  5. infix_cli/command_contract.py +157 -0
  6. infix_cli/commands/__init__.py +1 -0
  7. infix_cli/commands/_artifacts.py +142 -0
  8. infix_cli/commands/_comparison.py +443 -0
  9. infix_cli/commands/_confirm.py +26 -0
  10. infix_cli/commands/_control.py +290 -0
  11. infix_cli/commands/_create.py +351 -0
  12. infix_cli/commands/_create_output.py +139 -0
  13. infix_cli/commands/_delete.py +288 -0
  14. infix_cli/commands/_download.py +459 -0
  15. infix_cli/commands/_fusion_common.py +191 -0
  16. infix_cli/commands/_fusion_config.py +394 -0
  17. infix_cli/commands/_fusion_feedback.py +319 -0
  18. infix_cli/commands/_fusion_tasks.py +507 -0
  19. infix_cli/commands/_fusion_tensorboard.py +132 -0
  20. infix_cli/commands/_jobs.py +312 -0
  21. infix_cli/commands/_logs.py +210 -0
  22. infix_cli/commands/_publish.py +123 -0
  23. infix_cli/commands/_register.py +600 -0
  24. infix_cli/commands/_register_output.py +231 -0
  25. infix_cli/commands/_storage_tree.py +62 -0
  26. infix_cli/commands/admin.py +668 -0
  27. infix_cli/commands/asset.py +2012 -0
  28. infix_cli/commands/auth.py +246 -0
  29. infix_cli/commands/deploy.py +850 -0
  30. infix_cli/commands/evaluation.py +360 -0
  31. infix_cli/commands/examples.py +138 -0
  32. infix_cli/commands/fusion.py +1842 -0
  33. infix_cli/commands/merge.py +709 -0
  34. infix_cli/commands/resource.py +127 -0
  35. infix_cli/commands/spark.py +347 -0
  36. infix_cli/commands/storage.py +329 -0
  37. infix_cli/commands/training.py +748 -0
  38. infix_cli/config.py +311 -0
  39. infix_cli/config_input.py +217 -0
  40. infix_cli/context.py +84 -0
  41. infix_cli/discovery.py +459 -0
  42. infix_cli/domain/__init__.py +1 -0
  43. infix_cli/domain/dto/__init__.py +6 -0
  44. infix_cli/domain/dto/admin.py +413 -0
  45. infix_cli/domain/dto/asset.py +390 -0
  46. infix_cli/domain/dto/common.py +136 -0
  47. infix_cli/domain/dto/evaluation.py +296 -0
  48. infix_cli/domain/dto/logs.py +98 -0
  49. infix_cli/domain/dto/resource.py +108 -0
  50. infix_cli/domain/dto/serving.py +156 -0
  51. infix_cli/domain/dto/spark.py +241 -0
  52. infix_cli/domain/dto/storage.py +75 -0
  53. infix_cli/domain/dto/training.py +272 -0
  54. infix_cli/domain/enums.py +359 -0
  55. infix_cli/domain/hyperparams.py +190 -0
  56. infix_cli/domain/refs.py +108 -0
  57. infix_cli/domain/resolve.py +619 -0
  58. infix_cli/errors.py +158 -0
  59. infix_cli/example_data/__init__.py +1 -0
  60. infix_cli/example_data/fusion/README.md +128 -0
  61. infix_cli/example_data/fusion/fusion.json +149 -0
  62. infix_cli/example_data/fusion/prompts/code.jsonl +16 -0
  63. infix_cli/example_data/fusion/prompts/math.jsonl +16 -0
  64. infix_cli/example_data/fusion.zip +0 -0
  65. infix_cli/example_data/merge/README.md +89 -0
  66. infix_cli/example_data/merge/merge.json +26 -0
  67. infix_cli/example_data/merge.zip +0 -0
  68. infix_cli/http/__init__.py +1 -0
  69. infix_cli/http/browser_auth.py +160 -0
  70. infix_cli/http/client.py +575 -0
  71. infix_cli/http/pagination.py +84 -0
  72. infix_cli/http/upload.py +254 -0
  73. infix_cli/main.py +432 -0
  74. infix_cli/pipeline_config_schema.py +122 -0
  75. infix_cli/render/__init__.py +79 -0
  76. infix_cli/render/json_out.py +123 -0
  77. infix_cli/render/progress.py +62 -0
  78. infix_cli/render/text.py +233 -0
  79. infix_cli/update_check.py +177 -0
  80. infix_cli/waiter.py +93 -0
  81. infix_cli/workspace.py +158 -0
  82. infixspeed_cli-0.0.16.dist-info/METADATA +58 -0
  83. infixspeed_cli-0.0.16.dist-info/RECORD +85 -0
  84. infixspeed_cli-0.0.16.dist-info/WHEEL +4 -0
  85. infixspeed_cli-0.0.16.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,2012 @@
1
+ """``infix asset`` — browse registered models, datasets, code and images."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+ import typer
8
+
9
+ from infix_cli import render
10
+ from infix_cli.commands import _delete, _publish, _register, _register_output
11
+ from infix_cli.domain import enums, resolve
12
+ from infix_cli.domain.dto.asset import AssetDTO, AssetVersionDTO, ImageDTO
13
+ from infix_cli.domain.dto.common import compact, format_bytes
14
+ from infix_cli.errors import CliError, NotFoundError, UsageError
15
+ from infix_cli.render import progress, text
16
+ from infix_cli.http.pagination import fetch_page
17
+
18
+ app = typer.Typer(help="Registered assets: models, datasets, code and images.", no_args_is_help=True)
19
+
20
+ _MAX_PAGE_SIZE = 50
21
+
22
+
23
+ def _split_scope(name: str, scope_flag: str | None) -> tuple[str, str]:
24
+ """Resolve the effective scope from an optional prefix and ``--scope``.
25
+
26
+ The prefix wins because it is the more specific statement, but a
27
+ contradiction is an error rather than a silent preference: the user
28
+ clearly believes one of the two, and guessing which would hide the typo.
29
+ """
30
+ plain = name.strip()
31
+ prefix_scope: str | None = None
32
+ for prefix, scope in (("official/", "official"), ("workspace/", "workspace")):
33
+ if plain.startswith(prefix):
34
+ prefix_scope = scope
35
+ plain = plain[len(prefix):]
36
+ break
37
+ plain = plain.split(":", 1)[0].strip()
38
+ if not plain:
39
+ raise UsageError(f'"{name}" names no asset.')
40
+
41
+ if prefix_scope and scope_flag and prefix_scope != scope_flag:
42
+ raise UsageError(
43
+ f'"{name}" is a {prefix_scope} reference but --scope {scope_flag} was given.',
44
+ "Drop one of the two.",
45
+ )
46
+ scope = prefix_scope or scope_flag or "workspace"
47
+ return plain, enums.ASSET_SCOPE.to_backend(scope)
48
+
49
+
50
+ def _cli_scope(backend_scope: str) -> str:
51
+ return enums.ASSET_SCOPE.to_cli(backend_scope)
52
+
53
+
54
+
55
+ def _creator_id(run, kind: str, creator: str) -> str:
56
+ """Resolve a creator name to the id the backend filters on.
57
+
58
+ Assets store creator_id; the PRD's --creator takes a name. The per-kind
59
+ /creators endpoint is the mapping, and it only lists creators who actually
60
+ own assets of that kind — so an unmatched name gets the real candidates.
61
+ """
62
+ payload = run.client().get(f"/assets/{resolve.asset_path(kind)}/creators")
63
+ items = list((payload or {}).get("items") or []) if isinstance(payload, dict) else []
64
+ for item in items:
65
+ if str(item.get("name") or "") == creator or str(item.get("id") or "") == creator:
66
+ return str(item.get("id"))
67
+ names = ", ".join(sorted(str(i.get("name")) for i in items)) or "none"
68
+ raise UsageError(
69
+ f'No creator named "{creator}" owns {kind} assets here.',
70
+ f"Creators with {kind} assets: {names}.",
71
+ )
72
+
73
+
74
+ def _list_assets(
75
+ run,
76
+ kind: str,
77
+ *,
78
+ scope: str,
79
+ page: int,
80
+ page_size: int,
81
+ search: str | None,
82
+ filters: dict[str, str] | None = None,
83
+ ) -> None:
84
+ client = run.client()
85
+ backend_scope = enums.ASSET_SCOPE.to_backend(scope)
86
+ params: dict[str, object] = {"scope": backend_scope, "search": search}
87
+ params.update({k: v for k, v in (filters or {}).items() if v})
88
+ items, page_no, size, total = fetch_page(
89
+ client, f"/assets/{resolve.asset_path(kind)}",
90
+ params=params, page=page, page_size=page_size,
91
+ )
92
+ tag_lookup = _tag_resolver(client, kind)
93
+ dtos = [
94
+ AssetDTO.from_api(raw, scope=scope, tags=tag_lookup(raw.get("tag_ids") or []))
95
+ for raw in items
96
+ ]
97
+ render.render_list(
98
+ run, dtos, AssetDTO.columns(kind),
99
+ page=page_no, page_size=size, total=total,
100
+ empty_message=f"No {kind}s found in scope {scope}.",
101
+ )
102
+
103
+
104
+ def _tag_resolver(client, kind: str):
105
+ """Return a tag_ids -> labels function that degrades to raw ids on failure.
106
+
107
+ Assets store tag ids; users read and type ``group:name``. One extra request
108
+ per command buys the translation, and a failure there must not take the
109
+ listing down with it.
110
+ """
111
+ from infix_cli.errors import CliError
112
+
113
+ try:
114
+ index = {str(t.get("id")): resolve.tag_label(t) for t in resolve.tag_index(client, kind)}
115
+ except CliError:
116
+ index = {}
117
+
118
+ def lookup(tag_ids: list) -> list[str]:
119
+ return [index.get(str(t), str(t)) for t in tag_ids]
120
+
121
+ return lookup
122
+
123
+
124
+ def _get_asset(
125
+ run, kind: str, name: str, scope_flag: str | None, *, version: str | None = None,
126
+ ) -> None:
127
+ client = run.client()
128
+ plain, backend_scope = _split_scope(name, scope_flag)
129
+ if version and backend_scope == "official":
130
+ raise UsageError(
131
+ "Official assets expose only their latest version.",
132
+ f"Drop --version, or reference the workspace copy with workspace/{plain}.",
133
+ )
134
+ raw = resolve.find_asset(client, kind, plain, backend_scope)
135
+ detail = client.get(f"/assets/{resolve.asset_path(kind)}/{raw['id']}")
136
+ versions = resolve.list_versions(client, kind, str(raw["id"]))
137
+ chosen = _select_version(versions, version, plain, kind)
138
+ tag_lookup = _tag_resolver(client, kind)
139
+ payload = detail if isinstance(detail, dict) else raw
140
+ dto = AssetDTO.from_api(
141
+ payload,
142
+ scope=_cli_scope(backend_scope),
143
+ tags=tag_lookup(payload.get("tag_ids") or []),
144
+ version_count=len(versions),
145
+ selected_version=chosen,
146
+ )
147
+ if kind == "model" and chosen:
148
+ dto.related_evaluation = _related_evaluation(run, client, str(chosen.get("id") or ""))
149
+ render.render_detail(run, dto)
150
+
151
+
152
+ def _select_version(versions: list[dict], wanted: str | None, name: str, kind: str) -> dict | None:
153
+ """Pick the version to describe: the requested one, or the latest usable."""
154
+ if wanted:
155
+ for entry in versions:
156
+ if str(entry.get("version_number")) == wanted:
157
+ return entry
158
+ available = ", ".join(str(v.get("version_number")) for v in versions) or "none"
159
+ raise NotFoundError(
160
+ f'Version "{wanted}" not found for {kind} "{name}".',
161
+ f"Available versions: {available}.",
162
+ )
163
+ for entry in versions:
164
+ if enums.ASSET_STATUS.to_cli(entry.get("status")) == "available":
165
+ return entry
166
+ return versions[0] if versions else None
167
+
168
+
169
+ def _related_evaluation(run, client, version_id: str) -> str | None:
170
+ """Find an evaluation run of this model version, for the PRD's link field.
171
+
172
+ The URL is assembled from the configured API endpoint, which assumes the
173
+ console is served from the same host. The backend does not return a
174
+ detail URL yet (see tech-design §4.8); once it does, this should use it
175
+ rather than guessing at the front-end's routing.
176
+ """
177
+ from infix_cli.errors import CliError
178
+
179
+ if not version_id:
180
+ return None
181
+ try:
182
+ payload = client.get(
183
+ "/evaluation/jobs", params={"model_version_id": version_id, "page_size": 1},
184
+ )
185
+ except CliError:
186
+ return None
187
+ items = list((payload or {}).get("items") or []) if isinstance(payload, dict) else []
188
+ if not items:
189
+ return None
190
+ job = items[0]
191
+ return run.profile.web_url(f"evaluation/{job.get('id')}")
192
+
193
+
194
+ def _list_versions(run, kind: str, name: str, scope_flag: str | None, page: int, page_size: int) -> None:
195
+ client = run.client()
196
+ plain, backend_scope = _split_scope(name, scope_flag)
197
+ asset = resolve.find_asset(client, kind, plain, backend_scope)
198
+ versions = resolve.list_versions(client, kind, str(asset["id"]))
199
+ dtos = [AssetVersionDTO.from_api(v) for v in versions]
200
+ from infix_cli.http.pagination import slice_page
201
+
202
+ render.render_list(
203
+ run, slice_page(dtos, page, page_size), AssetVersionDTO.columns(),
204
+ page=page, page_size=page_size, total=len(dtos),
205
+ quiet_field="version",
206
+ empty_message=f'No versions registered for {kind} "{plain}".',
207
+ )
208
+
209
+
210
+ def _list_tags(run, category: str) -> None:
211
+ client = run.client()
212
+ tags = resolve.tag_index(client, category)
213
+ grouped: dict[str, list[str]] = {}
214
+ for tag in tags:
215
+ grouped.setdefault(str(tag.get("group") or "Other"), []).append(str(tag.get("name") or ""))
216
+
217
+ items = [
218
+ _TagDimension(dimension=dimension, values=sorted(values))
219
+ for dimension, values in sorted(grouped.items())
220
+ ]
221
+ render.render_list(
222
+ run, items, [("DIMENSION", "dimension"), ("VALUES", "values")],
223
+ page=None, page_size=None, total=len(items),
224
+ quiet_field="dimension",
225
+ empty_message=f"No {category} tags defined.",
226
+ )
227
+
228
+
229
+ class _TagDimension:
230
+ """Tiny DTO for the tag listing: one row per dimension."""
231
+
232
+ def __init__(self, dimension: str, values: list[str]) -> None:
233
+ self.dimension = dimension
234
+ self.values = values
235
+
236
+ def to_json(self) -> dict:
237
+ return {"dimension": self.dimension, "values": self.values}
238
+
239
+
240
+
241
+ def _usage_help(kind: str) -> str:
242
+ if kind == "dataset":
243
+ return "training | evaluation"
244
+ if kind == "code":
245
+ return "spark | training | service"
246
+ return "(not applicable to models)"
247
+
248
+
249
+ def _task_help(kind: str) -> str:
250
+ if kind == "dataset":
251
+ return "cpt | sft | rl | pre-training | post-training"
252
+ if kind == "code":
253
+ return f"{' | '.join(_register.CODE_TASKS)} (training code)"
254
+ return "(not applicable to models)"
255
+
256
+
257
+ def _reject_unsupported_filters(kind: str, *, usage: str | None, task: str | None) -> None:
258
+ if kind == "model":
259
+ flag = "--usage" if usage else "--task"
260
+ raise UsageError(
261
+ f"{flag} does not apply to models.",
262
+ "Filter models with --search, --scope or --tag instead.",
263
+ )
264
+ if task and kind == "code" and task not in _register.CODE_TASKS:
265
+ # PRD 3.5.1: code filters by training stage, with the training words
266
+ # only — the evaluation words describe datasets.
267
+ raise UsageError(
268
+ f'Invalid --task "{task}" for code.',
269
+ f"Valid: {', '.join(_register.CODE_TASKS)}.",
270
+ )
271
+
272
+
273
+ def _make_kind_app(kind: str) -> typer.Typer:
274
+ """Build the model / dataset / code sub-app — same verbs, same options."""
275
+ sub = typer.Typer(help=f"{kind.capitalize()} assets.", no_args_is_help=True)
276
+ is_dataset = kind == "dataset"
277
+
278
+ @sub.command("list")
279
+ def list_cmd( # noqa: D401 - typer command
280
+ ctx: typer.Context,
281
+ scope: str = typer.Option("workspace", "--scope", help="workspace | official"),
282
+ search: Optional[str] = typer.Option(None, "--search", help="Fuzzy name match."),
283
+ usage: Optional[str] = typer.Option(
284
+ None, "--usage", help=_usage_help(kind),
285
+ ),
286
+ task: Optional[str] = typer.Option(
287
+ None, "--task", help=_task_help(kind),
288
+ ),
289
+ creator: Optional[str] = typer.Option(
290
+ None, "--creator", help="Filter by creator (scope=workspace only).",
291
+ ),
292
+ visibility: Optional[str] = typer.Option(
293
+ None, "--visibility", help="private | public (scope=workspace only).",
294
+ ),
295
+ status: Optional[str] = typer.Option(
296
+ None, "--status",
297
+ help="registering | available | failed (scope=workspace only).",
298
+ ),
299
+ page: int = typer.Option(1, "--page", "-p", min=1),
300
+ page_size: int = typer.Option(None, "--page-size", min=1, max=_MAX_PAGE_SIZE),
301
+ ) -> None:
302
+ """List assets in this workspace or the official catalogue."""
303
+ run = ctx.obj
304
+ if scope not in ("workspace", "official"):
305
+ raise UsageError(f'Invalid --scope "{scope}". Valid: workspace, official.')
306
+ if scope == "official" and (creator or visibility or status):
307
+ # The PRD marks these three "scope=workspace only"; official assets
308
+ # are platform-owned, public, and always available.
309
+ raise UsageError(
310
+ "--creator, --visibility and --status apply to --scope workspace only.",
311
+ )
312
+ filters: dict[str, str] = {}
313
+ if usage or task:
314
+ # Models have neither field. Without this the shared signature would
315
+ # map --usage through the code vocabulary and send the backend a
316
+ # filter that silently matches nothing.
317
+ _reject_unsupported_filters(kind, usage=usage, task=task)
318
+ if usage:
319
+ mapper = enums.DATASET_USAGE if is_dataset else enums.CODE_USAGE
320
+ if usage not in mapper.cli_values:
321
+ raise UsageError(
322
+ f'Invalid --usage "{usage}".',
323
+ f"Valid: {', '.join(mapper.cli_values)}.",
324
+ )
325
+ filters["usage"] = mapper.to_backend(usage)
326
+ if task:
327
+ if task not in enums.DATASET_STAGE.cli_values:
328
+ raise UsageError(
329
+ f'Invalid --task "{task}".',
330
+ f"Valid: {', '.join(enums.DATASET_STAGE.cli_values)}.",
331
+ )
332
+ filters["stage"] = enums.DATASET_STAGE.to_backend(task)
333
+ if visibility:
334
+ if visibility not in enums.VISIBILITY.cli_values:
335
+ raise UsageError(
336
+ f'Invalid --visibility "{visibility}".',
337
+ f"Valid: {', '.join(enums.VISIBILITY.cli_values)}.",
338
+ )
339
+ filters["visibility"] = enums.VISIBILITY.to_backend(visibility)
340
+ if status:
341
+ if status not in enums.ASSET_STATUS.cli_values:
342
+ raise UsageError(
343
+ f'Invalid --status "{status}".',
344
+ "Valid: registering, available, failed.",
345
+ )
346
+ filters["status"] = enums.ASSET_STATUS.to_backend(status)
347
+ if creator:
348
+ filters["creator"] = _creator_id(run, kind, creator)
349
+
350
+ _list_assets(
351
+ run, kind, scope=scope, page=page,
352
+ page_size=run.default_page_size(page_size), search=search, filters=filters,
353
+ )
354
+
355
+ @sub.command("get")
356
+ def get_cmd(
357
+ ctx: typer.Context,
358
+ name: str = typer.Argument(..., help="Asset name, optionally prefixed with official/."),
359
+ scope: Optional[str] = typer.Option(None, "--scope", help="workspace | official"),
360
+ version: Optional[str] = typer.Option(
361
+ None, "--version", help="Version to show. Defaults to the latest.",
362
+ ),
363
+ ) -> None:
364
+ """Show one asset in detail."""
365
+ _get_asset(ctx.obj, kind, name, scope, version=version)
366
+
367
+ @sub.command("versions")
368
+ def versions_cmd(
369
+ ctx: typer.Context,
370
+ name: str = typer.Argument(..., help="Asset name, optionally prefixed with official/."),
371
+ scope: Optional[str] = typer.Option(None, "--scope", help="workspace | official"),
372
+ page: int = typer.Option(1, "--page", "-p", min=1),
373
+ page_size: int = typer.Option(None, "--page-size", min=1, max=_MAX_PAGE_SIZE),
374
+ ) -> None:
375
+ """List the registered versions of one asset."""
376
+ run = ctx.obj
377
+ _list_versions(run, kind, name, scope, page, run.default_page_size(page_size))
378
+
379
+ @sub.command("tags")
380
+ def tags_cmd(ctx: typer.Context) -> None:
381
+ """List the tag dimensions available for this asset type."""
382
+ _list_tags(ctx.obj, kind)
383
+
384
+ if is_dataset:
385
+ @sub.command("preview")
386
+ def preview_cmd(
387
+ ctx: typer.Context,
388
+ name: str = typer.Argument(..., help="Dataset name, optionally prefixed with official/."),
389
+ scope: Optional[str] = typer.Option(None, "--scope", help="workspace | official"),
390
+ version: Optional[str] = typer.Option(None, "--version", help="Version number, e.g. v1.0.0."),
391
+ rows: int = typer.Option(5, "--rows", "-r", min=1, max=20, help="Rows to show (max 20)."),
392
+ file: Optional[str] = typer.Option(None, "--file", help="Which shard to preview."),
393
+ ) -> None:
394
+ """Print the first rows of a dataset version."""
395
+ _preview_dataset(ctx.obj, name, scope, version, rows, file)
396
+
397
+ _attach_write_commands(sub, kind)
398
+ return sub
399
+
400
+
401
+ def _attach_write_commands(sub: typer.Typer, kind: str) -> None:
402
+ """Add register / add-version.
403
+
404
+ Defined per kind: the three disagree on almost every flag, and one merged
405
+ signature would put a --usage on models and an --inference-engine on
406
+ datasets.
407
+ """
408
+
409
+ if kind == "model":
410
+ @sub.command("register")
411
+ def register_model(
412
+ ctx: typer.Context,
413
+ name: str = typer.Option(..., "--name", "-n", help="Asset name (3-64 chars: letters, digits, . _ -)."),
414
+ source: str = typer.Option(..., "--source", "-s", help="storage | huggingface"),
415
+ path: str = typer.Option(
416
+ ..., "--path", "-p",
417
+ help="storage: path under Workspace Storage. huggingface: repo id, e.g. Qwen/Qwen2-7B.",
418
+ ),
419
+ version: str = typer.Option("v1.0.0", "--version", help="Version number for the first version."),
420
+ description: Optional[str] = typer.Option(None, "--description"),
421
+ visibility: str = typer.Option("private", "--visibility", help="private | public"),
422
+ tag: list[str] = typer.Option([], "--tag", "-t", help='Tag as "group:name". Repeatable.'),
423
+ inference_engine: Optional[str] = typer.Option(None, "--inference-engine"),
424
+ quantization: Optional[str] = typer.Option(None, "--quantization"),
425
+ owner: Optional[str] = typer.Option(
426
+ None, "--owner",
427
+ help="User id owning the storage path, when registering a file a "
428
+ "teammate shared. Defaults to you.",
429
+ ),
430
+ hf_revision: Optional[str] = typer.Option(None, "--hf-revision", help="Branch, tag or commit."),
431
+ hf_token: Optional[str] = typer.Option(None, "--hf-token", help="For private or gated repos."),
432
+ wait: bool = typer.Option(False, "--wait", help="Block until the version is available."),
433
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 2h. Default: 30s."),
434
+ ) -> None:
435
+ """Register a model asset."""
436
+ run = ctx.obj
437
+ _ensure_name_free(run, "model", name)
438
+ payload = _register.model_payload(
439
+ name, source=source, path=path, version=version, description=description,
440
+ visibility=visibility, tag_ids=_tag_ids(run, "model", tag),
441
+ inference_engine=inference_engine, quantization=quantization,
442
+ hf_revision=hf_revision, hf_token=hf_token, owner_user_id=owner,
443
+ )
444
+ _submit_registration(
445
+ run, "model", payload, wait=wait, timeout=timeout,
446
+ source=source, source_path=path,
447
+ )
448
+
449
+ elif kind == "dataset":
450
+ @sub.command("register")
451
+ def register_dataset(
452
+ ctx: typer.Context,
453
+ name: str = typer.Option(..., "--name", "-n"),
454
+ source: str = typer.Option(..., "--source", "-s", help="storage | local | huggingface"),
455
+ usage: str = typer.Option(..., "--usage", "-u", help="training | evaluation"),
456
+ path: str = typer.Option(
457
+ ..., "--path", "-p",
458
+ help="storage: Workspace Storage path. local: file to upload. huggingface: dataset id.",
459
+ ),
460
+ task: Optional[str] = typer.Option(
461
+ None, "--task", help="cpt | sft | rl | pre-training | post-training",
462
+ ),
463
+ file_format: Optional[str] = typer.Option(
464
+ None, "--format",
465
+ help=f"Evaluation JSONL schema: {' | '.join(_register.EVAL_FORMATS)}. "
466
+ "Required for a local evaluation dataset.",
467
+ ),
468
+ benchmark: Optional[str] = typer.Option(
469
+ None, "--benchmark", help="evalscope benchmark key, e.g. aime25.",
470
+ ),
471
+ version: str = typer.Option("v1.0.0", "--version"),
472
+ description: Optional[str] = typer.Option(None, "--description"),
473
+ visibility: str = typer.Option("private", "--visibility", help="private | public"),
474
+ tag: list[str] = typer.Option([], "--tag", "-t", help='Tag as "group:name". Repeatable.'),
475
+ owner: Optional[str] = typer.Option(
476
+ None, "--owner",
477
+ help="User id owning the storage path, when registering a file a "
478
+ "teammate shared. Defaults to you.",
479
+ ),
480
+ hf_revision: Optional[str] = typer.Option(None, "--hf-revision"),
481
+ hf_token: Optional[str] = typer.Option(None, "--hf-token"),
482
+ wait: bool = typer.Option(False, "--wait"),
483
+ timeout: Optional[str] = typer.Option(None, "--timeout"),
484
+ ) -> None:
485
+ """Register a dataset asset."""
486
+ run = ctx.obj
487
+ _ensure_name_free(run, "dataset", name)
488
+ # Everything that can be judged without the file is judged before
489
+ # it moves: a typo must not cost an upload.
490
+ _register.check_dataset_flags(
491
+ source=source, usage=usage, visibility=visibility, file_format=file_format,
492
+ )
493
+ task = _register.validate_dataset_task(usage, task)
494
+ tag_ids = _tag_ids(run, "dataset", tag)
495
+ artifact_url = None
496
+ if source == "local":
497
+ artifact_url = _upload_local_dataset(run, path, file_format)
498
+ payload = _register.dataset_payload(
499
+ name, source=source, usage=usage, path=path, artifact_url=artifact_url,
500
+ task=task, file_format=file_format, benchmark=benchmark, version=version,
501
+ description=description, visibility=visibility, tag_ids=tag_ids,
502
+ hf_revision=hf_revision, hf_token=hf_token, owner_user_id=owner,
503
+ )
504
+ _submit_registration(
505
+ run, "dataset", payload, wait=wait, timeout=timeout,
506
+ source=source, source_path=path, usage=usage, task=task,
507
+ )
508
+
509
+ elif kind == "code":
510
+ @sub.command("register")
511
+ def register_code(
512
+ ctx: typer.Context,
513
+ name: str = typer.Option(..., "--name", "-n"),
514
+ source: str = typer.Option(
515
+ ..., "--source", "-s", help="storage | local | git",
516
+ ),
517
+ usage: str = typer.Option(..., "--usage", "-u", help="spark | training | service"),
518
+ path: str = typer.Option(
519
+ ..., "--path", "-p", help="storage: Workspace Storage path. git: repository URL.",
520
+ ),
521
+ task: Optional[str] = typer.Option(
522
+ None, "--task",
523
+ help=f"Training stage this code targets: {' | '.join(_register.CODE_TASKS)}. "
524
+ "Only with --usage training.",
525
+ ),
526
+ git_branch: Optional[str] = typer.Option(None, "--git-branch", help="Branch, tag or commit."),
527
+ git_username: Optional[str] = typer.Option(None, "--git-username"),
528
+ git_token: Optional[str] = typer.Option(None, "--git-token"),
529
+ version: str = typer.Option("v1.0.0", "--version"),
530
+ description: Optional[str] = typer.Option(None, "--description"),
531
+ visibility: str = typer.Option("private", "--visibility", help="private | public"),
532
+ owner: Optional[str] = typer.Option(
533
+ None, "--owner",
534
+ help="User id owning the storage path, when registering a file a "
535
+ "teammate shared. Defaults to you.",
536
+ ),
537
+ tag: list[str] = typer.Option([], "--tag", "-t", help='Tag as "group:name". Repeatable.'),
538
+ wait: bool = typer.Option(False, "--wait"),
539
+ timeout: Optional[str] = typer.Option(None, "--timeout"),
540
+ ) -> None:
541
+ """Register a code asset."""
542
+ run = ctx.obj
543
+ _ensure_name_free(run, "code", name)
544
+ _register.check_code_flags(source=source, usage=usage, visibility=visibility)
545
+ task = _register.validate_code_task(usage, task)
546
+ tag_ids = _tag_ids(run, "code", tag)
547
+ artifact_url = None
548
+ if source == "local":
549
+ artifact_url = _upload_code_archive(run, path)
550
+ payload = _register.code_payload(
551
+ name, source=source, usage=usage, path=path, artifact_url=artifact_url,
552
+ task=task, git_branch=git_branch, git_username=git_username,
553
+ git_token=git_token, version=version, description=description,
554
+ visibility=visibility, tag_ids=tag_ids, owner_user_id=owner,
555
+ )
556
+ _submit_registration(
557
+ run, "code", payload, wait=wait, timeout=timeout,
558
+ source=source, source_path=path, git_branch=git_branch or "",
559
+ usage=usage, task=task,
560
+ )
561
+
562
+ @sub.command("delete")
563
+ def delete_asset(
564
+ ctx: typer.Context,
565
+ name: str = typer.Argument(..., help="Asset name."),
566
+ version: Optional[str] = typer.Option(None, "--version", help="Delete this one version."),
567
+ all_versions: bool = typer.Option(
568
+ False, "--all", help="Delete the asset with every version.",
569
+ ),
570
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
571
+ ) -> None:
572
+ """Delete one version of an asset, or the whole asset. This cannot be undone.
573
+
574
+ The version's files are removed from asset storage. Deleting the only
575
+ remaining version is refused — use --all to delete the asset.
576
+ """
577
+ plain, scope = _split_scope(name, None)
578
+ if scope == "official":
579
+ raise UsageError("Official assets are read-only.")
580
+ _delete.delete_asset(
581
+ ctx.obj, kind, plain, version=version, all_versions=all_versions, yes=yes,
582
+ )
583
+
584
+ @sub.command("publish")
585
+ def publish_asset(
586
+ ctx: typer.Context,
587
+ name: str = typer.Argument(..., help="Asset name."),
588
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
589
+ ) -> None:
590
+ """Make an asset public to the workspace. This cannot be undone."""
591
+ plain, scope = _split_scope(name, None)
592
+ if scope == "official":
593
+ raise UsageError("Official assets are already public to everyone.")
594
+ _publish.publish_asset(ctx.obj, kind, plain, yes=yes)
595
+
596
+ @sub.command("download")
597
+ def download_version(
598
+ ctx: typer.Context,
599
+ name: str = typer.Argument(..., help="Asset name; official/ prefix for official assets."),
600
+ version: Optional[str] = typer.Option(
601
+ None, "--version", help="Version to download. Default: the newest available.",
602
+ ),
603
+ path: Optional[str] = typer.Option(
604
+ None, "--path", "-p", help="Only this file or folder inside the version.",
605
+ ),
606
+ dest: Optional[str] = typer.Option(
607
+ None, "--dest", "-d", help="Local directory to download into. Defaults to the current one.",
608
+ ),
609
+ concurrency: int = typer.Option(4, "--concurrency", min=1, max=8),
610
+ overwrite: bool = typer.Option(
611
+ False, "--overwrite", help="Download from the beginning without reusing local files or partial downloads.",
612
+ ),
613
+ ) -> None:
614
+ """Download an asset version's files to <dest>/<name>-<version>/.
615
+
616
+ Re-running resumes: finished files are skipped and a partly downloaded
617
+ file continues from where it stopped.
618
+ """
619
+ from infix_cli.commands import _download
620
+
621
+ plain, scope = _split_scope(name, None)
622
+ _download.download_asset(
623
+ ctx.obj, kind, plain, scope, version=version, sub_path=path, dest=dest,
624
+ overwrite=overwrite, concurrency=concurrency,
625
+ )
626
+
627
+ @sub.command("wait")
628
+ def wait_version(
629
+ ctx: typer.Context,
630
+ name: str = typer.Argument(..., help="Asset name."),
631
+ version: Optional[str] = typer.Option(
632
+ None, "--version", help="Version to wait for. Default: the newest.",
633
+ ),
634
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 2h. Default: 30s."),
635
+ ) -> None:
636
+ """Wait for a version to finish registering; exit 0 if available, 7 if failed."""
637
+ plain, scope = _split_scope(name, None)
638
+ _wait_command(ctx.obj, kind, plain, scope, version=version, timeout=timeout)
639
+
640
+ _sources = " | ".join(_register.VERSION_SOURCES[kind])
641
+
642
+ if kind == "model":
643
+ @sub.command("add-version")
644
+ def add_version_model(
645
+ ctx: typer.Context,
646
+ name: Optional[str] = typer.Argument(None, help="Existing asset name."),
647
+ name_opt: Optional[str] = typer.Option(
648
+ None, "--name", "-n", help="Existing asset name (same as the argument).",
649
+ ),
650
+ version: Optional[str] = typer.Option(
651
+ None, "--version",
652
+ help="New version number, e.g. v1.1.0. Defaults to the next minor "
653
+ "version after the highest one this asset has.",
654
+ ),
655
+ source: str = typer.Option("storage", "--source", "-s", help=_sources),
656
+ path: Optional[str] = typer.Option(None, "--path", "-p"),
657
+ owner: Optional[str] = typer.Option(
658
+ None, "--owner",
659
+ help="User id owning the storage path, when the source is a file a "
660
+ "teammate shared. Defaults to you.",
661
+ ),
662
+ description: Optional[str] = typer.Option(None, "--description"),
663
+ hf_revision: Optional[str] = typer.Option(None, "--hf-revision"),
664
+ hf_token: Optional[str] = typer.Option(None, "--hf-token"),
665
+ wait: bool = typer.Option(False, "--wait"),
666
+ timeout: Optional[str] = typer.Option(None, "--timeout"),
667
+ ) -> None:
668
+ """Add a new version to an existing model."""
669
+ _submit_version(
670
+ ctx.obj, "model", _asset_name(name, name_opt), version=version, source=source, path=path,
671
+ description=description, hf_revision=hf_revision, hf_token=hf_token,
672
+ owner_user_id=owner, wait=wait, timeout=timeout,
673
+ )
674
+
675
+ elif kind == "dataset":
676
+ @sub.command("add-version")
677
+ def add_version_dataset(
678
+ ctx: typer.Context,
679
+ name: Optional[str] = typer.Argument(None, help="Existing asset name."),
680
+ name_opt: Optional[str] = typer.Option(
681
+ None, "--name", "-n", help="Existing asset name (same as the argument).",
682
+ ),
683
+ version: Optional[str] = typer.Option(
684
+ None, "--version",
685
+ help="New version number, e.g. v1.1.0. Defaults to the next minor "
686
+ "version after the highest one this asset has.",
687
+ ),
688
+ source: str = typer.Option("storage", "--source", "-s", help=_sources),
689
+ path: Optional[str] = typer.Option(
690
+ None, "--path", "-p",
691
+ help="storage: Workspace Storage path. local: file to upload. "
692
+ "huggingface: dataset id.",
693
+ ),
694
+ file_format: Optional[str] = typer.Option(
695
+ None, "--format",
696
+ help=f"Evaluation JSONL schema: {' | '.join(_register.EVAL_FORMATS)}. "
697
+ "Local evaluation files are checked against it; defaults to "
698
+ "the schema the dataset already records.",
699
+ ),
700
+ owner: Optional[str] = typer.Option(
701
+ None, "--owner",
702
+ help="User id owning the storage path, when the source is a file a "
703
+ "teammate shared. Defaults to you.",
704
+ ),
705
+ description: Optional[str] = typer.Option(None, "--description"),
706
+ hf_revision: Optional[str] = typer.Option(None, "--hf-revision"),
707
+ hf_token: Optional[str] = typer.Option(None, "--hf-token"),
708
+ wait: bool = typer.Option(False, "--wait"),
709
+ timeout: Optional[str] = typer.Option(None, "--timeout"),
710
+ ) -> None:
711
+ """Add a new version to an existing dataset."""
712
+ _submit_version(
713
+ ctx.obj, "dataset", _asset_name(name, name_opt), version=version, source=source, path=path,
714
+ file_format=file_format, description=description,
715
+ hf_revision=hf_revision, hf_token=hf_token, owner_user_id=owner,
716
+ wait=wait, timeout=timeout,
717
+ )
718
+
719
+ elif kind == "code":
720
+ @sub.command("add-version")
721
+ def add_version_code(
722
+ ctx: typer.Context,
723
+ name: Optional[str] = typer.Argument(None, help="Existing asset name."),
724
+ name_opt: Optional[str] = typer.Option(
725
+ None, "--name", "-n", help="Existing asset name (same as the argument).",
726
+ ),
727
+ version: Optional[str] = typer.Option(
728
+ None, "--version",
729
+ help="New version number, e.g. v1.1.0. Defaults to the next minor "
730
+ "version after the highest one this asset has.",
731
+ ),
732
+ source: str = typer.Option("storage", "--source", "-s", help=_sources),
733
+ path: Optional[str] = typer.Option(
734
+ None, "--path", "-p",
735
+ help="storage: Workspace Storage path. local: archive to upload. "
736
+ "git: repository URL.",
737
+ ),
738
+ git_branch: Optional[str] = typer.Option(None, "--git-branch", help="Branch, tag or commit."),
739
+ git_username: Optional[str] = typer.Option(None, "--git-username"),
740
+ git_token: Optional[str] = typer.Option(None, "--git-token"),
741
+ owner: Optional[str] = typer.Option(
742
+ None, "--owner",
743
+ help="User id owning the storage path, when the source is a file a "
744
+ "teammate shared. Defaults to you.",
745
+ ),
746
+ description: Optional[str] = typer.Option(None, "--description"),
747
+ wait: bool = typer.Option(False, "--wait"),
748
+ timeout: Optional[str] = typer.Option(None, "--timeout"),
749
+ ) -> None:
750
+ """Add a new version to an existing code asset."""
751
+ _submit_version(
752
+ ctx.obj, "code", _asset_name(name, name_opt), version=version, source=source, path=path,
753
+ description=description, git_branch=git_branch,
754
+ git_username=git_username, git_token=git_token, owner_user_id=owner,
755
+ wait=wait, timeout=timeout,
756
+ )
757
+
758
+
759
+ def _asset_name(argument: str | None, option: str | None) -> str:
760
+ """add-version takes the asset name as an argument, like ``get``, or as
761
+ ``--name/-n``, which is how the PRD writes it (3.3.6). Either works; two
762
+ different names are refused rather than one silently winning."""
763
+ if argument and option and argument != option:
764
+ raise UsageError(
765
+ f'Two asset names given: "{argument}" and --name "{option}".',
766
+ "Pass the name once.",
767
+ )
768
+ name = argument or option
769
+ if not name:
770
+ raise UsageError("Missing the asset name.", "Pass it as an argument or with --name.")
771
+ return name
772
+
773
+
774
+ def _submit_version(
775
+ run,
776
+ kind: str,
777
+ name: str,
778
+ *,
779
+ version: str | None,
780
+ source: str,
781
+ path: str | None,
782
+ description: str | None,
783
+ file_format: str | None = None,
784
+ git_branch: str | None = None,
785
+ git_username: str | None = None,
786
+ git_token: str | None = None,
787
+ hf_revision: str | None = None,
788
+ hf_token: str | None = None,
789
+ owner_user_id: str | None = None,
790
+ wait: bool,
791
+ timeout,
792
+ ) -> None:
793
+ """Resolve the asset, stage a local source if any, then post the version."""
794
+ client = run.client()
795
+ plain, backend_scope = _split_scope(name, None)
796
+ if backend_scope == "official":
797
+ raise UsageError(
798
+ "Official assets are read-only.",
799
+ "Register your own copy with asset "
800
+ f"{kind} register, then add versions to it.",
801
+ )
802
+ asset = resolve.find_asset(client, kind, plain, backend_scope)
803
+ if kind == "dataset":
804
+ # Settled before the version number is looked up and before any bytes
805
+ # move: a schema mismatch must not cost an upload.
806
+ file_format = _register.version_eval_format(
807
+ asset, source=source, file_format=file_format,
808
+ )
809
+ if version:
810
+ _ensure_version_free(client, kind, str(asset["id"]), plain, version)
811
+ else:
812
+ version = _register.next_version_number(
813
+ resolve.list_versions(client, kind, str(asset["id"])),
814
+ )
815
+
816
+ artifact_url = None
817
+ if source == "local":
818
+ # Same two-step as registration: the file is staged first and the
819
+ # version references what came back. Done after the asset is resolved so
820
+ # a wrong name does not cost an upload.
821
+ if kind == "dataset":
822
+ artifact_url = _upload_local_dataset(run, _require_path(path), file_format)
823
+ elif kind == "code":
824
+ artifact_url = _upload_code_archive(run, _require_path(path))
825
+
826
+ payload = _register.version_payload(
827
+ version, source=source, path=path, artifact_url=artifact_url,
828
+ description=description, git_branch=git_branch, git_username=git_username,
829
+ git_token=git_token, hf_revision=hf_revision, hf_token=hf_token,
830
+ owner_user_id=owner_user_id, kind=kind,
831
+ )
832
+ created = client.post(
833
+ f"/assets/{resolve.asset_path(kind)}/{asset['id']}/versions", json=payload,
834
+ )
835
+ _report_version(
836
+ run, kind, str(asset["id"]), plain, created, wait=wait, timeout=timeout,
837
+ source=source,
838
+ )
839
+
840
+
841
+ def _wait_command(run, kind: str, plain: str, scope: str, *, version: str | None, timeout) -> None:
842
+ """``asset <kind> wait``: re-attach to a registration or add-version."""
843
+ client = run.client()
844
+ asset = resolve.find_asset(client, kind, plain, scope)
845
+ asset_id = str(asset["id"])
846
+ versions = [
847
+ v for v in resolve.list_versions(client, kind, asset_id)
848
+ if str(v.get("status") or "") != "Deleted"
849
+ ]
850
+ if version:
851
+ target = next((v for v in versions if str(v.get("version_number")) == version), None)
852
+ if target is None:
853
+ raise NotFoundError(
854
+ f'{kind.capitalize()} "{plain}" has no version "{version}".',
855
+ f'See "infix asset {kind} versions {plain}".',
856
+ )
857
+ elif versions:
858
+ target = max(versions, key=lambda v: str(v.get("created_at") or ""))
859
+ else:
860
+ raise NotFoundError(f'{kind.capitalize()} "{plain}" has no versions.')
861
+
862
+ number = str(target.get("version_number") or "")
863
+ status = enums.ASSET_STATUS.to_cli(target.get("status"))
864
+ if status not in enums.ASSET_VERSION_TERMINAL:
865
+ status, target = _wait_for_version(
866
+ run, kind, asset_id, target, name=plain, timeout=timeout,
867
+ )
868
+ if status in enums.ASSET_VERSION_UNUSABLE:
869
+ _fail_registration(
870
+ run, _register_output.version_title(kind, plain, number, state="failed"),
871
+ kind, plain, version_id=str(target.get("id") or ""),
872
+ )
873
+ if run.output == "json":
874
+ render.render_detail(run, AssetDTO.from_api(
875
+ _fetch_asset(run, kind, asset_id) or asset, scope="workspace", tags=[],
876
+ ))
877
+ return
878
+ render.message(run, _register_output.version_title(
879
+ kind, plain, number, state=_register_output.status_display(status),
880
+ ))
881
+
882
+
883
+ def _ensure_version_free(client, kind: str, asset_id: str, name: str, version: str) -> None:
884
+ """Reject a version number the asset already has, before any bytes move.
885
+
886
+ The backend answers a duplicate with 409 — but only after a local source
887
+ has been uploaded, and as exit 1 rather than the usage error it is.
888
+ Best-effort: when the listing cannot be read, the backend still has the
889
+ final say, so that is not treated as a failure.
890
+ """
891
+ try:
892
+ existing = resolve.list_versions(client, kind, asset_id)
893
+ except CliError:
894
+ return
895
+ if any(str(v.get("version_number") or "") == version for v in existing):
896
+ raise UsageError(
897
+ f'Failed: Version "{version}" already exists for {kind} "{name}".',
898
+ f'See "infix asset {kind} versions {name}", or omit --version to take '
899
+ "the next one.",
900
+ )
901
+
902
+
903
+ def _require_path(path: str | None) -> str:
904
+ if not path:
905
+ raise UsageError("--path is required for this source.")
906
+ return path
907
+
908
+
909
+ def _preview_dataset(
910
+ run,
911
+ name: str,
912
+ scope_flag: str | None,
913
+ version: str | None,
914
+ rows: int,
915
+ file: str | None,
916
+ ) -> None:
917
+ client = run.client()
918
+ plain, backend_scope = _split_scope(name, scope_flag)
919
+ if backend_scope == "official" and version:
920
+ raise UsageError(
921
+ "Official datasets expose only their latest version.",
922
+ "Drop --version, or reference the workspace copy with workspace/<name>.",
923
+ )
924
+ asset = resolve.find_asset(client, "dataset", plain, backend_scope)
925
+ asset_id = str(asset["id"])
926
+ versions = resolve.list_versions(client, "dataset", asset_id)
927
+ chosen = _pick_version(versions, version, plain)
928
+ version_id = str(chosen["id"])
929
+
930
+ names = _data_files(client, asset_id, version_id)
931
+ if not names:
932
+ raise NotFoundError(
933
+ f'Version "{chosen.get("version_number")}" contains no readable data files.',
934
+ )
935
+ if file:
936
+ target = _match_requested_file(file, names)
937
+ else:
938
+ # Multi-shard datasets have no single "the" file; the first one is a
939
+ # defensible default as long as the output says which it is.
940
+ target = names[0]
941
+
942
+ content = client.get(
943
+ f"/assets/datasets/{asset_id}/versions/{version_id}/files/content",
944
+ params={"path": target, "lines": rows},
945
+ )
946
+ text_body = content if isinstance(content, str) else str(content)
947
+ shard_rows, body = _split_preview_header(text_body)
948
+ lines = [line for line in body if line.strip()][:rows]
949
+
950
+ metrics = (chosen.get("metrics") or {})
951
+ # A registered dataset carries its sample count; an official one usually
952
+ # does not, and then the shard's own header is the only count available.
953
+ total = metrics.get("total_samples") or shard_rows
954
+ payload = {
955
+ "dataset": plain,
956
+ "version": chosen.get("version_number"),
957
+ "format": asset.get("format"),
958
+ "total_rows": total,
959
+ "file": target,
960
+ "file_index": names.index(target) + 1,
961
+ "file_count": len(names),
962
+ "showing": {"from": 1, "to": len(lines)},
963
+ "rows": lines,
964
+ }
965
+ if run.output == "json":
966
+ render.render_object(run, payload, [])
967
+ return
968
+ if run.quiet:
969
+ for line in lines:
970
+ print(line)
971
+ return
972
+
973
+ from infix_cli.domain.dto.common import EMPTY, format_count
974
+ from infix_cli.render import text as text_render
975
+
976
+ prefix = "official" if backend_scope == "official" else "workspace"
977
+ header = [
978
+ ("Dataset", f"{prefix}/{plain}"),
979
+ ("Version", str(chosen.get("version_number"))),
980
+ ("Format", str(asset.get("format") or EMPTY)),
981
+ ("Total", f"{format_count(total)} rows" if total else EMPTY),
982
+ ("Showing", f"rows 1-{len(lines)}" if lines else "no rows"),
983
+ ]
984
+ if len(names) > 1:
985
+ # Not in the PRD, which does not cover sharded datasets: without it a
986
+ # preview of one shard reads as a preview of the whole dataset.
987
+ header.append(("File", f"{target} ({names.index(target) + 1} of {len(names)})"))
988
+ elif "/" in target:
989
+ # One file, but not where the user would have looked for it. Naming it
990
+ # is what makes the next command — --file, or a download — writable.
991
+ header.append(("File", target))
992
+ text_render.print_labeled(run, header, indent=0, gutter=2)
993
+
994
+ for index, line in enumerate(lines, start=1):
995
+ print()
996
+ print(f"Row {index}")
997
+ print(line)
998
+
999
+
1000
+ # Extensions a dataset's samples actually live in, best first. Ordering is
1001
+ # what makes a Hugging Face export preview usefully: those ship the rows as
1002
+ # parquet next to a README and a .gitattributes, and picking by directory
1003
+ # order lands on the repository furniture instead of the data.
1004
+ _DATA_SUFFIXES = (
1005
+ ".jsonl", ".json", ".parquet", ".csv", ".tsv", ".arrow", ".txt", ".ndjson",
1006
+ )
1007
+ # Files that sit beside a dataset without being one. ``dataset_infos.json`` is
1008
+ # the one .json that has to be named: it is Hugging Face's metadata sidecar,
1009
+ # so the suffix rule above would otherwise rank it as data.
1010
+ _NON_DATA_NAMES = frozenset({".gitattributes", "dataset_infos.json"})
1011
+ _NON_DATA_SUFFIXES = (".md", ".yaml", ".yml", ".py", ".sh", ".lock", ".gitignore")
1012
+ # How deep to look for the data directory. Hugging Face nests one level
1013
+ # (``data/``, ``plain_text/``); two covers a per-config layout under that,
1014
+ # and stopping there keeps a wide export from turning into a crawl.
1015
+ _MAX_PREVIEW_DEPTH = 3
1016
+
1017
+
1018
+ def _data_files(client, asset_id: str, version_id: str) -> list[str]:
1019
+ """Paths worth previewing, best candidate first.
1020
+
1021
+ The listing endpoint returns one directory at a time, and a dataset's rows
1022
+ are routinely a level below the version root — a Hugging Face export keeps
1023
+ them under ``data/`` and leaves only a README and a .gitattributes on top.
1024
+ Reading just the root therefore previewed the furniture rather than the
1025
+ dataset, so this walks down until a directory yields real data files.
1026
+ """
1027
+ base = f"/assets/datasets/{asset_id}/versions/{version_id}/files"
1028
+
1029
+ def listing(path: str | None) -> list[dict]:
1030
+ payload = client.get(base, params={"path": path} if path else None) or {}
1031
+ return [e for e in payload.get("entries") or [] if e.get("name")]
1032
+
1033
+ found: list[tuple[str, int]] = []
1034
+ fallback: list[str] = []
1035
+ # Breadth-first: a shallower file beats a deeper one at the same rank, so
1036
+ # the top-level shards of a flat dataset win over anything nested.
1037
+ queue: list[tuple[str | None, int]] = [(None, 0)]
1038
+ while queue:
1039
+ prefix, depth = queue.pop(0)
1040
+ try:
1041
+ entries = listing(prefix)
1042
+ except Exception:
1043
+ if prefix is None:
1044
+ # The version root itself is unreadable, so there is no tree to
1045
+ # fall back on. Its reason — a version still being copied comes
1046
+ # back as 409 — is the whole answer, and swallowing it reported
1047
+ # "contains no readable data files", which sends the reader off
1048
+ # to inspect a dataset that is merely not ready yet.
1049
+ raise
1050
+ # One unreadable subdirectory must not sink a preview that the
1051
+ # rest of the tree can still serve.
1052
+ continue
1053
+ for entry in entries:
1054
+ name = str(entry.get("name"))
1055
+ path = f"{prefix}/{name}" if prefix else name
1056
+ if entry.get("is_dir"):
1057
+ if depth + 1 < _MAX_PREVIEW_DEPTH:
1058
+ queue.append((path, depth + 1))
1059
+ elif _is_data_file(name):
1060
+ size = entry.get("size")
1061
+ found.append((path, size if isinstance(size, int) else 0))
1062
+ else:
1063
+ fallback.append(path)
1064
+ # Once a level has produced data files, deeper ones can only be shards
1065
+ # of the same thing; stop rather than walking the whole export.
1066
+ if found and not any(d == depth for _, d in queue):
1067
+ break
1068
+
1069
+ found.sort(key=_data_rank)
1070
+ # Nothing recognisable is still worth showing — a dataset stored with no
1071
+ # extension at all reads better than "contains no readable data files".
1072
+ return [path for path, _ in found] or fallback
1073
+
1074
+
1075
+ def _is_data_file(name: str) -> bool:
1076
+ lowered = name.lower()
1077
+ if lowered in _NON_DATA_NAMES or lowered.startswith("."):
1078
+ return False
1079
+ if lowered.endswith(_NON_DATA_SUFFIXES):
1080
+ return False
1081
+ return lowered.endswith(_DATA_SUFFIXES)
1082
+
1083
+
1084
+ def _data_rank(item: tuple[str, int]) -> tuple[int, int, int, str]:
1085
+ """Sort key: preferred extension, then shallower, then larger, then name.
1086
+
1087
+ Size before name because a split directory routinely holds a token
1088
+ auxiliary shard alongside the real one — mbpp's ten-row ``prompt`` file
1089
+ sorts ahead of its ``test`` split by name, and previewing that says
1090
+ nothing about the dataset. Name last keeps two runs against the same
1091
+ version on the same file.
1092
+ """
1093
+ path, size = item
1094
+ lowered = path.lower()
1095
+ suffix_rank = next(
1096
+ (i for i, suffix in enumerate(_DATA_SUFFIXES) if lowered.endswith(suffix)),
1097
+ len(_DATA_SUFFIXES),
1098
+ )
1099
+ return (suffix_rank, path.count("/"), -size, path)
1100
+
1101
+
1102
+ def _match_requested_file(wanted: str, names: list[str]) -> str:
1103
+ """Resolve ``--file`` against the discovered paths.
1104
+
1105
+ A bare file name is accepted for a nested shard: the user reads
1106
+ ``train-00000-of-00001.parquet`` off the preview header and should not
1107
+ have to retype the directory that got it there.
1108
+ """
1109
+ if wanted in names:
1110
+ return wanted
1111
+ tail_matches = [p for p in names if p.rsplit("/", 1)[-1] == wanted]
1112
+ if len(tail_matches) == 1:
1113
+ return tail_matches[0]
1114
+ if len(tail_matches) > 1:
1115
+ raise UsageError(
1116
+ f'File "{wanted}" is ambiguous in this version.',
1117
+ f"Matches: {', '.join(tail_matches)}.",
1118
+ )
1119
+ raise UsageError(
1120
+ f'File "{wanted}" is not part of this version.',
1121
+ f"Files: {', '.join(names)}.",
1122
+ )
1123
+
1124
+
1125
+ def _split_preview_header(body: str) -> tuple[int | None, list[str]]:
1126
+ """Separate the parquet preamble from the rows it describes.
1127
+
1128
+ A parquet shard comes back as two ``#`` comment lines (row count, schema)
1129
+ followed by JSONL. Counting those as rows meant ``--rows 2`` showed the
1130
+ preamble and no data at all, so they are lifted out here — and the row
1131
+ count they carry is the only total an official dataset publishes.
1132
+ """
1133
+ lines = body.splitlines()
1134
+ total: int | None = None
1135
+ index = 0
1136
+ while index < len(lines):
1137
+ marker = lines[index]
1138
+ if marker.startswith("# parquet:"):
1139
+ digits = "".join(ch for ch in marker.split("rows")[0] if ch.isdigit())
1140
+ total = int(digits) if digits else None
1141
+ elif not marker.startswith("# schema:"):
1142
+ # Any other line — including a file that merely opens with a
1143
+ # comment — is content, and stays in the body.
1144
+ break
1145
+ index += 1
1146
+ return total, lines[index:]
1147
+
1148
+
1149
+ def _pick_version(versions: list[dict], wanted: str | None, name: str) -> dict:
1150
+ if wanted:
1151
+ for version in versions:
1152
+ if str(version.get("version_number")) == wanted:
1153
+ return version
1154
+ available = ", ".join(str(v.get("version_number")) for v in versions) or "none"
1155
+ raise NotFoundError(
1156
+ f'Version "{wanted}" not found for dataset "{name}".',
1157
+ f"Available versions: {available}.",
1158
+ )
1159
+ for version in versions:
1160
+ if enums.ASSET_STATUS.to_cli(version.get("status")) == "available":
1161
+ return version
1162
+ raise NotFoundError(f'Dataset "{name}" has no available version yet.')
1163
+
1164
+
1165
+ # ── registration plumbing ───────────────────────────────────────────────────
1166
+
1167
+
1168
+ def _ensure_name_free(run, kind: str, name: str) -> None:
1169
+ """Reject a name already taken, before any bytes move.
1170
+
1171
+ The backend rejects duplicates too, but only once the file has been
1172
+ transferred — so a local registration spends the whole upload before
1173
+ failing. The PRD puts this in the immediate-validation group, and on a
1174
+ multi-hundred-megabyte dataset the difference is the whole point.
1175
+ """
1176
+ try:
1177
+ resolve.find_asset(run.client(), kind, name, "my")
1178
+ except NotFoundError:
1179
+ return
1180
+ raise UsageError(
1181
+ f'Registration failed: {kind.capitalize()} name "{name}" '
1182
+ f"already exists in this workspace.",
1183
+ f'Pick another name, or add to it with '
1184
+ f'"infix asset {kind} add-version {name} --version <version>".',
1185
+ )
1186
+
1187
+
1188
+ def _tag_ids(run, category: str, labels: list[str]) -> list[str]:
1189
+ """Resolve "group:name" tags to the ids the backend stores."""
1190
+ if not labels:
1191
+ return []
1192
+ return resolve.resolve_tag_ids(run.client(), category, labels)
1193
+
1194
+
1195
+ def _upload_local_dataset(run, path: str, file_format: str | None) -> str:
1196
+ """Stage a local file and return the artifact_url registration needs.
1197
+
1198
+ Local datasets are the one kind registered in two calls: the file goes to
1199
+ object storage first, and the registration then references what came back.
1200
+ """
1201
+ from pathlib import Path
1202
+
1203
+ source = Path(path).expanduser()
1204
+ if not source.is_file():
1205
+ raise UsageError(f'File not found: "{path}".')
1206
+ with source.open("rb") as handle:
1207
+ response = run.client().post_multipart(
1208
+ "/assets/datasets/upload-local",
1209
+ files={"file": (source.name, handle)},
1210
+ params={"format": file_format},
1211
+ )
1212
+ artifact_url = (response or {}).get("artifact_url")
1213
+ if not artifact_url:
1214
+ raise UsageError("Upload succeeded but returned no artifact URL.")
1215
+ render.message(run, f"Uploaded {source.name}.")
1216
+ return str(artifact_url)
1217
+
1218
+
1219
+ # Code registers through /assets/code/create; model and dataset through
1220
+ # .../register. The backend's own route table flags the inconsistency
1221
+ # ("create" not "register"), so it is spelled out here rather than derived.
1222
+ _REGISTER_VERB = {"model": "register", "dataset": "register", "code": "create"}
1223
+
1224
+
1225
+
1226
+ def _upload_code_archive(run, path: str) -> str:
1227
+ """Stage a local code file or archive and return its artifact URL.
1228
+
1229
+ Code has no upload-local endpoint of its own; it goes through the chunked
1230
+ upload session with purpose=code_asset, which stages the file (extracting
1231
+ it first if it is an archive) and hands back the URL registration needs.
1232
+ """
1233
+ from pathlib import Path
1234
+
1235
+ from infix_cli.http import upload as upload_mod
1236
+
1237
+ source = Path(path).expanduser()
1238
+ if not source.is_file():
1239
+ raise UsageError(
1240
+ f'Not a file: "{path}".',
1241
+ "Pass a file or an archive; upload a directory with "
1242
+ '"infix storage upload" and register it with --source storage.',
1243
+ )
1244
+ # Same transfer as "storage upload", so it reports the same way: a code
1245
+ # archive can be hundreds of megabytes, and a silent command gives no way
1246
+ # to tell a slow upload from a stalled one.
1247
+ tracker = progress.tracker(run, source.name, source.stat().st_size)
1248
+ try:
1249
+ result = upload_mod.upload_file(
1250
+ run.client(), source, purpose="code_asset", on_progress=tracker,
1251
+ )
1252
+ finally:
1253
+ progress.finish(run)
1254
+ if not result.artifact_url:
1255
+ raise UsageError("Upload succeeded but returned no artifact URL.")
1256
+ render.message(run, f"Uploaded {source.name}.")
1257
+ return result.artifact_url
1258
+
1259
+
1260
+ def _submit_registration(
1261
+ run,
1262
+ kind: str,
1263
+ payload: dict,
1264
+ *,
1265
+ wait: bool,
1266
+ timeout,
1267
+ source: str = "",
1268
+ source_path: str = "",
1269
+ git_branch: str = "",
1270
+ usage: str | None = None,
1271
+ task: str | None = None,
1272
+ ) -> None:
1273
+ """POST a registration and report it the way the PRD does (§3.3)."""
1274
+ path = f"/assets/{resolve.asset_path(kind)}/{_REGISTER_VERB[kind]}"
1275
+ created = run.client().post(path, json=payload)
1276
+ if not isinstance(created, dict):
1277
+ raise UsageError("Registration returned an unexpected response.")
1278
+
1279
+ name = str(created.get("name") or payload.get("name") or "")
1280
+ version_row = created.get("latest_version") or {}
1281
+ version = str(version_row.get("version_number") or payload.get("version_number") or "")
1282
+ visibility = enums.VISIBILITY.to_cli(created.get("visibility")) or "private"
1283
+ _warn_if_stage_dropped(run, kind, payload, created, task)
1284
+
1285
+ if run.output == "json":
1286
+ _registration_json(
1287
+ run, kind, name, created, version_row, wait=wait, timeout=timeout, source=source,
1288
+ )
1289
+ return
1290
+
1291
+ src_kind, src_detail = _register_output.source_summary(
1292
+ source, source_path, git_branch=git_branch,
1293
+ )
1294
+ if not wait:
1295
+ status = enums.ASSET_STATUS.to_cli(version_row.get("status")) or "registering"
1296
+ render.message(run, _register_output.title(kind, name, state="submitted"))
1297
+ text.print_labeled(run, _register_output.submitted_rows(
1298
+ kind, version=version, usage=usage, task=task,
1299
+ source=src_kind, source_detail=src_detail, visibility=visibility,
1300
+ status=_register_output.status_display(status),
1301
+ ), gutter=1)
1302
+ _print_next_steps(run, kind, name, waited=False, pending=status == "registering")
1303
+ return
1304
+
1305
+ # The PRD prints the submission line before waiting, so an interrupted
1306
+ # wait still leaves a record of what was accepted.
1307
+ render.message(run, _register_output.title(kind, name, state="submitted"))
1308
+ status, final_version = _wait_for_version(
1309
+ run, kind, str(created.get("id") or ""), version_row, name=name,
1310
+ timeout=timeout, source=source,
1311
+ )
1312
+ _report_completion(
1313
+ run, kind, name,
1314
+ version=str(final_version.get("version_number") or version),
1315
+ status=status, usage=usage, task=task, visibility=visibility,
1316
+ metrics=final_version.get("metrics") or {},
1317
+ version_id=str(final_version.get("id") or version_row.get("id") or ""),
1318
+ source=source,
1319
+ )
1320
+
1321
+
1322
+ def _warn_if_stage_dropped(run, kind: str, payload: dict, created: dict, task: str | None) -> None:
1323
+ """Say so when the backend accepted the registration but not its --task.
1324
+
1325
+ A backend without stage support for this kind (code gained it on a branch
1326
+ that has not reached every deployment) ignores the field rather than
1327
+ rejecting it, so the asset is created and the command would otherwise
1328
+ report success. The asset exists by now, so this warns rather than fails:
1329
+ a non-zero exit would invite a retry that then trips over the name.
1330
+ """
1331
+ if not task or not payload.get("stage") or created.get("stage"):
1332
+ return
1333
+ text.print_warning(
1334
+ run,
1335
+ f'The platform did not record --task {task}: this deployment does not '
1336
+ f"store a training stage on {kind} assets.",
1337
+ f"The {kind} was registered without one, so it is not restricted to any stage.",
1338
+ )
1339
+
1340
+
1341
+ def _registration_json(
1342
+ run, kind: str, name: str, created: dict, version_row: dict, *, wait: bool, timeout,
1343
+ source: str = "",
1344
+ ) -> None:
1345
+ """``-o json``: the asset record, after the wait when ``--wait`` was given.
1346
+
1347
+ Returning the just-created record immediately, as this used to, made
1348
+ ``-o json --wait`` exit 0 while the copy was still pending — a script
1349
+ would carry on with an asset that could not be used yet.
1350
+ """
1351
+ asset_id = str(created.get("id") or "")
1352
+ record = created
1353
+ status = ""
1354
+ if wait:
1355
+ status, final = _wait_for_version(
1356
+ run, kind, asset_id, version_row, name=name, timeout=timeout,
1357
+ )
1358
+ record = _fetch_asset(run, kind, asset_id) or created
1359
+ version_row = final or version_row
1360
+ render.render_detail(run, AssetDTO.from_api(record, scope="workspace", tags=[]))
1361
+ if status in enums.ASSET_VERSION_UNUSABLE:
1362
+ _fail_registration(
1363
+ run, _register_output.title(kind, name, state="failed"), kind, name,
1364
+ version_id=str(version_row.get("id") or ""), source=source,
1365
+ )
1366
+
1367
+
1368
+ def _fetch_asset(run, kind: str, asset_id: str) -> dict:
1369
+ asset = run.client().get(f"/assets/{resolve.asset_path(kind)}/{asset_id}")
1370
+ return asset if isinstance(asset, dict) else {}
1371
+
1372
+
1373
+ def _report_version(
1374
+ run, kind: str, asset_id: str, asset_name: str, version: dict, *, wait: bool, timeout,
1375
+ source: str = "",
1376
+ ) -> None:
1377
+ """add-version reports on the version, not on the whole asset."""
1378
+ version_number = str(version.get("version_number") or "")
1379
+ if run.output == "json":
1380
+ status = ""
1381
+ if wait:
1382
+ # Same as registration: under --wait the record comes after the
1383
+ # outcome, and a failed copy still exits 7.
1384
+ status, final = _wait_for_version(
1385
+ run, kind, asset_id, version, name=asset_name, timeout=timeout,
1386
+ )
1387
+ version = final or version
1388
+ render.render_detail(run, AssetDTO.from_api(
1389
+ _fetch_asset(run, kind, asset_id) or {"id": asset_id}, scope="workspace", tags=[],
1390
+ ))
1391
+ if status in enums.ASSET_VERSION_UNUSABLE:
1392
+ _fail_registration(
1393
+ run,
1394
+ _register_output.version_title(kind, asset_name, version_number, state="failed"),
1395
+ kind, asset_name, version_id=str(version.get("id") or ""), source=source,
1396
+ )
1397
+ return
1398
+
1399
+ # Printed before any wait too (PRD 3.3.6), so an interrupted wait still
1400
+ # leaves a record of what was accepted.
1401
+ render.message(run, _register_output.version_title(
1402
+ kind, asset_name, version_number, state="submitted",
1403
+ ))
1404
+ if not wait:
1405
+ status = enums.ASSET_STATUS.to_cli(version.get("status")) or "registering"
1406
+ text.print_labeled(
1407
+ run, [("Status", _register_output.status_display(status))], gutter=1,
1408
+ )
1409
+ _print_next_steps(
1410
+ run, kind, asset_name, waited=False,
1411
+ extra=f"infix asset {kind} get {asset_name} --version {version_number}",
1412
+ )
1413
+ return
1414
+
1415
+ status, _final = _wait_for_version(
1416
+ run, kind, asset_id, version, name=asset_name, timeout=timeout, source=source,
1417
+ )
1418
+ if status in enums.ASSET_VERSION_UNUSABLE:
1419
+ _fail_registration(
1420
+ run,
1421
+ _register_output.version_title(kind, asset_name, version_number, state="failed"),
1422
+ kind, asset_name,
1423
+ version_id=str(_final.get("id") or version.get("id") or ""), source=source,
1424
+ )
1425
+ render.message(run, _register_output.version_title(
1426
+ kind, asset_name, version_number,
1427
+ state=_register_output.status_display(status),
1428
+ ))
1429
+
1430
+
1431
+ def _wait_for_version(
1432
+ run, kind: str, asset_id: str, version: dict, *, name: str, timeout, source: str = "",
1433
+ ):
1434
+ """Block until the version reaches a terminal state."""
1435
+ from infix_cli import waiter
1436
+
1437
+ version_id = str(version.get("id") or "")
1438
+ if not version_id:
1439
+ return enums.ASSET_STATUS.to_cli(version.get("status")), version
1440
+
1441
+ render.message(run, "Waiting for registration to complete...", symbol="")
1442
+ seen: dict = {"percent": -1, "absent": False}
1443
+
1444
+ def poll() -> tuple[str, dict]:
1445
+ status, entry = _poll_version(run, kind, asset_id, version_id)
1446
+ if status == "registering":
1447
+ job = _print_copy_progress(run, version_id, seen)
1448
+ if str(job.get("status") or "") == "failed":
1449
+ # The copy has given up but the version still says Pending:
1450
+ # backends that only fail the version on a permanent error
1451
+ # leave it there for good once retries run out. Waiting on the
1452
+ # version alone would then only ever end in a timeout.
1453
+ return "failed", entry
1454
+ return status, entry
1455
+
1456
+ return waiter.wait_until_terminal(
1457
+ poll,
1458
+ terminal=enums.ASSET_VERSION_TERMINAL,
1459
+ ctx=run,
1460
+ timeout=waiter.parse_timeout(timeout),
1461
+ label="Registering",
1462
+ recheck_hint=f'Check again with "infix asset {kind} get {name}".',
1463
+ announce=_announcer(source),
1464
+ )
1465
+
1466
+
1467
+ def _announcer(source: str):
1468
+ """Progress wording from the PRD, printed on state changes only.
1469
+
1470
+ The PRD's example repeats the line on every poll; that turns a long wait
1471
+ into a wall of identical lines, and in CI it is a log file, not a spinner.
1472
+ The wording follows the source, because "processing file" is a poor
1473
+ description of cloning a repository or downloading from HuggingFace.
1474
+ """
1475
+ line = _register_output.progress_line(source)
1476
+
1477
+ def announce(ctx, status: str, _label: str) -> None:
1478
+ if ctx.output == "json" or ctx.quiet or status not in ("registering",):
1479
+ return
1480
+ # Flushed: stdout is block-buffered when it is not a terminal, so under
1481
+ # CI or a pipe these lines would sit in the buffer until the process
1482
+ # exits — arriving after the very outcome they were meant to precede.
1483
+ # A progress line that is not timely is not progress.
1484
+ print(line, flush=True)
1485
+
1486
+ return announce
1487
+
1488
+
1489
+ def _report_completion(
1490
+ run, kind: str, name: str, *, version: str, status: str, usage: str | None,
1491
+ task: str | None, visibility: str, metrics: dict,
1492
+ version_id: str = "", source: str = "",
1493
+ ) -> None:
1494
+ if status in enums.ASSET_VERSION_UNUSABLE:
1495
+ _fail_registration(
1496
+ run, _register_output.title(kind, name, state="failed"), kind, name,
1497
+ version_id=version_id, source=source,
1498
+ )
1499
+
1500
+ size = metrics.get("size_bytes")
1501
+ render.message(run, _register_output.title(
1502
+ kind, name, state=_register_output.status_display(status),
1503
+ ))
1504
+ text.print_labeled(run, _register_output.completed_rows(
1505
+ kind, version=version, usage=usage, task=task, visibility=visibility,
1506
+ size=format_bytes(size) if size else None,
1507
+ ), gutter=1)
1508
+
1509
+
1510
+ def _fail_registration(
1511
+ run, headline: str, kind: str, name: str, *, version_id: str = "", source: str = "",
1512
+ ) -> None:
1513
+ raw = _copy_failure_reason(run, version_id)
1514
+ if not raw:
1515
+ from infix_cli.errors import JobFailed
1516
+
1517
+ raise JobFailed(
1518
+ headline,
1519
+ f'Reason: see "infix asset {kind} versions {name}" for the version history.',
1520
+ )
1521
+ _raise_failed(run, headline, raw, source)
1522
+
1523
+
1524
+ def _raise_failed(run, headline: str, raw: str, source: str) -> None:
1525
+ """Exit 7 with the PRD's ``Reason:`` / ``Retry:`` lines.
1526
+
1527
+ The copy job's message is summarised to one line; ``--verbose`` adds it
1528
+ verbatim for whoever has to dig further.
1529
+ """
1530
+ from infix_cli.errors import JobFailed
1531
+
1532
+ reason, retry = _register_output.failure_reason(raw, source)
1533
+ lines = [f"Reason: {reason}"]
1534
+ if retry:
1535
+ lines.append(f"Retry: {retry}")
1536
+ if getattr(run, "verbose", False) and reason != raw:
1537
+ lines.append("Detail: " + raw.replace("\n", "\n "))
1538
+ raise JobFailed(headline, "\n ".join(lines))
1539
+
1540
+
1541
+ def _copy_failure_reason(run, version_id: str) -> str:
1542
+ """Why the copy failed, in the backend's own words.
1543
+
1544
+ ``asset_versions`` has no error column, so the reason lives on the copy job
1545
+ that did the work — newest first, and only for the asynchronous sources
1546
+ (HuggingFace, git, anything over the inline-copy size). An inline copy that
1547
+ failed has no job, hence no reason, and the caller falls back to pointing at
1548
+ the version history.
1549
+ """
1550
+ job = _newest_copy_job(run, version_id)
1551
+ return str(job.get("error_message") or job.get("error_kind") or "").strip()
1552
+
1553
+
1554
+ def _newest_copy_job(run, version_id: str) -> dict:
1555
+ """The most recent copy job for a version, or ``{}``.
1556
+
1557
+ Never allowed to change the outcome of what it is describing: a failure here
1558
+ must not replace a registration's own result with a different error, so every
1559
+ caller treats an empty dict as "no information available".
1560
+ """
1561
+ if not version_id:
1562
+ return {}
1563
+ try:
1564
+ jobs = run.client().get(f"/assets/versions/{version_id}/copy-jobs")
1565
+ except CliError:
1566
+ return {}
1567
+ return jobs[0] if isinstance(jobs, list) and jobs and isinstance(jobs[0], dict) else {}
1568
+
1569
+
1570
+ def _print_copy_progress(run, version_id: str, seen: dict) -> dict:
1571
+ """Report how far the copy has got, once per change.
1572
+
1573
+ Large models and HuggingFace downloads run for many minutes; without this
1574
+ the wait prints one line and then nothing, which is indistinguishable from
1575
+ a stall. Reprinting an unchanged percentage is what would make it noise, so
1576
+ the last value printed is remembered.
1577
+
1578
+ A version only polls while it is Pending, which only happens on the async
1579
+ path — so there is normally a job to read. When there is not, the lookup is
1580
+ abandoned rather than repeated on every tick.
1581
+
1582
+ Returns the job it read (``{}`` when there is none), so the caller can see
1583
+ a copy that has already given up.
1584
+ """
1585
+ if seen.get("absent"):
1586
+ return {}
1587
+ job = _newest_copy_job(run, version_id)
1588
+ if not job:
1589
+ seen["absent"] = True
1590
+ return {}
1591
+ if run.output == "json" or run.quiet:
1592
+ return job
1593
+ if not job.get("started_at"):
1594
+ # Still queued. Its progress_percent is 0, but printing "0%" reads as
1595
+ # "running and getting nowhere" when the truth is "not its turn yet".
1596
+ return job
1597
+ percent = int(job.get("progress_percent") or 0)
1598
+ if percent <= 0 or percent <= seen.get("percent", -1):
1599
+ # 0% says nothing the "Registering —" line has not already said.
1600
+ return job
1601
+ seen["percent"] = percent
1602
+ done, total = job.get("bytes_done"), job.get("bytes_total")
1603
+ sizes = f" {format_bytes(done)} / {format_bytes(total)}" if done and total else ""
1604
+ print(f" {percent}%{sizes}", flush=True)
1605
+ return job
1606
+
1607
+
1608
+ def _print_next_steps(
1609
+ run, kind: str, name: str, *, waited: bool, extra: str = "", pending: bool = True,
1610
+ ) -> None:
1611
+ lines = _register_output.next_steps(kind, name, waited=waited, pending=pending)
1612
+ if extra:
1613
+ lines = [line for line in lines if not line.startswith("Check status:")]
1614
+ lines.insert(0, f"Check status: {extra}")
1615
+ if not lines:
1616
+ return
1617
+ print()
1618
+ for line in lines:
1619
+ print(line)
1620
+
1621
+
1622
+ def _poll_version(run, kind: str, asset_id: str, version_id: str) -> tuple[str, dict]:
1623
+ """Read one version's current status. Bypasses the resolver's cache —
1624
+ the whole point of polling is to see the value change."""
1625
+ versions = run.client().get(f"/assets/{resolve.asset_path(kind)}/{asset_id}/versions")
1626
+ for entry in versions if isinstance(versions, list) else []:
1627
+ if str(entry.get("id")) == version_id:
1628
+ return enums.ASSET_STATUS.to_cli(entry.get("status")), entry
1629
+ return "registering", {}
1630
+
1631
+
1632
+ # ── images live outside /assets ─────────────────────────────────────────────
1633
+
1634
+ image_app = typer.Typer(help="Container images.", no_args_is_help=True)
1635
+
1636
+
1637
+ @image_app.command("list")
1638
+ def image_list(
1639
+ ctx: typer.Context,
1640
+ scope: str = typer.Option("workspace", "--scope", help="workspace | official"),
1641
+ search: Optional[str] = typer.Option(None, "--search"),
1642
+ chip: Optional[str] = typer.Option(None, "--chip", help="cpu | gpu"),
1643
+ page: int = typer.Option(1, "--page", "-p", min=1),
1644
+ page_size: int = typer.Option(None, "--page-size", min=1, max=_MAX_PAGE_SIZE),
1645
+ ) -> None:
1646
+ """List container images visible to this workspace."""
1647
+ run = ctx.obj
1648
+ if scope not in ("workspace", "official"):
1649
+ raise UsageError(f'Invalid --scope "{scope}". Valid: workspace, official.')
1650
+ params: dict[str, object] = {"image_type": scope, "search": search}
1651
+ if chip:
1652
+ params["chip_type"] = _register.choice(enums.CHIP_TYPE, chip, "--chip")
1653
+ items, page_no, size, total = fetch_page(
1654
+ run.client(), "/images", params=params,
1655
+ page=page, page_size=run.default_page_size(page_size),
1656
+ )
1657
+ dtos = [ImageDTO.from_api(raw) for raw in items]
1658
+ render.render_list(
1659
+ run, dtos, ImageDTO.columns(),
1660
+ page=page_no, page_size=size, total=total,
1661
+ empty_message=f"No images found in scope {scope}.",
1662
+ )
1663
+
1664
+
1665
+ @image_app.command("get")
1666
+ def image_get(
1667
+ ctx: typer.Context,
1668
+ name: str = typer.Argument(..., help="Image display name."),
1669
+ scope: str = typer.Option("workspace", "--scope", help="workspace | official"),
1670
+ ) -> None:
1671
+ """Show one container image in detail."""
1672
+ run = ctx.obj
1673
+ client = run.client()
1674
+ from infix_cli.http.pagination import iter_items
1675
+
1676
+ matches = [
1677
+ raw
1678
+ for raw in iter_items(client, "/images", params={"image_type": scope, "search": name})
1679
+ if str(raw.get("display_name") or "") == name
1680
+ ]
1681
+ if not matches:
1682
+ raise NotFoundError(
1683
+ f'Image "{name}" not found in scope {scope}.',
1684
+ 'Run "infix asset image list" to see what exists.',
1685
+ )
1686
+ detail = client.get(f"/images/{matches[0]['id']}")
1687
+ render.render_detail(run, ImageDTO.from_api(detail if isinstance(detail, dict) else matches[0]))
1688
+
1689
+
1690
+ @image_app.command("delete")
1691
+ def image_delete(
1692
+ ctx: typer.Context,
1693
+ name: str = typer.Argument(..., help="Image display name."),
1694
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
1695
+ ) -> None:
1696
+ """Delete a container image from this workspace. This cannot be undone."""
1697
+ run = ctx.obj
1698
+ _delete.delete_image(run, _workspace_image(run, name, read_only="read-only"), yes=yes)
1699
+
1700
+
1701
+ @image_app.command("wait")
1702
+ def image_wait(
1703
+ ctx: typer.Context,
1704
+ name: str = typer.Argument(..., help="Image display name."),
1705
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 2h. Default: 30s."),
1706
+ ) -> None:
1707
+ """Wait for an image to finish syncing; exit 0 if available, 7 if failed."""
1708
+ run = ctx.obj
1709
+ image = _workspace_image(run, name, read_only="always available")
1710
+ image_id = str(image.get("id"))
1711
+ detail = run.client().get(f"/images/{image_id}")
1712
+ detail = detail if isinstance(detail, dict) else image
1713
+ display = str(image.get("display_name") or name)
1714
+ status, final = _wait_for_image(run, image_id, name=display, current=detail, timeout=timeout)
1715
+ if status != "available":
1716
+ _fail_image(run, display, final)
1717
+ if run.output == "json":
1718
+ render.render_detail(run, ImageDTO.from_api(final or detail))
1719
+ return
1720
+ render.message(run, _register_output.title(
1721
+ "image", display, state=_register_output.status_display(status),
1722
+ ))
1723
+
1724
+
1725
+ @image_app.command("publish")
1726
+ def image_publish(
1727
+ ctx: typer.Context,
1728
+ name: str = typer.Argument(..., help="Image display name."),
1729
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
1730
+ ) -> None:
1731
+ """Make a workspace image public. This cannot be undone."""
1732
+ run = ctx.obj
1733
+ _publish.publish_image(
1734
+ run, _workspace_image(run, name, read_only="already public"), yes=yes,
1735
+ )
1736
+
1737
+
1738
+ def _workspace_image(run, name: str, *, read_only: str) -> dict:
1739
+ """One of this workspace's own images, by display name."""
1740
+ from infix_cli.http.pagination import iter_items
1741
+
1742
+ plain = name.strip()
1743
+ if plain.startswith("official/"):
1744
+ raise UsageError(f"Official images are {read_only}.")
1745
+ plain = plain.removeprefix("workspace/")
1746
+ matches = [
1747
+ raw
1748
+ for raw in iter_items(run.client(), "/images", params={"image_type": "workspace", "search": plain})
1749
+ if str(raw.get("display_name") or "") == plain
1750
+ ]
1751
+ if not matches:
1752
+ raise NotFoundError(
1753
+ f'Image "{plain}" not found in this workspace.',
1754
+ 'Run "infix asset image list" to see what exists.',
1755
+ )
1756
+ return matches[0]
1757
+
1758
+
1759
+ @image_app.command("tags")
1760
+ def image_tags(ctx: typer.Context) -> None:
1761
+ """List the tag dimensions available for images."""
1762
+ _list_tags(ctx.obj, "image")
1763
+
1764
+
1765
+ def _ensure_image_name_free(run, name: str) -> None:
1766
+ """Refuse a duplicate display name before the registry is contacted.
1767
+
1768
+ Best-effort only: the backend's uniqueness check spans the whole tenant
1769
+ (``image_service.check_duplicate_name``) while this listing can only see
1770
+ this workspace's images and the official ones. A name taken in a sibling
1771
+ workspace still comes back as a 409 from the POST, which reads clearly on
1772
+ its own — this check exists to catch the common case without a round trip
1773
+ to the source registry first.
1774
+ """
1775
+ from infix_cli.http.pagination import iter_items
1776
+
1777
+ client = run.client()
1778
+ for scope in ("workspace", "official"):
1779
+ taken = any(
1780
+ str(raw.get("display_name") or "") == name
1781
+ for raw in iter_items(client, "/images", params={"image_type": scope, "search": name})
1782
+ )
1783
+ if taken:
1784
+ raise UsageError(
1785
+ f'Registration failed: Image name "{name}" already exists.',
1786
+ 'Pick another name, or see it with "infix asset image get '
1787
+ f'{name}".',
1788
+ )
1789
+
1790
+
1791
+ def _ensure_image_reachable(
1792
+ run, uri: str, username: str | None, password: str | None,
1793
+ ) -> None:
1794
+ """Check the image exists in its registry before creating anything.
1795
+
1796
+ Without this the command reports "submitted" and the failure only surfaces
1797
+ minutes later, in the sync job, where a typo in the URI and a missing
1798
+ credential look the same. The backend exposes the check for exactly this
1799
+ (``POST /images/verify-uri``); a check that cannot be performed is not
1800
+ treated as a failure, since registering has its own error path.
1801
+ """
1802
+ payload = compact({
1803
+ "image_url": uri,
1804
+ "registry_username": username,
1805
+ "registry_password": password,
1806
+ })
1807
+ try:
1808
+ result = run.client().post("/images/verify-uri", json=payload)
1809
+ except CliError:
1810
+ return
1811
+ if not isinstance(result, dict) or result.get("exists"):
1812
+ return
1813
+ reason = str(result.get("error") or "").strip()
1814
+ hint = _register_output.image_access_hint(reason, has_credentials=bool(username))
1815
+ raise UsageError(
1816
+ f'Registration failed: Unable to access image "{uri}".'
1817
+ + (f" {reason}" if reason else ""),
1818
+ hint,
1819
+ )
1820
+
1821
+
1822
+ # How long an image may sit in Pending — never picked up by a sync worker —
1823
+ # before --wait stops treating it as queued and reports it as stuck.
1824
+ _IMAGE_PENDING_STALL_SECONDS = 15 * 60
1825
+
1826
+
1827
+ def _wait_for_image(run, image_id: str, *, name: str, current: dict, timeout):
1828
+ """Block until the image's registry sync settles."""
1829
+ from infix_cli import waiter
1830
+
1831
+ status = _image_sync_status(current)
1832
+ if not image_id or status in enums.IMAGE_SYNC_TERMINAL:
1833
+ return status, current
1834
+
1835
+ limit = waiter.parse_timeout(timeout)
1836
+ render.message(run, "Waiting for registration to complete...", symbol="")
1837
+ return waiter.wait_until_terminal(
1838
+ _image_poller(run, image_id, name=name, guard_stall=limit is None),
1839
+ terminal=enums.IMAGE_SYNC_TERMINAL,
1840
+ ctx=run,
1841
+ timeout=limit,
1842
+ label="Registering",
1843
+ recheck_hint=f'Check again with "infix asset image get {name}".',
1844
+ announce=_announce_image_sync,
1845
+ )
1846
+
1847
+
1848
+ def _image_poller(run, image_id: str, *, name: str, guard_stall: bool):
1849
+ """Poll the image, giving up on a sync that was never started.
1850
+
1851
+ Unlike an asset copy, an image sync leaves nothing a client can read while
1852
+ it is queued: the backend creates the image as Pending and hands it to the
1853
+ sync dispatcher, and when there is no dispatcher, or handing it over fails,
1854
+ it only logs that and the image stays Pending for good. With no --timeout
1855
+ the wait would then never end. Pending that outlasts any plausible queue is
1856
+ therefore reported as stuck. Once the image reaches Syncing a worker owns
1857
+ it, and the wait is left alone however long the pull takes.
1858
+
1859
+ An explicit --timeout means the caller has chosen how long to wait, so the
1860
+ guard steps aside rather than second-guessing it.
1861
+ """
1862
+ import time
1863
+
1864
+ started = time.monotonic()
1865
+
1866
+ def poll() -> tuple[str, dict]:
1867
+ status, detail = _poll_image(run, image_id)
1868
+ if (
1869
+ guard_stall
1870
+ and status == "registering"
1871
+ and time.monotonic() - started >= _IMAGE_PENDING_STALL_SECONDS
1872
+ ):
1873
+ from infix_cli.errors import WaitTimeout
1874
+
1875
+ minutes = _IMAGE_PENDING_STALL_SECONDS // 60
1876
+ raise WaitTimeout(
1877
+ f'Image "{name}" has been waiting to sync for {minutes} minutes '
1878
+ "without starting.",
1879
+ "The platform's image sync may not be running. Ask an "
1880
+ f'administrator, check with "infix asset image get {name}", or '
1881
+ "pass --timeout to wait longer.",
1882
+ )
1883
+ return status, detail
1884
+
1885
+ return poll
1886
+
1887
+
1888
+ def _poll_image(run, image_id: str) -> tuple[str, dict]:
1889
+ detail = run.client().get(f"/images/{image_id}")
1890
+ detail = detail if isinstance(detail, dict) else {}
1891
+ return _image_sync_status(detail), detail
1892
+
1893
+
1894
+ def _image_sync_status(detail: dict) -> str:
1895
+ """The CLI word for an image's sync state.
1896
+
1897
+ Images created before registry sync existed carry no ``sync_status`` at
1898
+ all, and the platform treats those as usable (computing_repo admits a null
1899
+ status alongside Completed). Reading that as "not yet" would wait forever.
1900
+ """
1901
+ raw = (detail or {}).get("sync_status")
1902
+ if not raw:
1903
+ return "available"
1904
+ return enums.IMAGE_SYNC_STATUS.to_cli(raw)
1905
+
1906
+
1907
+ def _announce_image_sync(ctx, status: str, _label: str) -> None:
1908
+ if ctx.output == "json" or ctx.quiet or status not in ("registering", "syncing"):
1909
+ return
1910
+ # Flushed for the same reason as _announcer: under a pipe this line would
1911
+ # otherwise surface after the failure it was meant to precede.
1912
+ print(" Registering — pulling from registry...", flush=True)
1913
+
1914
+
1915
+ def _fail_image(run, name: str, detail: dict) -> None:
1916
+ """Report a failed sync with the reason the backend recorded."""
1917
+ from infix_cli.errors import JobFailed
1918
+
1919
+ reason = str((detail or {}).get("sync_error") or "").strip()
1920
+ headline = _register_output.title("image", name, state="failed")
1921
+ if not reason:
1922
+ raise JobFailed(headline, f'Reason: see "infix asset image get {name}".')
1923
+ _raise_failed(run, headline, reason, "image")
1924
+
1925
+
1926
+ @image_app.command("register")
1927
+ def image_register(
1928
+ ctx: typer.Context,
1929
+ name: str = typer.Option(..., "--name", "-n", help="Display name (3-50 chars)."),
1930
+ uri: str = typer.Option(..., "--uri", help="Full image reference, e.g. registry/repo:tag."),
1931
+ task: list[str] = typer.Option(
1932
+ [], "--task",
1933
+ help="notebook | spark | training | service. Required; repeat for several.",
1934
+ ),
1935
+ chip: Optional[str] = typer.Option(None, "--chip", help="cpu | gpu. Required."),
1936
+ framework: Optional[str] = typer.Option(None, "--framework"),
1937
+ framework_version: Optional[str] = typer.Option(None, "--framework-version"),
1938
+ cuda: Optional[str] = typer.Option(None, "--cuda"),
1939
+ python_version: Optional[str] = typer.Option(None, "--python"),
1940
+ visibility: str = typer.Option("private", "--visibility", help="private | public"),
1941
+ tag: list[str] = typer.Option([], "--tag", "-t", help="Free-form tag. Repeatable."),
1942
+ description: Optional[str] = typer.Option(None, "--description"),
1943
+ registry_username: Optional[str] = typer.Option(None, "--registry-username"),
1944
+ registry_password: Optional[str] = typer.Option(None, "--registry-password"),
1945
+ wait: bool = typer.Option(False, "--wait", help="Block until the image finishes syncing."),
1946
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 2h. Default: 30s."),
1947
+ ) -> None:
1948
+ """Register a container image.
1949
+
1950
+ Images take free-form tag strings, not the tag ids the other asset kinds
1951
+ resolve against, so --tag values are sent as typed.
1952
+
1953
+ Registering pulls the image into the platform's own registry, which takes
1954
+ as long as the image is large; until that finishes the image cannot run a
1955
+ job. Use --wait to block until it can.
1956
+ """
1957
+ run = ctx.obj
1958
+ # Built first so a bad flag is reported before the registry is contacted.
1959
+ payload = _register.image_payload(
1960
+ name, uri=uri, visibility=visibility, tasks=list(task), chip=chip,
1961
+ framework=framework, framework_version=framework_version, cuda=cuda,
1962
+ python=python_version, tags=list(tag), description=description,
1963
+ registry_username=registry_username, registry_password=registry_password,
1964
+ )
1965
+ _ensure_image_name_free(run, name)
1966
+ _ensure_image_reachable(run, uri, registry_username, registry_password)
1967
+ created = run.client().post("/images", json=payload)
1968
+ created = created if isinstance(created, dict) else {}
1969
+ if run.output == "json":
1970
+ # --wait holds the record back until the sync settles, as it does for
1971
+ # the other kinds, and a failed sync still exits 7.
1972
+ status, record = "", created
1973
+ if wait:
1974
+ status, record = _wait_for_image(
1975
+ run, str(created.get("id") or ""), name=name, current=created, timeout=timeout,
1976
+ )
1977
+ render.render_detail(run, ImageDTO.from_api(record or created))
1978
+ if wait and status != "available":
1979
+ _fail_image(run, name, record)
1980
+ return
1981
+
1982
+ render.message(run, _register_output.title("image", name, state="submitted"))
1983
+ if not wait:
1984
+ status = enums.IMAGE_SYNC_STATUS.to_cli(created.get("sync_status")) or "registering"
1985
+ text.print_labeled(run, _register_output.submitted_rows(
1986
+ "image", version="", usage=None, task=None, source="", source_detail="",
1987
+ visibility=visibility, uri=uri, chip=chip or "", image_tasks=list(task),
1988
+ status=_register_output.status_display(
1989
+ "registering" if status == "syncing" else status,
1990
+ ),
1991
+ ), gutter=1)
1992
+ _print_next_steps(run, "image", name, waited=False)
1993
+ return
1994
+
1995
+ status, final = _wait_for_image(
1996
+ run, str(created.get("id") or ""), name=name, current=created, timeout=timeout,
1997
+ )
1998
+ if status != "available":
1999
+ _fail_image(run, name, final)
2000
+ render.message(run, _register_output.title(
2001
+ "image", name, state=_register_output.status_display(status),
2002
+ ))
2003
+ text.print_labeled(run, _register_output.completed_rows(
2004
+ "image", version="", usage=None, task=None,
2005
+ visibility=visibility, uri=uri, chip=chip or "",
2006
+ ), gutter=1)
2007
+
2008
+
2009
+ app.add_typer(_make_kind_app("model"), name="model")
2010
+ app.add_typer(_make_kind_app("dataset"), name="dataset")
2011
+ app.add_typer(_make_kind_app("code"), name="code")
2012
+ app.add_typer(image_app, name="image")