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,360 @@
1
+ """``infix evaluation`` — evaluation jobs (read-only in this phase)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+ import typer
8
+
9
+ from infix_cli import render
10
+ from infix_cli.commands import _control, _create, _delete, _jobs, _logs, _publish
11
+ from infix_cli.domain import enums, refs, resolve
12
+ from infix_cli.domain.dto.evaluation import EvaluationJobDTO
13
+ from infix_cli.errors import UsageError
14
+ from infix_cli.http.pagination import fetch_page
15
+ from infix_cli.commands import _comparison
16
+
17
+ app = typer.Typer(help="Model evaluation jobs.", no_args_is_help=True)
18
+ app.command("compare")(_comparison.compare)
19
+ app.command("compare-get")(_comparison.get)
20
+ app.command("compare-list")(_comparison.history)
21
+
22
+
23
+ @app.command("list")
24
+ def list_jobs(
25
+ ctx: typer.Context,
26
+ status: Optional[str] = typer.Option(None, "--status", help="Filter by job status."),
27
+ search: Optional[str] = typer.Option(None, "--search", help="Fuzzy name match."),
28
+ visibility: Optional[str] = typer.Option(
29
+ None, "--visibility", help="private | public",
30
+ ),
31
+ page: int = typer.Option(1, "--page", "-p", min=1),
32
+ page_size: int = typer.Option(None, "--page-size", min=1, max=50),
33
+ ) -> None:
34
+ """List evaluation jobs in the current workspace."""
35
+ run = ctx.obj
36
+ # /evaluation/jobs accepts status and search, but not visibility (see the
37
+ # endpoint's Query list). Sending it anyway was silently dropped by FastAPI
38
+ # and the flag did nothing, so it is applied to the fetched page instead —
39
+ # the same way spark does it.
40
+ wanted_visibility = _jobs.validate_visibility(visibility)
41
+ items, page_no, size, total = fetch_page(
42
+ run.client(), "/evaluation/jobs",
43
+ params={
44
+ "status": _jobs.validate_status("evaluation", status),
45
+ "search": search,
46
+ },
47
+ page=page, page_size=run.default_page_size(page_size),
48
+ )
49
+ dtos = [EvaluationJobDTO.from_api(raw) for raw in items]
50
+ if wanted_visibility:
51
+ dtos = [dto for dto in dtos if dto.visibility == wanted_visibility.lower()]
52
+ # Local filtering breaks the page arithmetic, so the footer is dropped
53
+ # rather than left claiming a total it no longer describes.
54
+ render.render_list(
55
+ run, dtos, EvaluationJobDTO.columns(),
56
+ page=None, page_size=None, total=len(dtos),
57
+ empty_message=f"No matching evaluation jobs on page {page}.",
58
+ )
59
+ return
60
+ render.render_list(
61
+ run, dtos, EvaluationJobDTO.columns(),
62
+ page=page_no, page_size=size, total=total,
63
+ empty_message="No evaluation jobs found.",
64
+ )
65
+
66
+
67
+ @app.command("get")
68
+ def get_job(
69
+ ctx: typer.Context,
70
+ name: str = typer.Argument(..., help="Job name (or id)."),
71
+ ) -> None:
72
+ """Show one evaluation job, including its scores.
73
+
74
+ A successful query exits 0; the job outcome is in the status field.
75
+ """
76
+ run = ctx.obj
77
+ client = run.client()
78
+ job = resolve.find_job(client, "evaluation", name)
79
+ detail = client.get(f"/evaluation/jobs/{job['id']}")
80
+ dto = EvaluationJobDTO.from_api(detail if isinstance(detail, dict) else job, detail=True)
81
+ # The backend reports one source, assets_models, for both namespaces, so a
82
+ # job run against an official model reads as "Workspace" until the asset is
83
+ # asked. `clone` resolves the same way, and the two must not disagree.
84
+ if dto.model_source in ("workspace", "official") and dto._model_asset_id:
85
+ dto.model_source = resolve.asset_scope_by_id(client, "model", dto._model_asset_id)
86
+ # PRD 3.6 ends the result block with a link to the run's page. The backend
87
+ # returns no detail_url, so it is assembled from the configured endpoint —
88
+ # the same assumption the Related Evaluation field makes.
89
+ if dto.id:
90
+ dto.detail_url = run.profile.web_url(f"evaluation/{dto.id}")
91
+ render.render_detail(run, dto)
92
+
93
+
94
+ _MODEL_SOURCES = ("official", "workspace", "storage", "endpoint")
95
+
96
+
97
+ @app.command("create")
98
+ def create_job(
99
+ ctx: typer.Context,
100
+ name: Optional[str] = typer.Option(None, "--name", "-n", help="Job name (3-50 chars).", rich_help_panel="Required"),
101
+ eval_type: Optional[str] = typer.Option(None, "--eval-type", help="official | custom", rich_help_panel="Required"),
102
+ custom_format: Optional[str] = typer.Option(
103
+ None, "--custom-format",
104
+ help="With --eval-type custom: single-choice | question-answering.",
105
+ ),
106
+ model_source: Optional[str] = typer.Option(
107
+ None, "--model-source", help="official | workspace | storage | endpoint", rich_help_panel="Required",
108
+ ),
109
+ model: Optional[str] = typer.Option(
110
+ None, "--model",
111
+ help="Matching reference: official/<name>, workspace/<name>[:<version>], "
112
+ "storage/<path>, or the endpoint URL of a model service.",
113
+ rich_help_panel="Required",
114
+ ),
115
+ dataset: Optional[str] = typer.Option(
116
+ None, "--dataset", help="official/<name> | workspace/<name>[:<version>] | storage/<path>", rich_help_panel="Required",
117
+ ),
118
+ endpoint_api_key: Optional[str] = typer.Option(
119
+ None, "--endpoint-api-key", help="API key for the model service, when it needs one.", rich_help_panel="Required (conditional)",
120
+ ),
121
+ visibility: Optional[str] = typer.Option(None, "--visibility", help="private | public"),
122
+ chat_template: Optional[str] = typer.Option(
123
+ None, "--chat-template",
124
+ help="model uses the tokenizer template (default); plain uses a text-only prompt. Local models only.",
125
+ ),
126
+ config: Optional[str] = typer.Option(
127
+ None, "--config", help="JSON file of the same options. Task flags cannot be combined with --config. Use - for stdin.",
128
+ ),
129
+ wait: bool = typer.Option(
130
+ False, "--wait",
131
+ help="Block until the job finishes AND its results are collected.",
132
+ ),
133
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 6h."),
134
+ dry_run: bool = typer.Option(False, "--dry-run", help="Resolve and validate inputs without submitting a job."),
135
+ ) -> None:
136
+ """Submit an evaluation job.
137
+
138
+ Examples:
139
+
140
+ infix evaluation create -n eval-mmlu --eval-type official
141
+ --model-source workspace --model workspace/my-sft:v1.0.0 --dataset official/mmlu --wait
142
+
143
+ infix evaluation create -n eval-qa --eval-type custom
144
+ --custom-format question-answering --model-source endpoint
145
+ --model https://api.example.com/v1/services/qwen-prod
146
+ --dataset workspace/my-eval-set
147
+ """
148
+ run = ctx.obj
149
+ cfg = _create.load_config(config)
150
+ pick = _create.pick
151
+
152
+ name = pick(name, cfg, "name", required=True, flag="--name")
153
+ eval_type = pick(eval_type, cfg, "eval_type", default="official")
154
+ custom_format = pick(custom_format, cfg, "custom_format")
155
+ model_source = pick(model_source, cfg, "model_source", required=True, flag="--model-source")
156
+ model_ref = pick(model, cfg, "model", required=True, flag="--model")
157
+ dataset_ref = pick(dataset, cfg, "dataset", required=True, flag="--dataset")
158
+ endpoint_api_key = pick(endpoint_api_key, cfg, "endpoint_api_key")
159
+ visibility = pick(visibility, cfg, "visibility", default="private")
160
+ chat_template = pick(chat_template, cfg, "chat_template", default="model")
161
+ if chat_template not in {"model", "plain"}:
162
+ raise UsageError("chat-template must be model or plain.")
163
+ if model_source == "endpoint" and chat_template != "model":
164
+ raise UsageError("External services manage their own chat templates.")
165
+
166
+ if model_source not in _MODEL_SOURCES:
167
+ raise UsageError(
168
+ f'Invalid --model-source "{model_source}".',
169
+ f"Valid: {', '.join(_MODEL_SOURCES)}.",
170
+ )
171
+
172
+ client = run.client()
173
+ model_id, model_version_id, model_owner = _resolve_model(client, model_source, model_ref)
174
+ dataset_slot = _create.resolve_slot(client, dataset_ref, kind="dataset", flag="--dataset")
175
+
176
+ payload = _create.evaluation_payload(
177
+ name=name, eval_type=eval_type, custom_format=custom_format,
178
+ model_source=model_source, model_id=model_id, model_version_id=model_version_id,
179
+ model_owner_user_id=model_owner, dataset=dataset_slot,
180
+ endpoint_api_key=endpoint_api_key, visibility=visibility,
181
+ )
182
+ if chat_template != "model":
183
+ payload["inference_params"] = {"chat_template": chat_template}
184
+ _jobs.submit_and_report(
185
+ run, "evaluation",
186
+ echo={"model": model_ref, "dataset": dataset_ref},
187
+ path="/evaluation/jobs", payload=payload,
188
+ detail_path=lambda job_id: f"/evaluation/jobs/{job_id}",
189
+ build_dto=lambda raw: EvaluationJobDTO.from_api(raw, detail=True),
190
+ wait=wait, timeout=timeout, dry_run=dry_run,
191
+ poll_status=_jobs.evaluation_status,
192
+ )
193
+
194
+
195
+ def _resolve_model(client, model_source: str, value: str) -> tuple[str, str | None, str | None]:
196
+ """Resolve --model according to --model-source.
197
+
198
+ The two must agree: --model-source workspace with an official/ reference is a
199
+ contradiction, not a preference, so it is rejected rather than resolved one
200
+ way or the other. ``endpoint`` is the one source a prefix cannot express —
201
+ it takes the model service's endpoint URL (PRD 3.4.3), which the CLI maps
202
+ back to the service id the backend expects.
203
+ """
204
+ if model_source == "endpoint":
205
+ service = resolve.resolve_model_service(client, value)
206
+ return str(service.get("id")), None, None
207
+
208
+ ref = refs.parse_ref(value, kind="model", flag="--model")
209
+ if model_source == "storage":
210
+ if not isinstance(ref, refs.StorageRef):
211
+ raise UsageError(
212
+ f'--model-source storage expects a storage/ reference, got "{value}".',
213
+ )
214
+ if ref.path.startswith("/mnt/output"):
215
+ raise UsageError(
216
+ "/mnt/output paths are inside the training pod, not Workspace Storage.",
217
+ 'Use the path shown by "infix storage list".',
218
+ )
219
+ return ref.path, None, None
220
+
221
+ if isinstance(ref, refs.StorageRef):
222
+ raise UsageError(
223
+ f'--model-source {model_source} expects an asset reference, got "{value}".',
224
+ )
225
+ expected_official = model_source == "official"
226
+ if ref.is_official != expected_official:
227
+ raise UsageError(
228
+ f'--model-source {model_source} does not match the "{value}" reference.',
229
+ "official/ goes with --model-source official; workspace/ with --model-source workspace.",
230
+ )
231
+ resolved = resolve.resolve_asset(client, ref)
232
+ return resolved.asset_id, resolved.version_id, None
233
+
234
+
235
+ @app.command("logs")
236
+ def job_logs(
237
+ ctx: typer.Context,
238
+ name: str = typer.Argument(..., help="Job name (or id)."),
239
+ tail: int = typer.Option(500, "--tail", min=1, max=5000, help="Lines to read."),
240
+ keyword: Optional[str] = typer.Option(
241
+ None, "--keyword", help="Filter locally, within the --tail lines only.",
242
+ ),
243
+ ) -> None:
244
+ """Read an evaluation job's logs.
245
+
246
+ Evaluation has no streaming or download endpoint, so -f and --download are
247
+ offered for training and spark only.
248
+ """
249
+ run = ctx.obj
250
+ client = run.client()
251
+ job_id = str(resolve.find_job(client, "evaluation", name)["id"])
252
+ _logs.render(run, _logs.fetch(client, "evaluation", job_id, worker=None, tail=tail),
253
+ keyword=keyword)
254
+
255
+
256
+ @app.command("stop")
257
+ def stop_job(
258
+ ctx: typer.Context,
259
+ name: str = typer.Argument(..., help="Job name (or id)."),
260
+ ) -> None:
261
+ """Stop an evaluation job."""
262
+ run = ctx.obj
263
+ job = resolve.find_job(run.client(), "evaluation", name)
264
+ updated = _control.stop(run, "evaluation", job)
265
+ status = enums.status_to_cli(updated.get("status")) or "stopping"
266
+ render.message(run, f'Evaluation job "{job.get("name")}" is now {status}.')
267
+
268
+
269
+ @app.command("restart")
270
+ def restart_job(
271
+ ctx: typer.Context,
272
+ name: str = typer.Argument(..., help="Job name (or id)."),
273
+ wait: bool = typer.Option(False, "--wait"),
274
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 6h."),
275
+ ) -> None:
276
+ """Resubmit an evaluation job."""
277
+ run = ctx.obj
278
+ job = resolve.find_job(run.client(), "evaluation", name)
279
+ _control.restart(run, "evaluation", job)
280
+ job_id = str(job["id"])
281
+ _jobs.report_existing(
282
+ run, "evaluation", job_id=job_id, name=str(job.get("name") or job_id),
283
+ detail_path=lambda jid: f"/evaluation/jobs/{jid}",
284
+ build_dto=lambda raw: EvaluationJobDTO.from_api(raw, detail=True),
285
+ wait=wait, timeout=timeout, poll_status=_jobs.evaluation_status,
286
+ )
287
+
288
+
289
+ @app.command("wait")
290
+ def wait_job(
291
+ ctx: typer.Context,
292
+ name: str = typer.Argument(..., help="Job name (or id)."),
293
+ timeout: Optional[str] = typer.Option(None, "--timeout", help="e.g. 30m, 6h. Default: 30s."),
294
+ ) -> None:
295
+ """Wait for a evaluation job to finish; exit 0 on success, 7 on failure, 6 on timeout.
296
+
297
+ For re-attaching after an interrupted --wait. Ctrl-C stops waiting only;
298
+ the job keeps running.
299
+ """
300
+ run = ctx.obj
301
+ client = run.client()
302
+ job = resolve.find_job(client, "evaluation", name)
303
+ job_id = str(job["id"])
304
+ _jobs.wait_existing(
305
+ run, "evaluation", job_id=job_id, name=str(job.get("name") or job_id),
306
+ detail_path=lambda jid: f"/evaluation/jobs/{jid}",
307
+ build_dto=lambda raw: EvaluationJobDTO.from_api(raw, detail=True),
308
+ timeout=timeout, poll_status=_jobs.evaluation_status,
309
+ )
310
+
311
+
312
+ @app.command("publish")
313
+ def publish_job(
314
+ ctx: typer.Context,
315
+ name: str = typer.Argument(..., help="Job name (or id)."),
316
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
317
+ ) -> None:
318
+ """Make a evaluation job public to the workspace. This cannot be undone.
319
+
320
+ Its output directory is shared along with it.
321
+ """
322
+ _publish.publish_job(ctx.obj, "evaluation", name, yes=yes)
323
+
324
+
325
+ @app.command("delete")
326
+ def delete_job(
327
+ ctx: typer.Context,
328
+ name: str = typer.Argument(..., help="Job name (or id)."),
329
+ force: bool = typer.Option(
330
+ False, "--force", help="Delete even if the job is still queued or running.",
331
+ ),
332
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
333
+ ) -> None:
334
+ """Delete a evaluation job. This cannot be undone.
335
+
336
+ Its results are deleted with it; deletion completes asynchronously.
337
+ A job that has not finished is refused unless --force is given.
338
+ """
339
+ _delete.delete_job(ctx.obj, "evaluation", name, force=force, yes=yes)
340
+
341
+
342
+ @app.command("clone")
343
+ def clone_job(
344
+ ctx: typer.Context,
345
+ name: str = typer.Argument(..., help="Job to copy the configuration from."),
346
+ new_name: Optional[str] = typer.Option(
347
+ None, "--name", help="Name for the new job. Default: <original>-clone-1.",
348
+ ),
349
+ save: Optional[str] = typer.Option(None, "--save", help="Write to this file."),
350
+ ) -> None:
351
+ """Print a job's configuration as a create --config file."""
352
+ run = ctx.obj
353
+ client = run.client()
354
+ job = resolve.find_job(client, "evaluation", name)
355
+ detail = client.get(f"/evaluation/jobs/{job['id']}")
356
+ dto = EvaluationJobDTO.from_api(detail if isinstance(detail, dict) else job, detail=True)
357
+ _control.emit_clone(
358
+ run, _control.evaluation_config(dto, _control.clone_name(dto, new_name), client=client),
359
+ save=save, module="evaluation",
360
+ )
@@ -0,0 +1,138 @@
1
+ """随安装包分发的离线示例:查看指南并导出可编辑材料。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from importlib.resources import files
7
+ from pathlib import Path
8
+
9
+ import typer
10
+
11
+ from infix_cli import render
12
+ from infix_cli.errors import CliError, UsageError
13
+
14
+ app = typer.Typer(
15
+ help="Browse and export bundled examples, including Model Fusion and Merge. No login required.",
16
+ no_args_is_help=True,
17
+ )
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Example:
22
+ name: str
23
+ description: str
24
+ files: tuple[str, ...]
25
+
26
+ def to_json(self) -> dict:
27
+ return {"name": self.name, "description": self.description, "files": self.files}
28
+
29
+
30
+ EXAMPLES = {
31
+ "fusion": Example(
32
+ "fusion", "Two-Teacher Fusion: prompts, five stages, evaluation and registration.",
33
+ ("README.md", "fusion.json", "prompts/math.jsonl", "prompts/code.jsonl"),
34
+ ),
35
+ "merge": Example(
36
+ "merge", "CPU TIES Merge: base model, three experts, comparison and registration.",
37
+ ("README.md", "merge.json"),
38
+ ),
39
+ }
40
+
41
+
42
+ @app.callback()
43
+ def offline(ctx: typer.Context) -> None:
44
+ # 示例读取完全离线,不触发根命令的更新检查。
45
+ ctx.obj.no_update_check = True
46
+
47
+
48
+ def _example(name: str) -> Example:
49
+ if name not in EXAMPLES:
50
+ raise UsageError(
51
+ f"Unknown example '{name}'.", "Run 'infix examples list' to see available names.",
52
+ )
53
+ return EXAMPLES[name]
54
+
55
+
56
+ def _read(example: Example, filename: str) -> bytes:
57
+ # 只允许目录清单中的文件,不把用户传入的路径直接交给资源读取器。
58
+ if filename not in example.files:
59
+ raise UsageError(
60
+ f"Unknown file '{filename}' in example '{example.name}'.",
61
+ "Available files: " + ", ".join(example.files),
62
+ )
63
+ return files("infix_cli.example_data").joinpath(
64
+ example.name, *filename.split("/"),
65
+ ).read_bytes()
66
+
67
+
68
+ @app.command("list")
69
+ def list_examples(ctx: typer.Context) -> None:
70
+ """List examples shipped with this CLI version (offline)."""
71
+ render.render_list(
72
+ ctx.obj, tuple(EXAMPLES.values()), [("NAME", "name"), ("DESCRIPTION", "description")],
73
+ page=None, page_size=None, total=len(EXAMPLES),
74
+ footer="Read: infix examples show NAME Export: infix examples export NAME --dir PATH",
75
+ )
76
+
77
+
78
+ @app.command()
79
+ def show(
80
+ ctx: typer.Context,
81
+ name: str = typer.Argument(..., help="Example name from 'infix examples list'."),
82
+ filename: str = typer.Option(
83
+ "README.md", "--file", help="File within the example, e.g. fusion.json or prompts/math.jsonl.",
84
+ ),
85
+ ) -> None:
86
+ """Read a bundled guide or file. JSON output wraps the text in content.
87
+
88
+ Use --output text for the original file contents when redirecting stdout.
89
+ """
90
+ content = _read(_example(name), filename).decode("utf-8")
91
+ if ctx.obj.output == "json":
92
+ render.json_out.print_raw({"name": name, "file": filename, "content": content})
93
+ else:
94
+ typer.echo(content, nl=False)
95
+
96
+
97
+ @app.command("export")
98
+ def export_examples(
99
+ ctx: typer.Context,
100
+ name: str = typer.Argument(..., help="Example name from 'infix examples list'."),
101
+ directory: Path | None = typer.Option(
102
+ None, "--dir", help="New directory to create; default: ./infix-examples/NAME. Never overwrites.",
103
+ ),
104
+ ) -> None:
105
+ """Export the guide, configuration and sample data to an editable directory.
106
+
107
+ Replace REPLACE_WITH_* references and adjust resources before running the guide's commands.
108
+ Exporting creates local files only; it never submits a task.
109
+ """
110
+ example = _example(name)
111
+ destination = (directory or Path("infix-examples") / name).expanduser().absolute()
112
+ contents = {filename: _read(example, filename) for filename in example.files}
113
+ try:
114
+ destination.mkdir(parents=True, exist_ok=False)
115
+ except FileExistsError as exc:
116
+ raise UsageError(
117
+ f"Destination already exists: {destination}",
118
+ "Choose a new --dir; existing files are never overwritten.",
119
+ ) from exc
120
+ except OSError as exc:
121
+ raise CliError(f"Cannot create example directory: {exc}") from exc
122
+ try:
123
+ for filename, content in contents.items():
124
+ target = destination / filename
125
+ target.parent.mkdir(parents=True, exist_ok=True)
126
+ with target.open("xb") as stream:
127
+ stream.write(content)
128
+ except OSError as exc:
129
+ raise CliError(
130
+ f"Cannot export example: {exc}",
131
+ f"Export may be incomplete; inspect {destination} before retrying in a new directory.",
132
+ ) from exc
133
+ render.render_object(
134
+ ctx.obj, {"name": name, "directory": str(destination), "files": example.files},
135
+ [("Example", name), ("Directory", str(destination)),
136
+ ("Files", ", ".join(example.files)), ("Next", f"Read {destination / 'README.md'}")],
137
+ quiet_value=str(destination),
138
+ )