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
infix_cli/config.py ADDED
@@ -0,0 +1,311 @@
1
+ """Credential and preference storage: ``~/.infix/config.toml``.
2
+
3
+ Layout (tech-design §3.9)::
4
+
5
+ current_profile = "testing"
6
+
7
+ [profiles.testing]
8
+ api_url = "https://infixspeed-nl.infiseek.cn"
9
+ api_key = "sk-..."
10
+ workspace_id = "ws_3ce41d24"
11
+ workspace_name = "my-workspace"
12
+
13
+ [profiles.testing.defaults]
14
+ output = "text"
15
+ page_size = 10
16
+
17
+ Two invariants matter here:
18
+
19
+ * **Snapshot on start.** Callers read the config once per process. A 20-hour
20
+ ``--wait`` in one window must not change behaviour because another window
21
+ ran ``auth login``.
22
+ * **Atomic, locked writes.** Two concurrent ``auth login`` calls would
23
+ otherwise interleave and tear the TOML file.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import os
29
+ import sys
30
+ from dataclasses import dataclass, field
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ if sys.version_info >= (3, 11): # pragma: no cover - version split
35
+ import tomllib
36
+ else: # pragma: no cover - version split
37
+ import tomli as tomllib
38
+
39
+ from infix_cli.errors import AuthError, UsageError
40
+
41
+ DEFAULT_PROFILE = "default"
42
+
43
+ # 全新配置默认连接 A1。--api-url、INFIX_API_URL 和已保存配置仍可覆盖该地址。
44
+ DEFAULT_API_URL = "https://infixspeed-cp.infiseek.cn"
45
+
46
+
47
+ def config_dir() -> Path:
48
+ """Config root. ``INFIX_CONFIG_DIR`` wins — some CI images have a read-only home."""
49
+ override = os.environ.get("INFIX_CONFIG_DIR", "").strip()
50
+ return Path(override) if override else Path.home() / ".infix"
51
+
52
+
53
+ def config_path() -> Path:
54
+ return config_dir() / "config.toml"
55
+
56
+
57
+ def cache_dir() -> Path:
58
+ """Where throwaway state lives — safe to delete, never holds credentials.
59
+
60
+ Separate from the config root so that wiping it cannot cost a user their
61
+ login, and overridable for the same reason config_dir is.
62
+ """
63
+ override = os.environ.get("INFIX_CACHE_DIR", "").strip()
64
+ return Path(override) if override else config_dir() / "cache"
65
+
66
+
67
+ @dataclass
68
+ class Profile:
69
+ """One resolved identity: where to talk to, as whom, in which workspace."""
70
+
71
+ name: str
72
+ api_url: str = ""
73
+ api_key: str = ""
74
+ workspace_id: str = ""
75
+ workspace_name: str = ""
76
+ defaults: dict[str, Any] = field(default_factory=dict)
77
+ auth_method: str = "api_key"
78
+ expires_at: str = ""
79
+
80
+ def web_url(self, path: str) -> str | None:
81
+ """Front-end address for a resource, or ``None`` when it has none.
82
+
83
+ Every workspace-scoped page in the web app nests under ``/w/<id>``
84
+ (``web/src/app/routes.tsx``), so a link built from the endpoint alone
85
+ resolves to a route that does not exist. The id is on the profile
86
+ because login stores it, but a config written before that did — or one
87
+ assembled from ``INFIX_API_URL`` alone — has none, and returning
88
+ ``None`` keeps a dead link out of the output rather than printing one
89
+ that 404s.
90
+ """
91
+ if not self.api_url or not self.workspace_id:
92
+ return None
93
+ return f"{self.api_url.rstrip('/')}/w/{self.workspace_id}/{path.lstrip('/')}"
94
+
95
+ def require_credentials(self) -> None:
96
+ """Fail with the PRD's wording when there are no credentials to use."""
97
+ if not self.api_url or not self.api_key:
98
+ message = 'Not logged in. Run "infix auth login" to authenticate.'
99
+ if self.name != DEFAULT_PROFILE:
100
+ # Only mention the profile when one was actually selected —
101
+ # otherwise the message is noise for the common case.
102
+ message = f'{message[:-1]} (profile "{self.name}").'
103
+ raise AuthError(message)
104
+
105
+
106
+ def load_raw() -> dict[str, Any]:
107
+ """Read the whole config file. Missing file is not an error — it means logged out."""
108
+ path = config_path()
109
+ if not path.exists():
110
+ return {}
111
+ try:
112
+ with path.open("rb") as handle:
113
+ return tomllib.load(handle)
114
+ except (OSError, tomllib.TOMLDecodeError) as exc:
115
+ raise UsageError(f"Cannot read config file {path}: {exc}") from exc
116
+
117
+
118
+ def current_profile_name(raw: dict[str, Any] | None = None) -> str:
119
+ """Active profile: ``INFIX_PROFILE`` (per-terminal) beats the stored default."""
120
+ env = os.environ.get("INFIX_PROFILE", "").strip()
121
+ if env:
122
+ return env
123
+ raw = load_raw() if raw is None else raw
124
+ stored = raw.get("current_profile")
125
+ return str(stored) if stored else DEFAULT_PROFILE
126
+
127
+
128
+ def load_profile(name: str | None = None, *, use_env: bool = True) -> Profile:
129
+ """Resolve one profile, with environment variables layered on top.
130
+
131
+ Precedence (tech-design §3.9): flag > env > config file > built-in default.
132
+ The flag layer is applied by the caller, which knows the flag values.
133
+ """
134
+ raw = load_raw()
135
+ profile_name = name or current_profile_name(raw)
136
+ section = (raw.get("profiles") or {}).get(profile_name) or {}
137
+
138
+ api_key = str(section.get("api_key") or "")
139
+ profile = Profile(
140
+ name=profile_name,
141
+ api_url=str(section.get("api_url") or ""),
142
+ api_key=api_key,
143
+ workspace_id=str(section.get("workspace_id") or ""),
144
+ workspace_name=str(section.get("workspace_name") or ""),
145
+ defaults=dict(section.get("defaults") or {}),
146
+ auth_method=str(section.get("auth_method") or "api_key"),
147
+ expires_at=str(section.get("expires_at") or ""),
148
+ )
149
+
150
+ if not use_env:
151
+ return profile
152
+
153
+ env_url = os.environ.get("INFIX_API_URL", "").strip()
154
+ env_key = os.environ.get("INFIX_API_KEY", "").strip()
155
+ env_ws = os.environ.get("INFIX_WORKSPACE_ID", "").strip()
156
+ changed_origin = env_url and env_url.rstrip("/") != profile.api_url.rstrip("/")
157
+ if env_url:
158
+ profile.api_url = env_url
159
+ if profile.auth_method == "browser" and changed_origin:
160
+ # Never forward a saved browser credential to a different deployment.
161
+ profile.api_key = ""
162
+ profile.workspace_id = ""
163
+ profile.workspace_name = ""
164
+ profile.auth_method = "api_key"
165
+ profile.expires_at = ""
166
+ if env_key and env_key != profile.api_key:
167
+ # A different key from the environment carries its own workspace
168
+ # binding; the stored workspace id belongs to the file's key and would
169
+ # be rejected by _enforce_api_key_workspace_binding. Drop it and let
170
+ # the caller re-resolve.
171
+ profile.api_key = env_key
172
+ profile.auth_method = "api_key"
173
+ profile.expires_at = ""
174
+ profile.workspace_id = ""
175
+ profile.workspace_name = ""
176
+ if env_ws and profile.auth_method != "browser":
177
+ profile.workspace_id = env_ws
178
+ if not profile.api_url:
179
+ profile.api_url = DEFAULT_API_URL
180
+ return profile
181
+
182
+
183
+ def save_profile(
184
+ profile: Profile, *, make_current: bool = True, expected_key: str | None = None,
185
+ ) -> Path:
186
+ """Write one profile back, preserving every other profile in the file."""
187
+
188
+ def mutate(raw: dict[str, Any]) -> dict[str, Any]:
189
+ profiles = raw.setdefault("profiles", {})
190
+ entry = dict(profiles.get(profile.name) or {})
191
+ if expected_key is not None and entry.get("api_key", "") != expected_key:
192
+ raise AuthError("This profile changed during login. Run infix auth login again.")
193
+ entry.update(
194
+ api_url=profile.api_url,
195
+ api_key=profile.api_key,
196
+ workspace_id=profile.workspace_id,
197
+ workspace_name=profile.workspace_name,
198
+ )
199
+ if profile.auth_method == "browser":
200
+ entry.update(auth_method=profile.auth_method, expires_at=profile.expires_at)
201
+ else:
202
+ entry.pop("auth_method", None)
203
+ entry.pop("expires_at", None)
204
+ if profile.defaults:
205
+ entry["defaults"] = profile.defaults
206
+ profiles[profile.name] = entry
207
+ if make_current:
208
+ raw["current_profile"] = profile.name
209
+ return raw
210
+
211
+ return _update(mutate)
212
+
213
+
214
+ def delete_profile(name: str, *, expected_key: str | None = None) -> bool:
215
+ """Remove a profile. Returns False when it was not there to begin with."""
216
+ removed = False
217
+
218
+ def mutate(raw: dict[str, Any]) -> dict[str, Any]:
219
+ nonlocal removed
220
+ profiles = raw.get("profiles") or {}
221
+ if name in profiles:
222
+ if expected_key is not None and profiles[name].get("api_key", "") != expected_key:
223
+ return
224
+ del profiles[name]
225
+ removed = True
226
+ raw["profiles"] = profiles
227
+ if removed and raw.get("current_profile") == name:
228
+ remaining = sorted(profiles)
229
+ if remaining:
230
+ raw["current_profile"] = remaining[0]
231
+ else:
232
+ raw.pop("current_profile", None)
233
+ return raw
234
+
235
+ _update(mutate)
236
+ return removed
237
+
238
+
239
+ def _update(mutate) -> Path:
240
+ """Read-modify-write the config under an exclusive lock, atomically."""
241
+ import fcntl
242
+ import tempfile
243
+
244
+ directory = config_dir()
245
+ directory.mkdir(parents=True, exist_ok=True)
246
+ os.chmod(directory, 0o700)
247
+ path = config_path()
248
+ lock_path = directory / ".config.lock"
249
+
250
+ with open(lock_path, "w") as lock:
251
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
252
+ try:
253
+ raw = load_raw()
254
+ raw = mutate(raw)
255
+ fd, tmp_name = tempfile.mkstemp(dir=str(directory), prefix=".config-", suffix=".toml")
256
+ try:
257
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
258
+ handle.write(dumps(raw))
259
+ os.chmod(tmp_name, 0o600)
260
+ os.replace(tmp_name, path)
261
+ except BaseException:
262
+ if os.path.exists(tmp_name):
263
+ os.unlink(tmp_name)
264
+ raise
265
+ finally:
266
+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
267
+ return path
268
+
269
+
270
+ def dumps(data: dict[str, Any]) -> str:
271
+ """Minimal TOML writer for the shapes this file uses.
272
+
273
+ Hand-rolled on purpose: the only alternative is a third dependency
274
+ (``tomli-w``) for a file with two levels of tables and scalar values.
275
+ """
276
+ lines: list[str] = []
277
+ for key, value in data.items():
278
+ if isinstance(value, dict):
279
+ continue
280
+ lines.append(f"{key} = {_scalar(value)}")
281
+ if lines:
282
+ lines.append("")
283
+
284
+ for name, section in (data.get("profiles") or {}).items():
285
+ lines.append(f"[profiles.{name}]")
286
+ nested: list[tuple[str, dict[str, Any]]] = []
287
+ for key, value in section.items():
288
+ if isinstance(value, dict):
289
+ nested.append((key, value))
290
+ continue
291
+ if value is None or value == "":
292
+ continue
293
+ lines.append(f"{key} = {_scalar(value)}")
294
+ lines.append("")
295
+ for key, value in nested:
296
+ lines.append(f"[profiles.{name}.{key}]")
297
+ for sub_key, sub_value in value.items():
298
+ if sub_value is None:
299
+ continue
300
+ lines.append(f"{sub_key} = {_scalar(sub_value)}")
301
+ lines.append("")
302
+ return "\n".join(lines).rstrip() + "\n"
303
+
304
+
305
+ def _scalar(value: Any) -> str:
306
+ if isinstance(value, bool):
307
+ return "true" if value else "false"
308
+ if isinstance(value, (int, float)):
309
+ return str(value)
310
+ text = str(value).replace("\\", "\\\\").replace('"', '\\"')
311
+ return f'"{text}"'
@@ -0,0 +1,217 @@
1
+ """结构化任务输入:有界读取、严格 JSON/YAML、按命令校验。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from infix_cli.cli_framework import click, parameter_schema, valid_value
10
+ from infix_cli.errors import UsageError
11
+
12
+ MAX_CONFIG_BYTES = 2 * 1024 * 1024
13
+ EXECUTION_OPTIONS = {"config", "wait", "timeout", "dry_run", "yes", "force", "save"}
14
+
15
+
16
+ def redact(value):
17
+ """预检结果不回显常见凭据字段。"""
18
+ if isinstance(value, dict):
19
+ return {
20
+ key: "[REDACTED]"
21
+ if any(
22
+ secret in key.lower().replace("-", "_")
23
+ for secret in ("api_key", "password", "token", "secret")
24
+ )
25
+ else redact(item)
26
+ for key, item in value.items()
27
+ }
28
+ if isinstance(value, list):
29
+ return [redact(item) for item in value]
30
+ return value
31
+
32
+
33
+ def read_document(path: str) -> dict:
34
+ def unique(pairs):
35
+ result = {}
36
+ for key, value in pairs:
37
+ if not isinstance(key, str) or key in result:
38
+ raise ValueError("duplicate or non-string key")
39
+ result[key] = value
40
+ return result
41
+
42
+ def validate(value, ancestors=frozenset(), depth=0, budget=None):
43
+ budget = [100000] if budget is None else budget
44
+ budget[0] -= 1
45
+ if depth > 100 or budget[0] < 0 or id(value) in ancestors:
46
+ raise ValueError("recursive or oversized configuration")
47
+ if isinstance(value, (dict, list)):
48
+ children = (
49
+ unique(value.items()).values() if isinstance(value, dict) else value
50
+ )
51
+ for child in children:
52
+ validate(child, ancestors | {id(value)}, depth + 1, budget)
53
+
54
+ try:
55
+ if path == "-":
56
+ content = sys.stdin.read(MAX_CONFIG_BYTES + 1)
57
+ else:
58
+ with Path(path).expanduser().open(encoding="utf-8") as stream:
59
+ content = stream.read(MAX_CONFIG_BYTES + 1)
60
+ if len(content.encode("utf-8")) > MAX_CONFIG_BYTES:
61
+ raise UsageError("Configuration exceeds 2 MiB.")
62
+ # 先尝试严格 JSON,只有语法不匹配才尝试 YAML,兼容以 { 开头的
63
+ # YAML 流式映射;重复键和非有限数值不能通过回退绕过检查。
64
+ try:
65
+ value = json.loads(
66
+ content,
67
+ object_pairs_hook=unique,
68
+ parse_constant=lambda _: (_ for _ in ()).throw(ValueError()),
69
+ )
70
+ except json.JSONDecodeError:
71
+ if path != "-" and Path(path).suffix.lower() == ".json":
72
+ raise
73
+ import yaml
74
+
75
+ class ConfigLoader(yaml.SafeLoader):
76
+ pass
77
+
78
+ def mapping(loader, node):
79
+ if not isinstance(node, yaml.MappingNode):
80
+ raise TypeError("invalid mapping")
81
+ return unique(
82
+ (loader.construct_object(key), loader.construct_object(val))
83
+ for key, val in node.value
84
+ )
85
+
86
+ ConfigLoader.add_constructor(
87
+ yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, mapping
88
+ )
89
+ value = yaml.load(content, Loader=ConfigLoader)
90
+ validate(value)
91
+ json.dumps(value, allow_nan=False)
92
+ if not isinstance(value, dict):
93
+ raise TypeError("expected an object")
94
+ return value
95
+ except FileNotFoundError as exc:
96
+ raise UsageError(
97
+ f'Config file not found: "{path}".', details={"field": "config"}
98
+ ) from exc
99
+ except (OSError, UnicodeError, ValueError, TypeError, RecursionError) as exc:
100
+ raise UsageError(
101
+ "Configuration must be a JSON or YAML object with unique string keys and finite values.",
102
+ details={"field": "config"},
103
+ ) from exc
104
+ except Exception as exc:
105
+ # YAML 解析器的异常不回显原文,配置中可能包含 endpoint 密钥。
106
+ import yaml
107
+
108
+ if isinstance(exc, yaml.YAMLError):
109
+ raise UsageError(
110
+ "Invalid YAML configuration.", details={"field": "config"}
111
+ ) from exc
112
+ raise
113
+
114
+
115
+ def config_parameters(ctx: click.Context) -> dict:
116
+ return {
117
+ p.name: p
118
+ for p in ctx.command.params
119
+ if p.name not in EXECUTION_OPTIONS and p.name != "help"
120
+ }
121
+
122
+
123
+ def load_job_config(path: str | None) -> dict:
124
+ if path is None:
125
+ return {}
126
+ raw = read_document(path)
127
+ config = {}
128
+ for key, value in raw.items():
129
+ normalized = key.replace("-", "_")
130
+ if normalized in config:
131
+ raise UsageError(
132
+ f"Duplicate configuration field: {normalized}.",
133
+ details={"field": normalized},
134
+ )
135
+ config[normalized] = value
136
+ ctx = click.get_current_context(silent=True)
137
+ if ctx is None:
138
+ return config
139
+ parameters = config_parameters(ctx)
140
+ aliases = {
141
+ "hyperparameters": "setting",
142
+ "set": "setting",
143
+ "engine_args": "engine_arg",
144
+ }
145
+ # serving clone 额外导出的字段。
146
+ extras = (
147
+ {"image", "port"} if ctx.parent and ctx.parent.info_name == "deploy" else set()
148
+ )
149
+ issues = []
150
+ for key, value in config.items():
151
+ target = aliases.get(key, key)
152
+ param = parameters.get(target)
153
+ if key in {"setting", "engine_arg"}:
154
+ param = None
155
+ if param is None and key not in extras:
156
+ issues.append({"field": key, "reason": "unknown field"})
157
+ continue
158
+ if param is None:
159
+ if key == "image" and not isinstance(value, str):
160
+ issues.append({"field": key, "reason": "expected string"})
161
+ if key == "port" and (type(value) is not int or not 1 <= value <= 65535):
162
+ issues.append(
163
+ {"field": key, "reason": "expected integer from 1 to 65535"}
164
+ )
165
+ continue
166
+ if ctx.get_parameter_source(target) == click.core.ParameterSource.COMMANDLINE:
167
+ issues.append(
168
+ {"field": key, "reason": "conflicts with command-line option"}
169
+ )
170
+ if target in {"setting", "spark_conf", "engine_arg"} and isinstance(
171
+ value, dict
172
+ ):
173
+ continue
174
+ if value is None and param.default is None:
175
+ continue
176
+ expected = parameter_schema(param)
177
+ values = [value]
178
+ if expected["type"] == "array":
179
+ if isinstance(value, list):
180
+ values = value
181
+ elif target != "dataset":
182
+ reason = (
183
+ "expected array or object"
184
+ if target in {"setting", "spark_conf", "engine_arg"}
185
+ else "expected array"
186
+ )
187
+ issues.append({"field": key, "reason": reason})
188
+ continue
189
+ # Spark 历史配置也接受单条数据集引用。
190
+ expected = expected["items"]
191
+ for item in values:
192
+ if not valid_value(item, expected):
193
+ issues.append(
194
+ {
195
+ "field": key,
196
+ "reason": f"expected {expected['type']} within the declared choices/range",
197
+ }
198
+ )
199
+ break
200
+ if "set" in config and "hyperparameters" in config:
201
+ issues.append({"field": "hyperparameters", "reason": "conflicts with set"})
202
+ # 配置描述整个任务;任何显式任务选项都不能被静默忽略。
203
+ for name in parameters:
204
+ if ctx.get_parameter_source(
205
+ name
206
+ ) == click.core.ParameterSource.COMMANDLINE and not any(
207
+ i["field"] == name for i in issues
208
+ ):
209
+ issues.append(
210
+ {
211
+ "field": name,
212
+ "reason": "task options cannot be combined with --config",
213
+ }
214
+ )
215
+ if issues:
216
+ raise UsageError("Invalid task configuration.", details=issues)
217
+ return config
infix_cli/context.py ADDED
@@ -0,0 +1,84 @@
1
+ """Per-invocation state: resolved identity, output preferences, HTTP client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from infix_cli.config import Profile, load_profile
9
+ from infix_cli.errors import ExitCode
10
+
11
+ # --exit-zero only neutralises *result* codes; a command that could not run at
12
+ # all (bad credentials, missing resource) still reports why.
13
+ _RESULT_CODES = frozenset({ExitCode.TIMEOUT, ExitCode.JOB_FAILED, ExitCode.JOB_RUNNING})
14
+
15
+
16
+ @dataclass
17
+ class RunContext:
18
+ """What every command needs: where to talk, and how to print."""
19
+
20
+ output: str = "json"
21
+ quiet: bool = False
22
+ no_color: bool = False
23
+ verbose: bool = False
24
+ exit_zero: bool = False
25
+ no_update_check: bool = False
26
+ profile_name: str | None = None
27
+ fields: tuple[str, ...] = ()
28
+ warnings: list[dict] = field(default_factory=list)
29
+ _profile: Profile | None = field(default=None, repr=False)
30
+ _client: Any = field(default=None, repr=False)
31
+
32
+ @property
33
+ def profile(self) -> Profile:
34
+ if self._profile is None:
35
+ # Read once per process: a 20-hour --wait must not change behaviour
36
+ # because another terminal ran auth login in the meantime.
37
+ self._profile = load_profile(self.profile_name)
38
+ return self._profile
39
+
40
+ def client(self, *, require_workspace: bool = True) -> Any:
41
+ """Build (once) an authenticated client for the active profile."""
42
+ if self._client is not None:
43
+ return self._client
44
+ from infix_cli.http.client import ApiClient
45
+
46
+ profile = self.profile
47
+ profile.require_credentials()
48
+ if require_workspace and not profile.workspace_id:
49
+ from infix_cli.workspace import discover_workspace
50
+
51
+ probe = ApiClient(profile.api_url, profile.api_key, verbose=self.verbose)
52
+ try:
53
+ me = probe.get("/account/me")
54
+ workspace_id, workspace_name = discover_workspace(probe, profile.api_key, me)
55
+ finally:
56
+ probe.close()
57
+ profile.workspace_id = workspace_id
58
+ profile.workspace_name = profile.workspace_name or workspace_name
59
+
60
+ self._client = ApiClient(
61
+ profile.api_url,
62
+ profile.api_key,
63
+ profile.workspace_id if require_workspace else "",
64
+ verbose=self.verbose,
65
+ )
66
+ return self._client
67
+
68
+ def close(self) -> None:
69
+ if self._client is not None:
70
+ self._client.close()
71
+ self._client = None
72
+
73
+ def resolve_exit(self, code: ExitCode | int) -> int:
74
+ """Apply --exit-zero to result-bearing exit codes."""
75
+ value = int(code)
76
+ if self.exit_zero and value in {int(c) for c in _RESULT_CODES}:
77
+ return int(ExitCode.OK)
78
+ return value
79
+
80
+ def default_page_size(self, requested: int | None) -> int:
81
+ if requested:
82
+ return requested
83
+ stored = self.profile.defaults.get("page_size")
84
+ return int(stored) if stored else 10