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,122 @@
1
+ """Fusion/Merge 的配置结构。动态参数及资源约束由目标平台提供。"""
2
+
3
+ from infix_cli.commands._fusion_config import ALIASES, ORDER
4
+ from infix_cli.domain.enums import VISIBILITY
5
+
6
+ _STRING = {"type": "string", "minLength": 1}
7
+ _OBJECT = {"type": "object"}
8
+ _REF = {"$ref": "#/$defs/reference"}
9
+ _REFS = {"type": "object", "minProperties": 1, "additionalProperties": _REF}
10
+ _NAME = {"type": "string", "minLength": 1, "maxLength": 200}
11
+
12
+
13
+ def _object(properties, required=(), *, additional=False):
14
+ return {
15
+ "type": "object",
16
+ "properties": properties,
17
+ "required": list(required),
18
+ "additionalProperties": additional,
19
+ }
20
+
21
+
22
+ def pipeline_config_schema(kind):
23
+ metadata = {
24
+ "name": _NAME,
25
+ "visibility": {"enum": list(VISIBILITY.cli_values), "default": "private"},
26
+ "description": {"type": "string", "maxLength": 10000},
27
+ "output_name": _NAME,
28
+ "schema_version": _STRING,
29
+ "parameter_contract": _STRING,
30
+ }
31
+ stage = _object({
32
+ "inputs": {"type": "object", "additionalProperties": {"$ref": "#/$defs/port"}},
33
+ "params": _OBJECT,
34
+ "resources": {"type": ["object", "null"]},
35
+ })
36
+ if kind == "fusion":
37
+ stages = (*ORDER, *ALIASES)
38
+ stage_ref = {"$ref": "#/$defs/stage"}
39
+ stage = _object({
40
+ **stage["properties"],
41
+ "input": {"$ref": "#/$defs/port"},
42
+ "set": _OBJECT,
43
+ "hardware": _STRING,
44
+ "teacher_hardware": _STRING,
45
+ "workers": {"type": "integer", "minimum": 1},
46
+ "student": _REF,
47
+ "checkpoint_precision": _STRING,
48
+ }, additional=True)
49
+ stage["allOf"] = [
50
+ {"not": {"required": ["set", "params"]}},
51
+ {"not": {"required": ["hardware", "resources"]}},
52
+ ]
53
+ teacher = _object({
54
+ "model": _REF, "prompt": _REF, "preset": _STRING, "domain": _STRING,
55
+ "weight": {"type": "number", "exclusiveMinimum": 0},
56
+ })
57
+ props = {
58
+ **metadata,
59
+ "from": {"enum": list(stages), "default": "split"},
60
+ "to": {"enum": list(stages), "default": "opd"},
61
+ "student": {"anyOf": [_REF, {"type": "null"}]},
62
+ "teachers": {
63
+ "anyOf": [
64
+ {"type": "object", "additionalProperties": {
65
+ **teacher, "required": ["model"],
66
+ }},
67
+ {"type": "array", "items": {"anyOf": [
68
+ _STRING,
69
+ {**teacher, "anyOf": [
70
+ {"required": ["model"]}, {"required": ["preset"]},
71
+ ]},
72
+ ]}},
73
+ ],
74
+ },
75
+ "stages": _object(dict.fromkeys(stages, stage_ref)),
76
+ **dict.fromkeys(stages, stage_ref),
77
+ "base": {"type": "null"},
78
+ "experts": {"const": {}},
79
+ }
80
+ schema = _object(props)
81
+ else:
82
+ props = {
83
+ **metadata,
84
+ "base_model": _REF,
85
+ "expert_model": {"type": "array", "items": _REF, "minItems": 1},
86
+ "experts": _REFS,
87
+ "method": _STRING,
88
+ "set": _OBJECT,
89
+ "hardware": _STRING,
90
+ "calibration": _REFS,
91
+ "from": {"const": "merge"},
92
+ "to": {"const": "merge"},
93
+ "base": _REF,
94
+ "stages": _object({"merge": {"$ref": "#/$defs/stage"}}, ("merge",)),
95
+ "student": {"type": "null"},
96
+ "teachers": {"const": {}},
97
+ }
98
+ schema = _object(props)
99
+ schema["anyOf"] = [
100
+ {"required": ["base_model", "expert_model"]},
101
+ {"required": ["base_model", "experts"]},
102
+ {"required": ["stages"]},
103
+ ]
104
+ return {
105
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
106
+ **schema,
107
+ "$defs": {
108
+ "reference": {"anyOf": [
109
+ {**_STRING, "description": "official/NAME, workspace/NAME:VERSION or storage/PATH."},
110
+ *[
111
+ _object({key: _STRING}, (key,))
112
+ for key in ("asset", "path", "snapshot", "from")
113
+ ],
114
+ ]},
115
+ "port": {"anyOf": [
116
+ _REF,
117
+ _object({"domains": _REFS, "base": _REF}, ("domains",)),
118
+ {"type": "object", "additionalProperties": {"$ref": "#/$defs/port"}},
119
+ ]},
120
+ "stage": stage,
121
+ },
122
+ }
@@ -0,0 +1,79 @@
1
+ """Output rendering: one DTO, three presentations (text / json / quiet)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Sequence
6
+
7
+ from infix_cli.render import json_out, text
8
+
9
+
10
+ def render_list(
11
+ ctx: Any,
12
+ items: Sequence[Any],
13
+ columns: list[tuple[str, str]],
14
+ *,
15
+ page: int | None,
16
+ page_size: int | None,
17
+ total: int,
18
+ quiet_field: str = "name",
19
+ empty_message: str = "No items found.",
20
+ title: str | None = None,
21
+ footer: str | None = None,
22
+ ) -> None:
23
+ """Render a paginated collection in whichever format the context selects.
24
+
25
+ ``title``/``footer`` are text-only by construction: a heading above the table
26
+ and the "what to do with these" lines under it are reading aids, and emitting
27
+ them in JSON or quiet mode would corrupt output meant to be parsed.
28
+ """
29
+ if ctx.output == "json":
30
+ json_out.print_list(items, page=page, page_size=page_size, total=total)
31
+ return
32
+ if ctx.quiet:
33
+ for item in items:
34
+ print(getattr(item, quiet_field, ""))
35
+ return
36
+ text.print_table(
37
+ ctx, items, columns, page=page, page_size=page_size, total=total,
38
+ empty_message=empty_message, title=title, footer=footer,
39
+ )
40
+
41
+
42
+ def render_detail(ctx: Any, item: Any, *, quiet_field: str = "id") -> None:
43
+ if ctx.output == "json":
44
+ json_out.print_object(item)
45
+ return
46
+ if ctx.quiet:
47
+ print(getattr(item, quiet_field, ""))
48
+ return
49
+ sections = getattr(item, "detail_sections", None)
50
+ if callable(sections):
51
+ text.print_sections(ctx, sections())
52
+ return
53
+ text.print_detail(ctx, item)
54
+
55
+
56
+ def render_object(ctx: Any, payload: dict, rows: list[tuple[str, str]], *, quiet_value: str = "") -> None:
57
+ """Render a plain dict (auth status, upload summary) without a DTO."""
58
+ if ctx.output == "json":
59
+ json_out.print_raw(payload)
60
+ return
61
+ if ctx.quiet:
62
+ if quiet_value:
63
+ print(quiet_value)
64
+ return
65
+ text.print_rows(ctx, rows)
66
+
67
+
68
+ def message(ctx: Any, text_line: str, *, symbol: str = "ok") -> None:
69
+ """A one-line confirmation. Suppressed by --quiet, absent from JSON output."""
70
+ if ctx.output == "json" or ctx.quiet:
71
+ return
72
+ text.print_message(ctx, text_line, symbol=symbol)
73
+
74
+
75
+ def note(ctx: Any, text_line: str) -> None:
76
+ """An explanation of empty output, on stderr. Same suppression as message."""
77
+ if ctx.output == "json" or ctx.quiet:
78
+ return
79
+ text.print_note(ctx, text_line)
@@ -0,0 +1,123 @@
1
+ """JSON output — contract #3 in its machine-readable form.
2
+
3
+ Shapes are fixed: ``list`` always emits ``{items, page, page_size, total}``
4
+ (so ``jq '.items[]'`` works everywhere, and ``total`` survives explicit
5
+ pagination), ``get`` emits the object directly, and errors never appear on
6
+ stdout.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from typing import Any, Sequence
14
+
15
+
16
+ def _dump(payload: Any) -> None:
17
+ from infix_cli.cli_framework import click
18
+
19
+ ctx = click.get_current_context(silent=True)
20
+ fields = getattr(ctx.obj, "fields", ()) if ctx else ()
21
+ warnings = getattr(ctx.obj, "warnings", []) if ctx else []
22
+ if warnings and isinstance(payload, dict):
23
+ payload = {**payload, "warnings": [*(payload.get("warnings") or []), *warnings]}
24
+ if fields:
25
+ payload = project(payload, fields)
26
+ # 先完整序列化;非法服务端数值不能留下半份 JSON。
27
+ encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":"), default=str)
28
+ sys.stdout.write(encoded + "\n")
29
+
30
+
31
+ def print_list(
32
+ items: Sequence[Any],
33
+ *,
34
+ page: int | None,
35
+ page_size: int | None,
36
+ total: int,
37
+ ) -> None:
38
+ _dump({
39
+ "items": [_to_dict(item) for item in items],
40
+ "page": page,
41
+ "page_size": page_size,
42
+ "total": total,
43
+ })
44
+
45
+
46
+ def print_object(item: Any) -> None:
47
+ _dump(_to_dict(item))
48
+
49
+
50
+ def print_raw(payload: Any) -> None:
51
+ _dump(payload)
52
+
53
+
54
+ def print_ndjson(record: dict) -> None:
55
+ """One record per line — the shape ``logs -o json`` streams."""
56
+ sys.stdout.write(json.dumps(record, ensure_ascii=False, default=str) + "\n")
57
+ sys.stdout.flush()
58
+
59
+
60
+ def project(payload: Any, fields: tuple[str, ...]) -> Any:
61
+ """只裁剪结果对象;分页元数据和总数保持完整。"""
62
+ from infix_cli.errors import UsageError
63
+
64
+ paths = [tuple(field.split(".")) for field in fields]
65
+ selected_paths = set(paths)
66
+ # 选中整个对象时,它的子路径已包含在结果中。
67
+ paths = [
68
+ path for path in paths
69
+ if not any(path[:depth] in selected_paths for depth in range(1, len(path)))
70
+ ]
71
+
72
+ found = set()
73
+ missing = set()
74
+ unverifiable = set()
75
+
76
+ def select(value, branches, depth=0):
77
+ if isinstance(value, list):
78
+ if not value:
79
+ unverifiable.update(branches)
80
+ return [select(item, branches, depth) for item in value]
81
+ if value is None:
82
+ unverifiable.update(branches)
83
+ return None
84
+ if not isinstance(value, dict):
85
+ missing.update(branches)
86
+ return None
87
+
88
+ grouped = {}
89
+ for path in branches:
90
+ grouped.setdefault(path[depth], []).append(path)
91
+ result = {}
92
+ for key, descendants in grouped.items():
93
+ if key not in value:
94
+ missing.update(descendants)
95
+ result[key] = None
96
+ elif len(descendants[0]) == depth + 1:
97
+ found.add(descendants[0])
98
+ result[key] = value[key]
99
+ else:
100
+ result[key] = select(value[key], descendants, depth + 1)
101
+ return result
102
+
103
+ if isinstance(payload, dict) and isinstance(payload.get("items"), list):
104
+ output = {**payload, "items": select(payload["items"], paths)}
105
+ elif isinstance(payload, (dict, list)):
106
+ output = select(payload, paths)
107
+ else:
108
+ return payload
109
+
110
+ # 空数组或 null 无法验证子路径。只要有可检查的记录,就按其中是否存在该字段判断。
111
+ valid = found | (unverifiable - missing)
112
+ invalid = list(dict.fromkeys(".".join(path) for path in paths if path not in valid))
113
+ if invalid:
114
+ details = {"field": "fields", "paths": invalid}
115
+ if isinstance(payload, dict):
116
+ details.update({key: payload[key] for key in ("id", "name") if key in payload})
117
+ raise UsageError("Unknown or invalid --fields paths: " + ", ".join(invalid), details=details)
118
+ return output
119
+
120
+
121
+ def _to_dict(item: Any) -> Any:
122
+ to_json = getattr(item, "to_json", None)
123
+ return to_json() if callable(to_json) else item
@@ -0,0 +1,62 @@
1
+ """Transfer progress for uploads.
2
+
3
+ Shared by ``storage upload`` and the local-source asset registrations, which
4
+ push bytes through the same chunked protocol and so should report them the same
5
+ way. Kept out of the command modules because both of them need it, and out of
6
+ ``text.py`` because this writes carriage returns rather than lines.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from typing import Any, Callable
13
+
14
+
15
+ def tracker(
16
+ ctx: Any, name: str, total: int, *, verb: str = "Uploading",
17
+ ) -> Callable[[int], None] | None:
18
+ """Return a callback that renders transfer progress, or None for no output.
19
+
20
+ Suppressed under --quiet and -o json, and when stdout is not a terminal — a
21
+ progress bar in a CI log is noise that cannot be read back.
22
+ """
23
+ if not _visible(ctx):
24
+ return None
25
+
26
+ state = {"sent": 0}
27
+
28
+ def update(chunk: int) -> None:
29
+ state["sent"] += chunk
30
+ done = min(state["sent"], total)
31
+ width = 24
32
+ filled = int(width * done / total) if total else width
33
+ bar = "█" * filled + " " * (width - filled)
34
+ percent = (done / total * 100) if total else 100
35
+ sys.stdout.write(
36
+ f"\r{verb} {name}... {percent:3.0f}% [{bar}] "
37
+ f"{_size(done)} / {_size(total)}",
38
+ )
39
+ sys.stdout.flush()
40
+
41
+ return update
42
+
43
+
44
+ def finish(ctx: Any) -> None:
45
+ """Close the line a tracker left open."""
46
+ if _visible(ctx):
47
+ sys.stdout.write("\n")
48
+ sys.stdout.flush()
49
+
50
+
51
+ def _visible(ctx: Any) -> bool:
52
+ return (
53
+ getattr(ctx, "output", "") != "json"
54
+ and not getattr(ctx, "quiet", False)
55
+ and sys.stdout.isatty()
56
+ )
57
+
58
+
59
+ def _size(size: int) -> str:
60
+ from infix_cli.domain.dto.common import format_bytes
61
+
62
+ return format_bytes(size)
@@ -0,0 +1,233 @@
1
+ """Human-readable output: tables, detail blocks, status lines.
2
+
3
+ Two degradations are handled centrally rather than per command: terminals
4
+ that cannot encode ``✓``/``✗`` get ``[ok]``/``[x]``, and non-TTY output drops
5
+ colour so piped text stays clean.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from typing import Any, Sequence
12
+
13
+ from infix_cli.domain.dto.common import format_bytes, format_duration
14
+
15
+ _SYMBOLS = {"ok": ("✓", "[ok]"), "error": ("✗", "[x]"), "warn": ("!", "[!]")}
16
+
17
+
18
+ def supports_unicode() -> bool:
19
+ encoding = (getattr(sys.stdout, "encoding", None) or "").lower()
20
+ return "utf" in encoding
21
+
22
+
23
+ def symbol_for(name: str) -> str:
24
+ """``✓`` / ``✗`` where the terminal can encode them, ``[ok]`` / ``[x]`` elsewhere."""
25
+ fancy, plain = _SYMBOLS.get(name, ("", ""))
26
+ return fancy if supports_unicode() else plain
27
+
28
+
29
+ def _console(ctx: Any, *, stderr: bool = False, width: int | None = None):
30
+ from rich.console import Console
31
+
32
+ return Console(
33
+ no_color=getattr(ctx, "no_color", False),
34
+ stderr=stderr,
35
+ highlight=False,
36
+ soft_wrap=True,
37
+ width=width,
38
+ )
39
+
40
+
41
+ # Width to measure a table against when asking how wide it wants to be.
42
+ _UNBOUNDED = 10_000
43
+
44
+
45
+ def print_table(
46
+ ctx: Any,
47
+ items: Sequence[Any],
48
+ columns: list[tuple[str, str]],
49
+ *,
50
+ page: int | None,
51
+ page_size: int | None,
52
+ total: int,
53
+ empty_message: str = "No items found.",
54
+ title: str | None = None,
55
+ footer: str | None = None,
56
+ ) -> None:
57
+ from rich import box
58
+ from rich.table import Table
59
+
60
+ console = _console(ctx)
61
+ if title:
62
+ console.print(title)
63
+ if not items:
64
+ console.print(empty_message)
65
+ return
66
+
67
+ table = Table(box=box.SIMPLE_HEAD, pad_edge=False, show_edge=False)
68
+ for header, _attr in columns:
69
+ table.add_column(header, no_wrap=True)
70
+ for item in items:
71
+ table.add_row(*[cell(item, attr) for _header, attr in columns])
72
+ # Cells are never cut or wrapped, as with kubectl get: a name or status
73
+ # shortened to "availa…" cannot be copied into the next command or
74
+ # grepped. A table wider than the terminal is printed at its natural width
75
+ # and the terminal wraps the lines; piped output (where rich assumes 80
76
+ # columns) gets every row whole.
77
+ natural = console.measure(table, options=console.options.update_width(_UNBOUNDED)).maximum
78
+ if natural > console.width:
79
+ console = _console(ctx, width=natural)
80
+ console.print(table)
81
+
82
+ if page and page_size and total:
83
+ first = (page - 1) * page_size + 1
84
+ last = min(page * page_size, total)
85
+ line = f"Showing {first}-{last} of {total}."
86
+ if last < total:
87
+ line += f" Use --page {page + 1} or --page-size {min(50, page_size * 2)} to see more."
88
+ console.print(line, style="dim")
89
+
90
+ if footer:
91
+ console.print(footer)
92
+
93
+
94
+ def print_detail(ctx: Any, item: Any) -> None:
95
+ rows_fn = getattr(item, "detail_rows", None)
96
+ rows = rows_fn() if callable(rows_fn) else []
97
+ print_rows(ctx, rows)
98
+
99
+
100
+ def print_labeled(
101
+ ctx: Any, rows: list[tuple[str, str]], *, indent: int = 2, gutter: int = 1,
102
+ ) -> None:
103
+ """The PRD's ``Label: value`` block, used by auth and dataset preview.
104
+
105
+ Distinct from print_rows on purpose: job and asset detail views in the PRD
106
+ are columns without colons, these have them. ``gutter`` is the space after
107
+ the longest label — one in the auth examples, two in the preview header.
108
+ """
109
+ console = _console(ctx)
110
+ if not rows:
111
+ return
112
+ width = max(len(label) for label, _ in rows) + 1 # + the colon
113
+ pad = " " * indent
114
+ for label, value in rows:
115
+ console.print(f"{pad}{(label + ':').ljust(width + gutter)}{value}")
116
+
117
+
118
+ # Width of the PRD's section rules: "─── Output ─────…" runs to 57 columns.
119
+ _RULE_WIDTH = 57
120
+
121
+ # Sentinel value: render the label on its own line, because the value that
122
+ # follows is too long to sit beside it (storage paths).
123
+ BLOCK_VALUE = "\x00block"
124
+
125
+
126
+ def print_sections(ctx: Any, sections: list[tuple[str | None, list[tuple[str, str]]]]) -> None:
127
+ """Render a grouped detail view, as the PRD writes job details.
128
+
129
+ A section with no title leads the block (Job Name / Status); the rest are
130
+ introduced by a rule. Labels align across the whole view rather than per
131
+ section — the PRD's own examples drift by a column or two between groups,
132
+ and one column is easier to read down.
133
+ """
134
+ console = _console(ctx)
135
+ labels = [
136
+ label for _title, rows in sections
137
+ for label, value in rows if label and value != BLOCK_VALUE
138
+ ]
139
+ if not labels:
140
+ return
141
+ width = max(len(label) for label in labels) + 2
142
+
143
+ for index, (title, rows) in enumerate(sections):
144
+ if title:
145
+ if index:
146
+ console.print("")
147
+ rule = "─" * max(1, _RULE_WIDTH - len(title) - 5)
148
+ console.print(f"─── {title} {rule}")
149
+ for label, value in rows:
150
+ if not label and not value:
151
+ console.print("") # blank row inside a section
152
+ elif value == BLOCK_VALUE:
153
+ console.print(label)
154
+ else:
155
+ console.print(f"{label.ljust(width)}{value}")
156
+
157
+
158
+ def print_rows(ctx: Any, rows: list[tuple[str, str]]) -> None:
159
+ console = _console(ctx)
160
+ if not rows:
161
+ return
162
+ # Two spaces after the longest label — the gutter every PRD detail example
163
+ # uses. Wider drifts noticeably on blocks with a long label like
164
+ # "Related Evaluation".
165
+ width = max(len(label) for label, _ in rows)
166
+ for label, value in rows:
167
+ console.print(f"{label.ljust(width)} {value}")
168
+
169
+
170
+ def print_message(ctx: Any, line: str, *, symbol: str = "ok") -> None:
171
+ mark = symbol_for(symbol)
172
+ _console(ctx).print(f"{mark} {line}" if mark else line)
173
+
174
+
175
+ def print_note(ctx: Any, line: str) -> None:
176
+ """A dim aside on stderr, so it survives `logs > file` without landing in it."""
177
+ _console(ctx, stderr=True).print(line, style="dim")
178
+
179
+
180
+ def print_error(message: str, hint: str | None = None, *, no_color: bool = False) -> None:
181
+ """Errors always go to stderr, so ``-o json`` stdout stays parseable."""
182
+ from rich.console import Console
183
+
184
+ console = Console(stderr=True, no_color=no_color, highlight=False, soft_wrap=True)
185
+ console.print(f"{symbol_for('error')} {message}", style="" if no_color else "red")
186
+ if hint:
187
+ console.print(f" {hint}", style="dim")
188
+
189
+
190
+ def print_warning(ctx: Any, message: str, hint: str | None = None) -> None:
191
+ """Something succeeded but not entirely as asked, on stderr.
192
+
193
+ Unlike ``message`` it is not suppressed by ``-o json`` or ``--quiet``: those
194
+ silence prose about what went right, and a warning is about what did not.
195
+ """
196
+ if ctx.output == "json":
197
+ ctx.warnings.append({"message": message, **({"hint": hint} if hint else {})})
198
+ return
199
+ console = _console(ctx, stderr=True)
200
+ no_color = getattr(ctx, "no_color", False)
201
+ console.print(f"{symbol_for('warn')} {message}", style="" if no_color else "yellow")
202
+ if hint:
203
+ console.print(f" {hint}", style="dim")
204
+
205
+
206
+ def cell(item: Any, attr: str) -> str:
207
+ """Format one table cell.
208
+
209
+ Formatting lives here, not in the DTO: JSON publishes raw numbers
210
+ (``duration_seconds``, ``size_bytes``, a 0-1 score) and only the text layer
211
+ turns them into ``1h 22m`` / ``256.0 MB`` / ``73.40%``.
212
+ """
213
+ value = getattr(item, attr, None)
214
+ if attr == "overall_score":
215
+ score_text = getattr(item, "score_text", None)
216
+ if callable(score_text):
217
+ return score_text()
218
+ if value is None or value == "":
219
+ return "--"
220
+ if attr == "duration_seconds":
221
+ return format_duration(value)
222
+ if attr == "size_bytes":
223
+ return format_bytes(value)
224
+ if attr.endswith("_at") and isinstance(value, str):
225
+ # Tables show "08-12 17:25": the year is almost always the current one
226
+ # and costs five columns that narrow terminals do not have. The full
227
+ # ISO timestamp stays in detail views and in JSON.
228
+ return value.replace("T", " ").rstrip("Z")[5:16]
229
+ if isinstance(value, bool):
230
+ return "yes" if value else "no"
231
+ if isinstance(value, (list, tuple)):
232
+ return ", ".join(str(v) for v in value) if value else "--"
233
+ return str(value)