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,254 @@
1
+ """Chunked upload to Workspace Storage.
2
+
3
+ Protocol (app/api/uploads/router.py)::
4
+
5
+ POST /uploads/sessions -> {upload_id, part_size_bytes}
6
+ PUT /uploads/sessions/{id}/parts/{n} raw bytes, 1-indexed
7
+ POST /uploads/sessions/{id}/complete -> {path, artifact_url, size_bytes}
8
+ DELETE /uploads/sessions/{id} MUST run on any failure path
9
+
10
+ Two things this layer exists to guarantee:
11
+
12
+ * **No orphaned sessions.** An abandoned session leaves parts on the server's
13
+ disk forever, so a failed transfer deletes it.
14
+ * **Resumability.** Part numbers are stable and the server keeps what it has
15
+ received, so an interrupted transfer resumes from the recorded part instead
16
+ of re-sending the whole file.
17
+
18
+ These two pull against each other, and Ctrl-C is where they meet: deleting the
19
+ session on every exit made the second guarantee unreachable — a 500MB upload
20
+ stopped at 90% had to start over. So an interrupt keeps the session and the
21
+ progress file (the user stopped it and will likely resume), while a *failure*
22
+ still deletes both, because a session whose parts were rejected is not one
23
+ anything can resume onto.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import os
31
+ from dataclasses import dataclass
32
+ from pathlib import Path
33
+ from typing import Any, Callable, Iterator
34
+
35
+ from infix_cli.errors import CliError, UsageError
36
+
37
+ # 数据集等用途仍保留 500MiB 限制;Workspace Storage 由后端配置决定上限。
38
+ MAX_UPLOAD_BYTES = 500 * 1024 * 1024
39
+ _DEFAULT_PART_SIZE = 32 * 1024 * 1024
40
+
41
+
42
+ @dataclass
43
+ class UploadResult:
44
+ local_path: str
45
+ remote_path: str
46
+ size_bytes: int
47
+ artifact_url: str | None = None
48
+
49
+
50
+ class UploadSession:
51
+ """One file's transfer. Deletes its server-side session unless completed."""
52
+
53
+ def __init__(
54
+ self,
55
+ client: Any,
56
+ source: Path,
57
+ *,
58
+ purpose: str = "workspace_storage",
59
+ dest_subpath: str = "",
60
+ ) -> None:
61
+ self.client = client
62
+ self.source = source
63
+ self.size = source.stat().st_size
64
+ self.purpose = purpose
65
+ self.dest_subpath = dest_subpath
66
+ self.upload_id: str | None = None
67
+ self.part_size = _DEFAULT_PART_SIZE
68
+
69
+ def open(self) -> None:
70
+ payload = {
71
+ "purpose": self.purpose,
72
+ "filename": self.source.name,
73
+ "size": self.size,
74
+ "metadata": {"dest_subpath": self.dest_subpath} if self.dest_subpath else {},
75
+ }
76
+ response = self.client.post("/uploads/sessions", json=payload) or {}
77
+ self.upload_id = str(response.get("upload_id") or "")
78
+ if not self.upload_id:
79
+ raise UsageError("Upload session was not created.")
80
+ self.part_size = int(response.get("part_size_bytes") or _DEFAULT_PART_SIZE)
81
+
82
+ def send_parts(
83
+ self,
84
+ *,
85
+ start_part: int = 1,
86
+ on_progress: Callable[[int], None] | None = None,
87
+ ) -> None:
88
+ """Stream the file part by part, skipping any already sent.
89
+
90
+ Progress is recorded after each part lands, so an interruption resumes
91
+ from the next one rather than the beginning.
92
+ """
93
+ assert self.upload_id
94
+ with self.source.open("rb") as handle:
95
+ handle.seek((start_part - 1) * self.part_size)
96
+ part_number = start_part
97
+ while True:
98
+ chunk = handle.read(self.part_size)
99
+ if not chunk:
100
+ break
101
+ self.client.put_bytes(
102
+ f"/uploads/sessions/{self.upload_id}/parts/{part_number}", chunk,
103
+ )
104
+ if on_progress:
105
+ on_progress(len(chunk))
106
+ _record_progress(self.source, self.upload_id, part_number + 1)
107
+ part_number += 1
108
+
109
+ def complete(self) -> UploadResult:
110
+ assert self.upload_id
111
+ response = self.client.post(
112
+ f"/uploads/sessions/{self.upload_id}/complete",
113
+ ) or {}
114
+ _clear_progress(self.source)
115
+ return UploadResult(
116
+ local_path=str(self.source),
117
+ remote_path=str(response.get("path") or ""),
118
+ size_bytes=int(response.get("size_bytes") or self.size),
119
+ artifact_url=response.get("artifact_url"),
120
+ )
121
+
122
+ def abort(self) -> None:
123
+ """Delete the server-side session. Never raises: it runs on a failure path."""
124
+ if not self.upload_id:
125
+ return
126
+ try:
127
+ self.client.delete(f"/uploads/sessions/{self.upload_id}")
128
+ except CliError:
129
+ pass
130
+
131
+
132
+ def upload_file(
133
+ client: Any,
134
+ source: Path,
135
+ *,
136
+ dest_subpath: str = "",
137
+ purpose: str = "workspace_storage",
138
+ on_progress: Callable[[int], None] | None = None,
139
+ resume: bool = True,
140
+ ) -> UploadResult:
141
+ """Upload one file, cleaning up the session on any failure."""
142
+ if not source.is_file():
143
+ raise UsageError(f'Not a file: "{source}".')
144
+ size = source.stat().st_size
145
+ if purpose != "workspace_storage" and size > MAX_UPLOAD_BYTES:
146
+ raise UsageError(
147
+ f'"{source.name}" is {_mb(size)}, over the {_mb(MAX_UPLOAD_BYTES)} limit.',
148
+ "Split the file, or upload the directory it lives in as an archive.",
149
+ )
150
+
151
+ session = UploadSession(client, source, purpose=purpose, dest_subpath=dest_subpath)
152
+ saved = _read_progress(source) if resume else None
153
+ if saved:
154
+ session.upload_id = saved["upload_id"]
155
+ session.part_size = saved["part_size"]
156
+ start_part = saved["next_part"]
157
+ if on_progress:
158
+ on_progress(min((start_part - 1) * session.part_size, size))
159
+ else:
160
+ session.open()
161
+ start_part = 1
162
+ _record_progress(source, session.upload_id or "", 1, part_size=session.part_size)
163
+
164
+ try:
165
+ session.send_parts(start_part=start_part, on_progress=on_progress)
166
+ return session.complete()
167
+ except KeyboardInterrupt:
168
+ # Deliberate stop. The session is still valid and the parts already
169
+ # accepted are still on the server, so both are kept: re-running the
170
+ # same command picks up from the next part.
171
+ raise
172
+ except BaseException:
173
+ # A real failure. The session's state is now unknown, so it is deleted
174
+ # rather than left for a resume that would build on it.
175
+ session.abort()
176
+ _clear_progress(source)
177
+ raise
178
+
179
+
180
+ def iter_files(root: Path) -> Iterator[Path]:
181
+ """Every file under a directory, in a stable order."""
182
+ for path in sorted(root.rglob("*")):
183
+ if path.is_file() and not path.name.startswith("."):
184
+ yield path
185
+
186
+
187
+ def relative_dest(root: Path, file: Path, dest: str) -> str:
188
+ """Destination subpath for one file inside an uploaded directory tree."""
189
+ relative = file.relative_to(root).parent
190
+ parts = [segment for segment in (dest.strip("/"), root.name, str(relative)) if segment and segment != "."]
191
+ return "/".join(parts)
192
+
193
+
194
+ # ── resume bookkeeping ──────────────────────────────────────────────────────
195
+
196
+
197
+ def _progress_path(source: Path) -> Path:
198
+ from infix_cli.config import config_dir
199
+
200
+ digest = hashlib.sha256(str(source.resolve()).encode()).hexdigest()[:16]
201
+ return config_dir() / "uploads" / f"{digest}.json"
202
+
203
+
204
+ def _record_progress(source: Path, upload_id: str, next_part: int, *, part_size: int | None = None) -> None:
205
+ path = _progress_path(source)
206
+ try:
207
+ path.parent.mkdir(parents=True, exist_ok=True)
208
+ existing = json.loads(path.read_text()) if path.exists() else {}
209
+ existing.update(
210
+ upload_id=upload_id,
211
+ next_part=next_part,
212
+ size=source.stat().st_size,
213
+ mtime=int(source.stat().st_mtime),
214
+ )
215
+ if part_size:
216
+ existing["part_size"] = part_size
217
+ existing.setdefault("part_size", _DEFAULT_PART_SIZE)
218
+ path.write_text(json.dumps(existing))
219
+ except OSError:
220
+ # Resume is a convenience; failing to record it must not fail the upload.
221
+ pass
222
+
223
+
224
+ def _read_progress(source: Path) -> dict | None:
225
+ """Return resumable state, but only if the file has not changed since."""
226
+ path = _progress_path(source)
227
+ try:
228
+ saved = json.loads(path.read_text())
229
+ except (OSError, ValueError):
230
+ return None
231
+ stat = source.stat()
232
+ if saved.get("size") != stat.st_size or saved.get("mtime") != int(stat.st_mtime):
233
+ # The file was edited; the parts already on the server belong to a
234
+ # different file and resuming would splice two versions together.
235
+ _clear_progress(source)
236
+ return None
237
+ if not saved.get("upload_id") or int(saved.get("next_part", 1)) <= 1:
238
+ return None
239
+ return {
240
+ "upload_id": str(saved["upload_id"]),
241
+ "next_part": int(saved["next_part"]),
242
+ "part_size": int(saved.get("part_size", _DEFAULT_PART_SIZE)),
243
+ }
244
+
245
+
246
+ def _clear_progress(source: Path) -> None:
247
+ try:
248
+ os.unlink(_progress_path(source))
249
+ except OSError:
250
+ pass
251
+
252
+
253
+ def _mb(size: int) -> str:
254
+ return f"{size / (1024 * 1024):.1f} MB"
infix_cli/main.py ADDED
@@ -0,0 +1,432 @@
1
+ """CLI entry point: global flags, sub-app wiring, single error boundary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum
6
+ from typing import Optional
7
+
8
+ import typer
9
+ from infix_cli.cli_framework import click
10
+ from typer.core import TyperGroup
11
+
12
+ from infix_cli import __version__, discovery
13
+ from infix_cli.commands import (
14
+ admin, asset, auth, deploy, evaluation, examples, resource, spark, storage, training,merge,fusion,
15
+ )
16
+ from infix_cli.context import RunContext
17
+ from infix_cli.errors import CliError, ExitCode, UsageError
18
+
19
+ # The error boundary reads these after a command has failed, when the failing
20
+ # command's context is already gone.
21
+ _RUNTIME = {"no_color": False, "exit_zero": False, "output": "json"}
22
+
23
+ _RESULT_CODES = (
24
+ int(ExitCode.TIMEOUT), int(ExitCode.JOB_FAILED), int(ExitCode.JOB_RUNNING),
25
+ )
26
+
27
+
28
+ class OutputFormat(str, Enum):
29
+ """Declared as an enum so --help lists the values instead of showing <str>."""
30
+
31
+ text = "text"
32
+ json = "json"
33
+
34
+
35
+ # Global flags are declared on the root callback, so click only accepts them
36
+ # *before* the subcommand name. Users write them at the end — as do kubectl, gh
37
+ # and docker, and as does the PRD's own example
38
+ # (`infix asset list --quiet --output json`). These two sets drive the
39
+ # normalisation in _hoist_global_flags.
40
+ _OUTPUT_FLAGS = frozenset({"--output", "-o"})
41
+ _GLOBAL_FLAGS_WITH_VALUE = _OUTPUT_FLAGS | {"--profile", "--fields"}
42
+ # --version is deliberately absent: the asset commands take a --version *value*
43
+ # of their own, and hoisting would turn `asset code register --version v1.0.0`
44
+ # into `infix --version`, printing the CLI version and exiting.
45
+ _GLOBAL_FLAGS_BOOLEAN = frozenset({
46
+ "--quiet", "-q", "--exit-zero", "--no-color", "--verbose", "--no-update-check",
47
+ })
48
+
49
+
50
+ def _is_attached_global(token: str) -> bool:
51
+ """Match the ``--output=json`` and ``-ojson`` spellings."""
52
+ if token.startswith("--") and "=" in token:
53
+ return token.split("=", 1)[0] in _GLOBAL_FLAGS_WITH_VALUE
54
+ return (
55
+ len(token) > 2
56
+ and token.startswith("-")
57
+ and not token.startswith("--")
58
+ and token[:2] in _GLOBAL_FLAGS_WITH_VALUE
59
+ )
60
+
61
+
62
+ def _hoist_global_flags(args: list[str]) -> list[str]:
63
+ """Move root-level flags to the front, wherever the user wrote them.
64
+
65
+ Two details worth keeping:
66
+
67
+ * Everything after ``--`` is left alone — it is the user's literal data.
68
+ * 所有带值选项缺少值时直接报错,不静默切换输出格式。
69
+ """
70
+ leading: list[str] = []
71
+ rest: list[str] = []
72
+ index = 0
73
+ while index < len(args):
74
+ token = args[index]
75
+ if token == "--":
76
+ rest.extend(args[index:])
77
+ break
78
+ if token in _GLOBAL_FLAGS_BOOLEAN or _is_attached_global(token):
79
+ leading.append(token)
80
+ elif token in _GLOBAL_FLAGS_WITH_VALUE:
81
+ # A following token that itself looks like a flag is not this
82
+ # option's value — `-o --quiet` means two separate flags.
83
+ following = args[index + 1] if index + 1 < len(args) else None
84
+ has_value = following is not None and not following.startswith("-")
85
+ if has_value:
86
+ leading.append(token)
87
+ index += 1
88
+ leading.append(args[index])
89
+ else:
90
+ raise UsageError(
91
+ f"Option '{token}' requires a value.",
92
+ f"Write it as '{token} <value>'.",
93
+ )
94
+ else:
95
+ rest.append(token)
96
+ index += 1
97
+ return leading + rest
98
+
99
+
100
+ class _ErrorBoundary(TyperGroup):
101
+ """Single place where a CliError becomes a message plus an exit status.
102
+
103
+ It lives on the group rather than in ``run()`` so that the installed
104
+ binary and click's test runner take the same path; typer's own rich error
105
+ rendering is bypassed because it drops the hint line the error carries.
106
+
107
+ It also normalises global-flag position (see _hoist_global_flags); the root
108
+ group is the right place because click hands it the complete argument list
109
+ before dispatching, so one hoist covers every nesting depth.
110
+ """
111
+
112
+ def parse_args(self, ctx, args): # noqa: D401 - click hook
113
+ args = _hoist_global_flags(list(args))
114
+ for index, token in enumerate(args):
115
+ if token == "--":
116
+ break
117
+ if token in _OUTPUT_FLAGS and index + 1 < len(args):
118
+ if args[index + 1] in {"text", "json"}:
119
+ _RUNTIME["output"] = args[index + 1]
120
+ elif token in {"--output=text", "-otext"}:
121
+ _RUNTIME["output"] = "text"
122
+ elif token in {"--output=json", "-ojson"}:
123
+ _RUNTIME["output"] = "json"
124
+ return super().parse_args(ctx, args)
125
+
126
+ def main(self, *args, **kwargs): # noqa: D401 - click hook
127
+ # 在解析前重置,避免嵌入调用和测试沿用上一次的运行参数。
128
+ _RUNTIME.update(no_color=False, exit_zero=False, output="json")
129
+ standalone = kwargs.pop("standalone_mode", True)
130
+ try:
131
+ # 让 Click 解析异常经过同一个边界,避免 Rich 错误框混入 JSON。
132
+ result = super().main(*args, standalone_mode=False, **kwargs)
133
+ if isinstance(result, int) and result not in {0, 130}:
134
+ err = UsageError("Command validation failed.") if result == 2 else CliError("Command did not complete successfully.")
135
+ err.exit_code = result
136
+ if result != 2:
137
+ err.code = "COMMAND_FAILED"
138
+ raise err
139
+ if standalone:
140
+ raise SystemExit(result if isinstance(result, int) else 0)
141
+ return result
142
+ except click.ClickException as exc:
143
+ details = {"command": exc.ctx.command_path} if getattr(exc, "ctx", None) else {}
144
+ if isinstance(exc, click.BadParameter) and exc.param is not None:
145
+ details["field"] = exc.param.name
146
+ err = UsageError(exc.format_message(), details=details)
147
+ err.show(no_color=bool(_RUNTIME["no_color"]), output=_RUNTIME["output"])
148
+ raise SystemExit(err.exit_code) from None
149
+ except CliError as err:
150
+ code = int(err.exit_code)
151
+ if _RUNTIME["exit_zero"] and code in _RESULT_CODES:
152
+ code = int(ExitCode.OK)
153
+ err.show(no_color=bool(_RUNTIME["no_color"]), output=_RUNTIME["output"])
154
+ raise SystemExit(code) from None
155
+ except click.Abort:
156
+ from infix_cli.errors import Aborted
157
+
158
+ Aborted("Aborted.").show(output=_RUNTIME["output"])
159
+ raise SystemExit(1) from None
160
+ except SystemExit as exc:
161
+ # typer turns Ctrl-C into a silent Exit(130) before it can reach
162
+ # run()'s handler; 130 is never one of our own codes (see errors.py).
163
+ if exc.code == 130:
164
+ err = CliError("Interrupted. Remote tasks are not canceled.", "Re-run the same command to resume a download or upload; query an existing task before resubmitting.")
165
+ err.code = "INTERRUPTED"
166
+ err.exit_code = 130
167
+ err.show(output=_RUNTIME["output"])
168
+ raise
169
+ except Exception as exc:
170
+ CliError("Unexpected CLI error.", "Use --verbose for request diagnostics.", details={"error_type": type(exc).__name__}).show(output=_RUNTIME["output"])
171
+ raise SystemExit(1) from None
172
+
173
+
174
+ app = typer.Typer(
175
+ cls=_ErrorBoundary,
176
+ name="infix",
177
+ help=(
178
+ "InfiXspeed platform CLI — manage assets, jobs and storage from the terminal.\n\n"
179
+ # The PRD's stated structure (design principle 3), spelled out because
180
+ # click's own usage line describes the grammar, not the naming.
181
+ # Square brackets are rich markup; escaped so they render literally.
182
+ "Commands read as: infix <module> <action> \\[target] \\[flags]\n\n"
183
+ " infix training create --name my-job ...\n"
184
+ " infix training get my-job\n"
185
+ " infix asset model list --scope official\n\n"
186
+ "Agent integration: infix guide -o text, infix capabilities --groups, infix schema <command>.\n\n"
187
+ "Global flags may be written before or after the subcommand."
188
+ ),
189
+ no_args_is_help=True,
190
+ add_completion=False,
191
+ context_settings={"help_option_names": ["-h", "--help"]},
192
+ )
193
+
194
+
195
+
196
+ def _version_callback(value: bool) -> None:
197
+ if value:
198
+ typer.echo(f"infix {__version__}")
199
+ raise typer.Exit()
200
+
201
+
202
+ _GLOBAL_PANEL = "Global Flags"
203
+ _EXTRA_PANEL = "Additional Flags"
204
+
205
+
206
+ @app.callback()
207
+ def main(
208
+ ctx: typer.Context,
209
+ output: OutputFormat = typer.Option(
210
+ OutputFormat.json, "--output", "-o", help="Output format. JSON by default; text for human-readable output.",
211
+ rich_help_panel=_GLOBAL_PANEL,
212
+ ),
213
+ quiet: bool = typer.Option(
214
+ False, "--quiet", "-q", help="Print only the essential values.",
215
+ rich_help_panel=_GLOBAL_PANEL,
216
+ ),
217
+ profile: Optional[str] = typer.Option(
218
+ None, "--profile", help="Configuration profile to use.",
219
+ rich_help_panel=_EXTRA_PANEL,
220
+ ),
221
+ fields: Optional[str] = typer.Option(
222
+ None, "--fields", help="Select comma-separated JSON field paths. Dots traverse objects and arrays. List pagination is preserved.",
223
+ rich_help_panel=_GLOBAL_PANEL,
224
+ ),
225
+ exit_zero: bool = typer.Option(
226
+ False, "--exit-zero",
227
+ help="Always exit 0 for job-result codes (6/7/8). Useful under 'set -e'.",
228
+ rich_help_panel=_EXTRA_PANEL,
229
+ ),
230
+ no_color: bool = typer.Option(
231
+ False, "--no-color", help="Disable coloured output.",
232
+ rich_help_panel=_EXTRA_PANEL,
233
+ ),
234
+ verbose: bool = typer.Option(
235
+ False, "--verbose", help="Print request diagnostics.",
236
+ rich_help_panel=_EXTRA_PANEL,
237
+ ),
238
+ no_update_check: bool = typer.Option(
239
+ False, "--no-update-check",
240
+ help="Do not check whether a newer CLI has been published.",
241
+ rich_help_panel=_EXTRA_PANEL,
242
+ ),
243
+ _version: bool = typer.Option(
244
+ False, "--version", callback=_version_callback, is_eager=True,
245
+ help="Show the CLI version and exit.",
246
+ rich_help_panel=_EXTRA_PANEL,
247
+ ),
248
+ ) -> None:
249
+ """Set up the run context shared by every command."""
250
+ # typer rejects an invalid value before we get here; store the plain string
251
+ # so downstream comparisons stay simple.
252
+ _RUNTIME["no_color"] = no_color
253
+ _RUNTIME["exit_zero"] = exit_zero
254
+ _RUNTIME["output"] = output.value
255
+ selected_fields = tuple(part.strip() for part in fields.split(",")) if fields is not None else ()
256
+ if selected_fields:
257
+ import re
258
+
259
+ if output != OutputFormat.json or any(not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*", part) for part in selected_fields):
260
+ raise UsageError("--fields requires JSON output and comma-separated field paths.", details={"field": "fields"})
261
+ ctx.obj = RunContext(
262
+ output=output.value,
263
+ quiet=quiet,
264
+ no_color=no_color,
265
+ verbose=verbose,
266
+ exit_zero=exit_zero,
267
+ no_update_check=no_update_check,
268
+ profile_name=profile,
269
+ fields=selected_fields,
270
+ )
271
+ ctx.call_on_close(ctx.obj.close)
272
+ # 默认不进行隐式联网检查;版本查询由显式 version 命令提供。
273
+
274
+
275
+ @app.command()
276
+ def version(ctx: typer.Context) -> None:
277
+ """Show CLI version, the endpoint in use, and whether it answers.
278
+
279
+ First question in any support thread is "which environment are you on" —
280
+ so the answer is one command, not three.
281
+ """
282
+ from infix_cli import render
283
+
284
+ run = ctx.obj
285
+ profile = run.profile
286
+ backend = _probe_backend(profile.api_url) if profile.api_url else "not configured"
287
+ payload = {
288
+ "cli_version": __version__,
289
+ "api_url": profile.api_url or None,
290
+ "profile": profile.name,
291
+ "backend": backend,
292
+ }
293
+ rows = [
294
+ ("CLI Version", __version__),
295
+ ("Profile", profile.name),
296
+ ("API URL", profile.api_url or "--"),
297
+ ("Backend", backend),
298
+ ]
299
+ render.render_object(run, payload, rows, quiet_value=__version__)
300
+
301
+
302
+ _COMPLETION_SHELLS = ("bash", "zsh", "fish")
303
+
304
+
305
+ @app.command()
306
+ def completion(
307
+ shell: str = typer.Argument(..., help="bash | zsh | fish"),
308
+ ) -> None:
309
+ """Print the shell completion script for infix.
310
+
311
+ Completes commands, subcommands and flags. Add it to your shell yourself —
312
+ nothing here edits your rc files:
313
+
314
+ bash: infix completion bash > ~/.infix-completion.bash
315
+ echo 'source ~/.infix-completion.bash' >> ~/.bashrc
316
+
317
+ zsh: infix completion zsh > "${fpath[1]}/_infix"
318
+
319
+ fish: infix completion fish > ~/.config/fish/completions/infix.fish
320
+ """
321
+ if shell not in _COMPLETION_SHELLS:
322
+ raise UsageError(
323
+ f'Unsupported shell "{shell}".', f"Valid: {', '.join(_COMPLETION_SHELLS)}.",
324
+ )
325
+ from typer._completion_shared import get_completion_script
326
+
327
+ typer.echo(get_completion_script(
328
+ prog_name="infix", complete_var=_COMPLETE_VAR, shell=shell,
329
+ ))
330
+
331
+
332
+ # The variable the completion scripts set when the shell asks for candidates.
333
+ _COMPLETE_VAR = "_INFIX_COMPLETE"
334
+
335
+
336
+ def _probe_backend(api_url: str) -> str:
337
+ """Health check lives outside /api/v1, so it bypasses the API client."""
338
+ import httpx
339
+
340
+ try:
341
+ response = httpx.get(f"{api_url.rstrip('/')}/health", timeout=5.0)
342
+ except httpx.HTTPError as exc:
343
+ return f"unreachable ({type(exc).__name__})"
344
+ if response.status_code == 200:
345
+ return "ok"
346
+ return f"HTTP {response.status_code}"
347
+
348
+
349
+ def _group_options_by_requirement(typer_app: typer.Typer) -> None:
350
+ """Split each command's options into Required / Optional panels.
351
+
352
+ The PRD asks for exactly this ("Required Flags 与 Optional Flags 分组列出").
353
+ Done by walking the registered commands rather than annotating ~250
354
+ parameters by hand: typer keeps each option's metadata in the function's
355
+ default values, and a panel set explicitly on a parameter is left alone.
356
+ """
357
+ for command in typer_app.registered_commands:
358
+ callback = command.callback
359
+ if callback is None:
360
+ continue
361
+ for default in callback.__defaults__ or ():
362
+ if not isinstance(default, typer.models.OptionInfo):
363
+ continue
364
+ if default.rich_help_panel:
365
+ continue
366
+ default.rich_help_panel = (
367
+ "Required" if default.default is ... else "Optional"
368
+ )
369
+ for group in typer_app.registered_groups:
370
+ if group.typer_instance is not None:
371
+ _group_options_by_requirement(group.typer_instance)
372
+
373
+
374
+ app.add_typer(auth.app, name="auth")
375
+ app.add_typer(asset.app, name="asset")
376
+ app.add_typer(storage.app, name="storage")
377
+ app.add_typer(resource.app, name="resource")
378
+ app.add_typer(training.app, name="training")
379
+ app.add_typer(evaluation.app, name="evaluation")
380
+ app.add_typer(merge.app,name="merge")
381
+ app.add_typer(fusion.app,name="fusion")
382
+ app.add_typer(examples.app, name="examples")
383
+ app.add_typer(spark.app, name="spark")
384
+ app.add_typer(deploy.app, name="deploy")
385
+ app.add_typer(admin.app, name="admin")
386
+
387
+ app.command("capabilities")(discovery.capabilities)
388
+ app.command("schema")(discovery.schema)
389
+ app.command("doctor")(discovery.doctor)
390
+ app.command("guide")(discovery.guide)
391
+
392
+
393
+ def hoist_global_flags(argv: list[str]) -> list[str]:
394
+ """Move global flags to the front, preserving everything else in order.
395
+
396
+ Stops at ``--``, as POSIX requires: past that, tokens are operands even if
397
+ they look like flags. A subcommand option whose *value* is literally one of
398
+ these flag names (``--search -o``) would be misread; no such value is
399
+ plausible here, and the alternative — parsing without knowing each
400
+ subcommand's arity — cannot be done reliably.
401
+ """
402
+ return _hoist_global_flags(argv)
403
+
404
+
405
+ _group_options_by_requirement(app)
406
+
407
+
408
+ def run() -> None:
409
+ """Process entry point. Errors are handled by _ErrorBoundary; Ctrl-C here."""
410
+ import os
411
+ import sys
412
+
413
+ if os.environ.get(_COMPLETE_VAR):
414
+ # Typer registers its completion handlers lazily, and the app is built
415
+ # with add_completion=False (no --install-completion: the CLI does not
416
+ # edit rc files). So they are registered here, and only when a shell is
417
+ # actually asking — ordinary invocations do not pay for the import.
418
+ from typer.completion import completion_init
419
+
420
+ completion_init()
421
+ try:
422
+ app(args=sys.argv[1:])
423
+ except KeyboardInterrupt:
424
+ err = CliError("Interrupted. Remote tasks are not canceled.")
425
+ err.code = "INTERRUPTED"
426
+ err.exit_code = 130
427
+ err.show(output=_RUNTIME["output"])
428
+ raise SystemExit(130) from None
429
+
430
+
431
+ if __name__ == "__main__": # pragma: no cover
432
+ run()