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,600 @@
1
+ """Request bodies for asset registration.
2
+
3
+ Pure functions, no I/O: the four asset kinds disagree about almost every field
4
+ name (``source`` vs ``data_source`` vs ``code_source``, ``storage_path`` vs
5
+ ``artifact_url`` vs ``hf_*``), and that mapping is where a wrong guess turns
6
+ into a 422. Keeping it free of HTTP makes each mapping directly testable.
7
+
8
+ Field names verified against app/api/assets/schemas.py and
9
+ app/api/images/schemas.py.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from typing import Any
16
+ from urllib.parse import urlsplit, urlunsplit
17
+
18
+ from infix_cli.domain import enums
19
+ from infix_cli.domain.dto.common import compact
20
+ from infix_cli.errors import UsageError
21
+
22
+ # Evaluation datasets uploaded from a local file must declare their JSONL
23
+ # schema; the backend validates the file against it.
24
+ EVAL_FORMATS = ("multiple_choice", "text_similarity")
25
+
26
+ # `format` alone is not enough to make the dataset usable. Evaluation resolves
27
+ # its EvalScope adapter from `custom_eval_kind` (docs/codebase/evaluation/
28
+ # benchmark-mapping.md), and rejects a custom evaluation dataset whose `stage`
29
+ # is not "posttrain". Registering with only `format` produced an asset that
30
+ # looked fine in the listing and then failed at submission with
31
+ # "Custom evaluation datasets must use posttrain stage".
32
+ _EVAL_KIND_FOR_FORMAT = {
33
+ "multiple_choice": "single_choice",
34
+ "text_similarity": "qa",
35
+ }
36
+ _FORMAT_FOR_EVAL_KIND = {kind: fmt for fmt, kind in _EVAL_KIND_FOR_FORMAT.items()}
37
+ _CUSTOM_EVAL_STAGE = "posttrain"
38
+
39
+ # Which --task words each --usage accepts (PRD 3.2.2). The backend stores a
40
+ # free-form stage, so nothing downstream rejects a typo: an unchecked value is
41
+ # written to the asset and only surfaces much later, when a training job filters
42
+ # on stage and silently fails to match.
43
+ TASK_BY_USAGE = {
44
+ "training": ("cpt", "sft", "rl"),
45
+ "evaluation": ("pre-training", "post-training"),
46
+ }
47
+
48
+ # Which --task words ``code register`` accepts (PRD 3.3). Code is written for
49
+ # one training stage, so this is the training row above and nothing else: the
50
+ # evaluation words describe what a dataset measures, not what code does.
51
+ CODE_TASKS = TASK_BY_USAGE["training"]
52
+
53
+ # Sources each kind's add-version accepts — "the same as its register command"
54
+ # (PRD 3.3). Models have no local source because the platform has no upload
55
+ # channel for weights: a model comes from Workspace Storage or HuggingFace.
56
+ VERSION_SOURCES = {
57
+ "model": ("storage", "huggingface"),
58
+ "dataset": ("storage", "local", "huggingface"),
59
+ "code": ("storage", "local", "git"),
60
+ }
61
+
62
+
63
+ def choice(mapper: enums.Mapper, value: str | None, flag: str, *, what: str = "") -> str:
64
+ """Map a CLI word to its wire value, refusing words the mapper does not know.
65
+
66
+ ``Mapper.to_backend`` passes unknown words through unchanged, which is right
67
+ for display but wrong for a request body: a typo then reaches the backend
68
+ and comes back as a raw 422, or — for ``--visibility`` — as a 503
69
+ ``LookupError`` with exit 1. Rejecting it here reports the flag by name,
70
+ exits 2, and does so before any file is uploaded.
71
+ """
72
+ word = (value or "").strip().lower()
73
+ if word not in mapper.cli_values:
74
+ suffix = f" for {what}" if what else ""
75
+ raise UsageError(
76
+ f'Invalid {flag} "{value}"{suffix}.',
77
+ f"Valid: {', '.join(mapper.cli_values)}.",
78
+ )
79
+ return mapper.to_backend(word)
80
+
81
+
82
+ def _require_eval_format(source: str, backend_usage: str, file_format: str | None) -> None:
83
+ if source == "local" and backend_usage == "Evaluation" and not file_format:
84
+ raise UsageError(
85
+ "--format is required when uploading a local evaluation dataset.",
86
+ f"Valid: {', '.join(EVAL_FORMATS)}.",
87
+ )
88
+
89
+
90
+ def version_eval_format(asset: dict, *, source: str, file_format: str | None) -> str | None:
91
+ """The JSONL schema a new dataset version's local file is checked against.
92
+
93
+ ``upload-local`` validates only when it is told a format, and a version has
94
+ no format of its own — ``CreateVersionRequest`` carries none, the schema is
95
+ the asset's. So an evaluation dataset given a local version without
96
+ ``--format`` used to accept any file at all, and the mistake surfaced only
97
+ when an evaluation job read it.
98
+
99
+ The format already recorded on the asset is the answer, so the caller does
100
+ not have to repeat it; an explicit ``--format`` that disagrees is refused,
101
+ since one asset whose versions differ in schema cannot match one template.
102
+ Benchmark datasets (``dataset_name``) follow their benchmark's own layout,
103
+ which ``upload-local`` has no schema for, and are passed through unchecked.
104
+ """
105
+ if file_format and file_format not in EVAL_FORMATS:
106
+ raise UsageError(
107
+ f'Invalid --format "{file_format}".', f"Valid: {', '.join(EVAL_FORMATS)}.",
108
+ )
109
+ if str(asset.get("usage") or "") != "Evaluation":
110
+ if file_format:
111
+ raise UsageError(
112
+ "--format only applies to evaluation datasets.",
113
+ "Training datasets take any file; drop --format.",
114
+ )
115
+ return None
116
+ if source != "local":
117
+ if file_format:
118
+ raise UsageError(
119
+ f'--format only applies to --source local, not "{source}".',
120
+ "Drop --format.",
121
+ )
122
+ return None
123
+
124
+ recorded = str(asset.get("format") or "") or _FORMAT_FOR_EVAL_KIND.get(
125
+ str(asset.get("custom_eval_kind") or ""), "",
126
+ )
127
+ if recorded:
128
+ if file_format and file_format != recorded:
129
+ raise UsageError(
130
+ f'--format "{file_format}" does not match this dataset, which is '
131
+ f'"{recorded}".',
132
+ "Every version of a dataset uses the same schema; drop --format, "
133
+ "or register the file as a new dataset.",
134
+ )
135
+ return recorded
136
+ if asset.get("dataset_name"):
137
+ return file_format
138
+ if not file_format:
139
+ raise UsageError(
140
+ "--format is required: this evaluation dataset does not record its schema.",
141
+ f"Valid: {', '.join(EVAL_FORMATS)}.",
142
+ )
143
+ return file_format
144
+
145
+
146
+ def check_dataset_flags(
147
+ *, source: str, usage: str, visibility: str, file_format: str | None,
148
+ ) -> None:
149
+ """Every check ``dataset_payload`` makes that does not need the upload.
150
+
151
+ Run before a local file is staged: each of these used to fail only after
152
+ the transfer, spending the whole upload and leaving an orphaned staged
153
+ file behind to learn about a typo.
154
+ """
155
+ choice(enums.VISIBILITY, visibility, "--visibility")
156
+ backend_usage = choice(enums.DATASET_USAGE, usage, "--usage")
157
+ choice(enums.DATASET_REGISTER_SOURCE, source, "--source", what="a dataset")
158
+ _require_eval_format(source, backend_usage, file_format)
159
+
160
+
161
+ def check_code_flags(*, source: str, usage: str, visibility: str) -> None:
162
+ """Same as ``check_dataset_flags``, for ``code register``."""
163
+ choice(enums.VISIBILITY, visibility, "--visibility")
164
+ choice(enums.CODE_USAGE, usage, "--usage")
165
+ choice(enums.CODE_REGISTER_SOURCE, source, "--source", what="code")
166
+
167
+
168
+ def validate_dataset_task(usage: str, task: str | None) -> str | None:
169
+ """Check --task against --usage, and require it.
170
+
171
+ Returns the task so callers can use this inline.
172
+ """
173
+ allowed = TASK_BY_USAGE.get(usage)
174
+ if allowed is None:
175
+ # --usage itself is wrong; check_dataset_flags / the payload builder
176
+ # report that instead of blaming the flag the user did supply.
177
+ return task
178
+ if not task:
179
+ raise UsageError(
180
+ f"--task is required with --usage {usage}.",
181
+ f"Valid: {', '.join(allowed)}.",
182
+ )
183
+ if task not in allowed:
184
+ raise UsageError(
185
+ f'Invalid --task "{task}" for usage={usage}.',
186
+ f"Valid: {', '.join(allowed)}.",
187
+ )
188
+ return task
189
+
190
+
191
+ _SEMVER_RE = re.compile(r"^(v?)(\d+)\.(\d+)\.(\d+)$")
192
+
193
+
194
+ def next_version_number(versions: list[dict]) -> str:
195
+ """The next minor version after the highest one an asset already has.
196
+
197
+ Only well-formed ``v1.2.3`` / ``1.2.3`` numbers can be ordered, and the
198
+ platform does not enforce that shape — official assets use ``1.0``, and
199
+ nothing stops a version called ``latest``. When none of the existing
200
+ numbers parse there is no "next" to derive, and guessing ``v1.0.0`` would
201
+ collide with whatever is already there, so the caller is asked to say.
202
+
203
+ The ``v`` prefix follows what the asset already uses rather than being
204
+ imposed, so an asset numbered ``1.0.0`` does not suddenly gain one.
205
+ """
206
+ best: tuple[int, int, int] | None = None
207
+ prefix = "v"
208
+ for entry in versions:
209
+ match = _SEMVER_RE.match(str(entry.get("version_number") or "").strip())
210
+ if not match:
211
+ continue
212
+ parsed = (int(match.group(2)), int(match.group(3)), int(match.group(4)))
213
+ if best is None or parsed > best:
214
+ best = parsed
215
+ prefix = match.group(1)
216
+ if best is None:
217
+ raise UsageError(
218
+ "Cannot work out the next version number for this asset.",
219
+ "Pass --version explicitly, e.g. --version v2.0.0.",
220
+ )
221
+ return f"{prefix}{best[0]}.{best[1] + 1}.0"
222
+
223
+
224
+ def _owner_for(source: str, owner_user_id: str | None) -> str | None:
225
+ """Pass an explicit source owner through, for storage sources only.
226
+
227
+ ``owner_user_id`` tells the backend whose Workspace Storage folder the path
228
+ lives under, for a file a teammate shared. It has no meaning for any other
229
+ source — the backend would ignore it — so sending it with one is refused
230
+ rather than dropped, which would leave the caller believing it applied.
231
+ """
232
+ if owner_user_id and source != "storage":
233
+ raise UsageError(
234
+ f'--owner only applies to --source storage, not "{source}".',
235
+ "Drop --owner.",
236
+ )
237
+ return owner_user_id or None
238
+
239
+
240
+ def validate_code_task(usage: str, task: str | None) -> str | None:
241
+ """Check ``code register --task`` against ``--usage``.
242
+
243
+ Unlike a dataset's, this flag is optional: code that declares no stage is
244
+ usable by every training stage. Checked before the source is uploaded, so a
245
+ typo does not cost a transfer first.
246
+ """
247
+ if not task:
248
+ return None
249
+ if usage != "training":
250
+ raise UsageError(
251
+ f'--task is only valid with --usage training, not "{usage}".',
252
+ "Drop --task, or register this as training code.",
253
+ )
254
+ if task not in CODE_TASKS:
255
+ raise UsageError(
256
+ f'Invalid --task "{task}" for code.',
257
+ f"Valid: {', '.join(CODE_TASKS)}.",
258
+ )
259
+ return task
260
+
261
+
262
+ def _base(
263
+ name: str,
264
+ *,
265
+ description: str | None,
266
+ version: str,
267
+ visibility: str,
268
+ tag_ids: list[str],
269
+ ) -> dict[str, Any]:
270
+ return {
271
+ "name": name,
272
+ "description": description,
273
+ "version_number": version,
274
+ "visibility": choice(enums.VISIBILITY, visibility, "--visibility"),
275
+ "tag_ids": tag_ids,
276
+ }
277
+
278
+
279
+ def model_payload(
280
+ name: str,
281
+ *,
282
+ source: str,
283
+ path: str,
284
+ description: str | None = None,
285
+ version: str = "v1.0.0",
286
+ visibility: str = "private",
287
+ tag_ids: list[str] | None = None,
288
+ inference_engine: str | None = None,
289
+ quantization: str | None = None,
290
+ hf_revision: str | None = None,
291
+ hf_token: str | None = None,
292
+ owner_user_id: str | None = None,
293
+ ) -> dict[str, Any]:
294
+ """``POST /assets/models/register``.
295
+
296
+ ``source`` here is the CLI's word for *where the files come from*; the
297
+ backend's own ``source`` field means something else entirely (Manual vs
298
+ TrainingJob — who created the asset), which is why storage and huggingface
299
+ both send "Manual".
300
+ """
301
+ payload = _base(
302
+ name, description=description, version=version,
303
+ visibility=visibility, tag_ids=tag_ids or [],
304
+ )
305
+ payload["source"] = "Manual"
306
+ if source == "huggingface":
307
+ payload.update(
308
+ source_kind="huggingface",
309
+ hf_model_id=path,
310
+ hf_revision=hf_revision,
311
+ hf_token=hf_token,
312
+ )
313
+ elif source == "storage":
314
+ payload["storage_path"] = path
315
+ else:
316
+ raise UsageError(
317
+ f'Invalid --source "{source}" for a model.',
318
+ "Valid: storage, huggingface.",
319
+ )
320
+ payload.update(inference_engine=inference_engine, quantization=quantization)
321
+ payload["owner_user_id"] = _owner_for(source, owner_user_id)
322
+ return compact(payload)
323
+
324
+
325
+ def dataset_payload(
326
+ name: str,
327
+ *,
328
+ source: str,
329
+ usage: str,
330
+ path: str | None = None,
331
+ artifact_url: str | None = None,
332
+ task: str | None = None,
333
+ file_format: str | None = None,
334
+ benchmark: str | None = None,
335
+ description: str | None = None,
336
+ version: str = "v1.0.0",
337
+ visibility: str = "private",
338
+ tag_ids: list[str] | None = None,
339
+ hf_revision: str | None = None,
340
+ hf_token: str | None = None,
341
+ owner_user_id: str | None = None,
342
+ ) -> dict[str, Any]:
343
+ """``POST /assets/datasets/register``.
344
+
345
+ ``artifact_url`` is what ``upload-local`` returned, so a local registration
346
+ is two calls; the caller makes the first one and passes the result here.
347
+ """
348
+ payload = _base(
349
+ name, description=description, version=version,
350
+ visibility=visibility, tag_ids=tag_ids or [],
351
+ )
352
+ backend_usage = choice(enums.DATASET_USAGE, usage, "--usage")
353
+ payload["usage"] = backend_usage
354
+ payload["data_source"] = enums.DATASET_REGISTER_SOURCE.to_backend(source)
355
+
356
+ if source == "storage":
357
+ payload["storage_path"] = _require(path, "--path")
358
+ elif source == "local":
359
+ payload["artifact_url"] = _require(artifact_url, "artifact_url")
360
+ elif source == "huggingface":
361
+ # HuggingFace = "HuggingFace" is deprecated and rejected on new writes;
362
+ # third-party imports go through source_kind instead.
363
+ payload.update(source_kind="huggingface", hf_dataset_id=_require(path, "--path"))
364
+ payload.update(hf_revision=hf_revision, hf_token=hf_token)
365
+ else:
366
+ raise UsageError(
367
+ f'Invalid --source "{source}" for a dataset.',
368
+ "Valid: storage, local, huggingface.",
369
+ )
370
+
371
+ if task:
372
+ payload["stage"] = enums.DATASET_STAGE.to_backend(task)
373
+ if file_format:
374
+ payload["format"] = file_format
375
+ kind = _EVAL_KIND_FOR_FORMAT.get(file_format)
376
+ if kind and backend_usage == "Evaluation":
377
+ payload["custom_eval_kind"] = kind
378
+ # Only defaulted: an explicit --task still wins, so a caller who
379
+ # means something else is not overridden.
380
+ payload.setdefault("stage", _CUSTOM_EVAL_STAGE)
381
+ if benchmark:
382
+ payload["dataset_name"] = benchmark
383
+
384
+ _require_eval_format(source, backend_usage, file_format)
385
+ payload["owner_user_id"] = _owner_for(source, owner_user_id)
386
+ return compact(payload)
387
+
388
+
389
+ def code_payload(
390
+ name: str,
391
+ *,
392
+ source: str,
393
+ usage: str,
394
+ path: str,
395
+ artifact_url: str | None = None,
396
+ task: str | None = None,
397
+ git_branch: str | None = None,
398
+ git_username: str | None = None,
399
+ git_token: str | None = None,
400
+ description: str | None = None,
401
+ version: str = "v1.0.0",
402
+ visibility: str = "private",
403
+ tag_ids: list[str] | None = None,
404
+ owner_user_id: str | None = None,
405
+ ) -> dict[str, Any]:
406
+ """``POST /assets/code/create``."""
407
+ payload = _base(
408
+ name, description=description, version=version,
409
+ visibility=visibility, tag_ids=tag_ids or [],
410
+ )
411
+ payload["usage"] = choice(enums.CODE_USAGE, usage, "--usage")
412
+ payload["code_source"] = enums.CODE_REGISTER_SOURCE.to_backend(source)
413
+ if task:
414
+ # Same wire field and vocabulary as a dataset's stage: one concept, one
415
+ # name. Validated by validate_code_task before the caller uploads
416
+ # anything.
417
+ payload["stage"] = enums.DATASET_STAGE.to_backend(task)
418
+
419
+ if source == "storage":
420
+ payload["storage_path"] = path
421
+ elif source == "local":
422
+ payload["artifact_url"] = _require(artifact_url, "artifact_url")
423
+ elif source == "git":
424
+ # CodeAssetSource.GIT ("Git") is a legacy value the backend rejects;
425
+ # the live path is ImportFromThirdParty + source_kind.
426
+ if git_username and not git_token:
427
+ raise UsageError("--git-token is required when --git-username is given.")
428
+ git_url = _git_url(path, git_username, authenticated=bool(git_token))
429
+ payload.update(source_kind="git", git_url=git_url, git_revision=git_branch)
430
+ if git_token:
431
+ payload["git_credentials"] = git_token
432
+ else:
433
+ raise UsageError(
434
+ f'Invalid --source "{source}" for code.',
435
+ "Valid: storage, local, git.",
436
+ )
437
+ payload["owner_user_id"] = _owner_for(source, owner_user_id)
438
+ return compact(payload)
439
+
440
+
441
+ def _git_url(url: str, username: str | None, *, authenticated: bool) -> str:
442
+ """Return the repository URL, carrying ``--git-username`` as its userinfo.
443
+
444
+ The backend's ``git_credentials`` field is the *password alone*: it reads
445
+ the username off the URL and falls back to a provider default when the URL
446
+ carries none — ``x-access-token`` for github.com, ``oauth2`` elsewhere
447
+ (``app/application/asset_copy_executors.py`` ``_git_url_with_credentials``).
448
+ Sending ``user:token`` as the credential, as this used to, made the whole
449
+ string the password and every private-repo clone failed to authenticate.
450
+
451
+ Credentials are rejected for non-HTTP(S) remotes because the backend
452
+ rejects them too, and it does so only once the copy job runs — minutes
453
+ after the command returned "submitted".
454
+ """
455
+ if not authenticated:
456
+ return url
457
+ parts = urlsplit(url)
458
+ if parts.scheme not in ("http", "https"):
459
+ raise UsageError(
460
+ f'--git-token only works with an HTTP(S) repository URL, got "{url}".',
461
+ "Use the https:// clone URL for a private repository.",
462
+ )
463
+ if not username:
464
+ return url
465
+ if parts.username:
466
+ raise UsageError(
467
+ f'--path already carries the username "{parts.username}".',
468
+ "Pass the username once: either in the URL or with --git-username.",
469
+ )
470
+ # ':' would read as the password separator and '/' would end the authority,
471
+ # so either one silently rewrites the URL into something else.
472
+ if any(ch in username for ch in ":/?#"):
473
+ raise UsageError(
474
+ "--git-username cannot contain any of : / ? #",
475
+ "These characters have their own meaning inside a URL.",
476
+ )
477
+ return urlunsplit(parts._replace(netloc=f"{username}@{parts.netloc}"))
478
+
479
+
480
+ def image_payload(
481
+ name: str,
482
+ *,
483
+ uri: str,
484
+ visibility: str = "private",
485
+ tasks: list[str] | None = None,
486
+ chip: str | None = None,
487
+ framework: str | None = None,
488
+ framework_version: str | None = None,
489
+ cuda: str | None = None,
490
+ python: str | None = None,
491
+ tags: list[str] | None = None,
492
+ description: str | None = None,
493
+ registry_username: str | None = None,
494
+ registry_password: str | None = None,
495
+ ) -> dict[str, Any]:
496
+ """``POST /images`` — different route, different field names entirely.
497
+
498
+ Tags are plain strings here, not tag ids: images do not use the /tags
499
+ registry the other three kinds resolve against. Visibility is called
500
+ ``scope`` on the wire, with the same Private/Public values.
501
+
502
+ ``--task`` and ``--chip`` are required (PRD 3.3.5) and translated to the
503
+ console's own strings: the backend accepts any text, and anything else is
504
+ stored but never matches the console's filters.
505
+ """
506
+ if not tasks:
507
+ raise UsageError(
508
+ "--task is required. Repeat it for an image that serves several.",
509
+ f"Valid: {', '.join(enums.IMAGE_TASK.cli_values)}.",
510
+ )
511
+ if not chip:
512
+ raise UsageError(
513
+ "--chip is required.", f"Valid: {', '.join(enums.CHIP_TYPE.cli_values)}.",
514
+ )
515
+ task_types: list[str] = []
516
+ for task in tasks:
517
+ value = choice(enums.IMAGE_TASK, task, "--task")
518
+ if value not in task_types:
519
+ task_types.append(value)
520
+ return compact({
521
+ "display_name": name,
522
+ "image_url": uri,
523
+ "scope": choice(enums.VISIBILITY, visibility, "--visibility"),
524
+ "task_types": task_types,
525
+ "chip_type": choice(enums.CHIP_TYPE, chip, "--chip"),
526
+ "framework": framework or "",
527
+ "framework_version": framework_version or "",
528
+ "cuda_version": cuda,
529
+ "python_version": python,
530
+ "tags": tags or [],
531
+ "description": description,
532
+ "registry_username": registry_username,
533
+ "registry_password": registry_password,
534
+ })
535
+
536
+
537
+ def version_payload(
538
+ version: str,
539
+ *,
540
+ source: str,
541
+ path: str | None = None,
542
+ artifact_url: str | None = None,
543
+ description: str | None = None,
544
+ git_branch: str | None = None,
545
+ git_username: str | None = None,
546
+ git_token: str | None = None,
547
+ hf_revision: str | None = None,
548
+ hf_token: str | None = None,
549
+ owner_user_id: str | None = None,
550
+ kind: str = "model",
551
+ ) -> dict[str, Any]:
552
+ """``POST /assets/{kind}/{asset_id}/versions``.
553
+
554
+ Each kind accepts the sources its ``register`` does (PRD 3.3), so the
555
+ allowed set is checked by the caller's flag help and again here.
556
+ """
557
+ allowed = VERSION_SOURCES.get(kind, ())
558
+ if source not in allowed:
559
+ # Checked before anything else: a source this kind cannot use must be
560
+ # reported as such, not as whichever flag that source would have needed.
561
+ raise UsageError(
562
+ f'Invalid --source "{source}" for a new {kind} version.',
563
+ f"Valid: {', '.join(allowed)}.",
564
+ )
565
+ payload: dict[str, Any] = {"version_number": version, "description": description}
566
+ if source == "storage":
567
+ payload["storage_path"] = _require(path, "--path")
568
+ elif source == "local":
569
+ payload["artifact_url"] = _require(artifact_url, "artifact_url")
570
+ elif source == "git":
571
+ # Unlike HuggingFace, a new version has no flat git_* fields: the copy
572
+ # worker reads the repository out of source_spec. compact() only cleans
573
+ # the top level, so the spec is filtered separately or a null revision
574
+ # reaches the worker as an explicit "no branch".
575
+ if git_username and not git_token:
576
+ raise UsageError("--git-token is required when --git-username is given.")
577
+ payload["source_kind"] = "git"
578
+ payload["source_spec"] = compact({
579
+ "git_url": _git_url(
580
+ _require(path, "--path"), git_username, authenticated=bool(git_token),
581
+ ),
582
+ "git_revision": git_branch,
583
+ "git_credentials": git_token,
584
+ })
585
+ elif source == "huggingface":
586
+ payload["source_kind"] = "huggingface"
587
+ payload["hf_revision"] = hf_revision
588
+ payload["hf_token"] = hf_token
589
+ if kind == "dataset":
590
+ payload["hf_dataset_id"] = _require(path, "--path")
591
+ else:
592
+ payload["hf_model_id"] = _require(path, "--path")
593
+ payload["owner_user_id"] = _owner_for(source, owner_user_id)
594
+ return compact(payload)
595
+
596
+
597
+ def _require(value: str | None, flag: str) -> str:
598
+ if not value:
599
+ raise UsageError(f"{flag} is required for this source.")
600
+ return value