envloop-cli 1.30.0__tar.gz → 1.32.0__tar.gz

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 (67) hide show
  1. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/.gitignore +1 -0
  2. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/PKG-INFO +18 -4
  3. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/README.pypi.md +17 -3
  4. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/_optional.py +1 -1
  5. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/cli_errors.py +14 -1
  6. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/client.py +2 -2
  7. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/http.py +13 -6
  8. envloop_cli-1.32.0/envloop/lifecycle_cli.py +118 -0
  9. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/profile_secrets.py +13 -2
  10. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/resource_cli.py +20 -4
  11. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/cli.py +18 -3
  12. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/client.py +41 -8
  13. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/data.py +166 -27
  14. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/data_cli.py +108 -22
  15. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/data_publications.py +35 -0
  16. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/data_upload.py +15 -3
  17. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/http.py +16 -1
  18. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/profile_updates.py +2 -1
  19. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/recipes.py +4 -3
  20. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/resource_cli.py +5 -1
  21. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/cli.py +46 -8
  22. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/client.py +24 -2
  23. envloop_cli-1.32.0/packages/experiment/envloop_experiment/inference.py +79 -0
  24. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/job_spec_cli.py +5 -1
  25. envloop_cli-1.32.0/packages/experiment/envloop_experiment/named_profile.py +62 -0
  26. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/resource_cli.py +5 -1
  27. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/runtime_params.py +6 -3
  28. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/train.py +10 -4
  29. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/train_progress.py +17 -1
  30. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/pyproject.toml +2 -2
  31. envloop_cli-1.30.0/envloop/lifecycle_cli.py +0 -57
  32. envloop_cli-1.30.0/packages/experiment/envloop_experiment/inference.py +0 -36
  33. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/__init__.py +0 -0
  34. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/auth_cli.py +0 -0
  35. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/auth_login.py +0 -0
  36. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/auth_workspace.py +0 -0
  37. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/cli.py +0 -0
  38. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/cli_output.py +0 -0
  39. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/config.py +0 -0
  40. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/downloads.py +0 -0
  41. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/navigation_resources.py +0 -0
  42. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/resources.py +0 -0
  43. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/terminal.py +0 -0
  44. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/utils/__init__.py +0 -0
  45. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/envloop/utils/logging.py +0 -0
  46. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/__init__.py +0 -0
  47. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/cli_output.py +0 -0
  48. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/navigation_resources.py +0 -0
  49. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/data/envloop_data/runner_packages.py +0 -0
  50. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/__init__.py +0 -0
  51. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/cli_output.py +0 -0
  52. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/decision.py +0 -0
  53. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/http.py +0 -0
  54. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/job_cost.py +0 -0
  55. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/job_logs.py +0 -0
  56. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/navigation_resources.py +0 -0
  57. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/resources.py +0 -0
  58. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/sandbox.py +0 -0
  59. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/train_log_cli.py +0 -0
  60. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/train_metrics_cli.py +0 -0
  61. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/train_runner_cli.py +0 -0
  62. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/experiment/envloop_experiment/training/__init__.py +0 -0
  63. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/rsi-loop/envloop_rsi_loop/__init__.py +0 -0
  64. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/rsi-loop/envloop_rsi_loop/agent_runs.py +0 -0
  65. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/rsi-loop/envloop_rsi_loop/cli.py +0 -0
  66. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/rsi-loop/envloop_rsi_loop/cli_output.py +0 -0
  67. {envloop_cli-1.30.0 → envloop_cli-1.32.0}/packages/rsi-loop/envloop_rsi_loop/rsi_cli.py +0 -0
@@ -14,3 +14,4 @@ dist/
14
14
  # Isolated build and integration-test fixtures
15
15
  .ci-deps/
16
16
  .local-runs/
17
+ .ea/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: envloop-cli
3
- Version: 1.30.0
3
+ Version: 1.32.0
4
4
  Summary: EnvLoop CLI and Python SDK for jobs, training, checkpoints and inference
5
5
  Project-URL: Homepage, https://envloop.ai
6
6
  Project-URL: Documentation, https://docs.envloop.ai
@@ -160,6 +160,20 @@ cleaning up temporary resources.
160
160
 
161
161
  ## Sandbox jobs
162
162
 
163
+ After `el auth login`, you may reuse an existing EnvPlatform Profile as an
164
+ optional preset. It uses the current login and project permissions. Submit its
165
+ published name and optional ANS input bindings or declared parameters:
166
+
167
+ ```bash
168
+ el job submit --type sandbox --profile team/report@1 --input report=ARTIFACT_URI --params Mode=Summary --max-cost-usd 3
169
+ ```
170
+
171
+ The platform resolves and freezes the Runner and inputs, and manages any model
172
+ service declared by the Profile. No local script, Dataset Task wrapper or Runner
173
+ argument is required. Use a published Artifact URI in place of `ARTIFACT_URI`.
174
+ `--profile` and `--spec` are mutually exclusive. Named Profile parameter names
175
+ retain their case and duplicates are rejected.
176
+
163
177
  With a matching platform and a published `envloop/base` ANS Runner, submit a
164
178
  Sandbox Job without a Dataset:
165
179
 
@@ -277,9 +291,9 @@ Availability requires matching platform support and approved content in your pro
277
291
 
278
292
  ## ANS data and verified downloads
279
293
 
280
- `client.data.download_directory(uri, destination)` and `el data download URI --output ./content`
294
+ `client.data.download_directory(uri, destination)` and `el data download DATA_ID|URI --output ./content`
281
295
  download a complete registered ANS object directory through EnvHub. Datasets require
282
- `split="lite"` / `--split lite`; the Dataset version and filenames are preserved. After API
296
+ `split="lite"` / `--split lite` (the error lists the declared splits); the Dataset version and filenames are preserved. After API
283
297
  authorization the SDK uses GET URLs valid for up to five minutes, verifies file size/SHA-256,
284
298
  and installs the directory atomically. Matching platform support is required.
285
299
 
@@ -291,7 +305,7 @@ el data get DATA_ID --json
291
305
  el data download DATA_ID --file FILE_ID --output ./dataset.tgz --resume --json
292
306
  ```
293
307
 
294
- Unified ANS CRUD supports Dataset, Runner, Recipe and HF model Checkpoint registrations through `el data` and `client.data`. Dataset/Runner/Recipe creation requires a native immutable `--ref`, `--manifest` and exact `--directory`. HF metadata registration uses `el data create --type checkpoint --model namespace/model --revision FULL_COMMIT`; SDK uses `create(kind="checkpoint", model=..., revision=...)`. HF weights are not downloaded, and artifact imports do not establish Model or Job checkpoint provenance.
308
+ Unified ANS CRUD supports Dataset, Runner, Recipe and HF model Checkpoint registrations through `el data` and `client.data`. Dataset/Runner/Recipe creation requires a native `--manifest` and exact `--directory`. For Dataset create/update/upload, `--ref` (SDK `ref`) is optional when `dataset.namespace`, `dataset.name` and `dataset.version` are present in the manifest; EnvHub derives the immutable Dataset URI. Other resource types and manifests without that identity still require an explicit ref. Explicit refs remain supported; the platform validates their consistency with the manifest. HF metadata registration uses `el data create --type checkpoint --model namespace/model --revision FULL_COMMIT`; SDK uses `create(kind="checkpoint", model=..., revision=...)`. HF weights are not downloaded, and artifact imports do not establish Model or Job checkpoint provenance. While native publication runs, `create`/`update` repeat the same idempotent request until ready (`--timeout`, default 3600 s); `--no-wait` / `wait=False` returns the pending `publishing` resource with resume instructions.
295
309
 
296
310
  `el runner register DIRECTORY --revision FULL_COMMIT [--source-ref main]` publishes a Runner package directory through the same Data API with the manifest built for you, then reads the catalog revision back. `el profile create|update|fork ... --secret NAME[=prompt|stdin|env:VAR|file:PATH]` stores write-only Secret parameters whose names follow the platform's credential rule or `secret_params`; values never come from the command line. `el setting model-access grant NAMESPACE/NAME --protocol anthropic [--revision FULL_COMMIT]` (project Admin) lets a published Runner receive the project's metered model key on Fly Trials; `list` and `revoke GRANT_ID` manage grants.
297
311
 
@@ -143,6 +143,20 @@ cleaning up temporary resources.
143
143
 
144
144
  ## Sandbox jobs
145
145
 
146
+ After `el auth login`, you may reuse an existing EnvPlatform Profile as an
147
+ optional preset. It uses the current login and project permissions. Submit its
148
+ published name and optional ANS input bindings or declared parameters:
149
+
150
+ ```bash
151
+ el job submit --type sandbox --profile team/report@1 --input report=ARTIFACT_URI --params Mode=Summary --max-cost-usd 3
152
+ ```
153
+
154
+ The platform resolves and freezes the Runner and inputs, and manages any model
155
+ service declared by the Profile. No local script, Dataset Task wrapper or Runner
156
+ argument is required. Use a published Artifact URI in place of `ARTIFACT_URI`.
157
+ `--profile` and `--spec` are mutually exclusive. Named Profile parameter names
158
+ retain their case and duplicates are rejected.
159
+
146
160
  With a matching platform and a published `envloop/base` ANS Runner, submit a
147
161
  Sandbox Job without a Dataset:
148
162
 
@@ -260,9 +274,9 @@ Availability requires matching platform support and approved content in your pro
260
274
 
261
275
  ## ANS data and verified downloads
262
276
 
263
- `client.data.download_directory(uri, destination)` and `el data download URI --output ./content`
277
+ `client.data.download_directory(uri, destination)` and `el data download DATA_ID|URI --output ./content`
264
278
  download a complete registered ANS object directory through EnvHub. Datasets require
265
- `split="lite"` / `--split lite`; the Dataset version and filenames are preserved. After API
279
+ `split="lite"` / `--split lite` (the error lists the declared splits); the Dataset version and filenames are preserved. After API
266
280
  authorization the SDK uses GET URLs valid for up to five minutes, verifies file size/SHA-256,
267
281
  and installs the directory atomically. Matching platform support is required.
268
282
 
@@ -274,7 +288,7 @@ el data get DATA_ID --json
274
288
  el data download DATA_ID --file FILE_ID --output ./dataset.tgz --resume --json
275
289
  ```
276
290
 
277
- Unified ANS CRUD supports Dataset, Runner, Recipe and HF model Checkpoint registrations through `el data` and `client.data`. Dataset/Runner/Recipe creation requires a native immutable `--ref`, `--manifest` and exact `--directory`. HF metadata registration uses `el data create --type checkpoint --model namespace/model --revision FULL_COMMIT`; SDK uses `create(kind="checkpoint", model=..., revision=...)`. HF weights are not downloaded, and artifact imports do not establish Model or Job checkpoint provenance.
291
+ Unified ANS CRUD supports Dataset, Runner, Recipe and HF model Checkpoint registrations through `el data` and `client.data`. Dataset/Runner/Recipe creation requires a native `--manifest` and exact `--directory`. For Dataset create/update/upload, `--ref` (SDK `ref`) is optional when `dataset.namespace`, `dataset.name` and `dataset.version` are present in the manifest; EnvHub derives the immutable Dataset URI. Other resource types and manifests without that identity still require an explicit ref. Explicit refs remain supported; the platform validates their consistency with the manifest. HF metadata registration uses `el data create --type checkpoint --model namespace/model --revision FULL_COMMIT`; SDK uses `create(kind="checkpoint", model=..., revision=...)`. HF weights are not downloaded, and artifact imports do not establish Model or Job checkpoint provenance. While native publication runs, `create`/`update` repeat the same idempotent request until ready (`--timeout`, default 3600 s); `--no-wait` / `wait=False` returns the pending `publishing` resource with resume instructions.
278
292
 
279
293
  `el runner register DIRECTORY --revision FULL_COMMIT [--source-ref main]` publishes a Runner package directory through the same Data API with the manifest built for you, then reads the catalog revision back. `el profile create|update|fork ... --secret NAME[=prompt|stdin|env:VAR|file:PATH]` stores write-only Secret parameters whose names follow the platform's credential rule or `secret_params`; values never come from the command line. `el setting model-access grant NAMESPACE/NAME --protocol anthropic [--revision FULL_COMMIT]` (project Admin) lets a published Runner receive the project's metered model key on Fly Trials; `list` and `revoke GRANT_ID` manage grants.
280
294
 
@@ -38,7 +38,7 @@ CLIENTS = {
38
38
  **{name: ('experiment', 'client') for name in ('TrialService', 'RpcService', 'load_task', 'validate_command', 'dataset_selector', 'Trials', 'runner_selector', 'job_budget', 'Jobs')},
39
39
  **{name: ('base', 'downloads') for name in ('ArtifactError', 'artifact_path')},
40
40
  }
41
- DATA_ENDPOINTS = set('open_download resolve_dataset list_runners get_runner_revision register_runner_revision runner_path profile_path put_profile list_profiles get_profile resolve_profile set_default_profile archive_profile revoke_profile_secret export_profile import_profile open_checkpoint_archive'.split())
41
+ DATA_ENDPOINTS = set('open_download resolve_dataset list_runners get_runner_revision register_runner_revision runner_path profile_path put_profile list_profiles get_profile resolve_profile set_default_profile archive_profile set_profile_visibility fork_profile revoke_profile_secret export_profile import_profile open_checkpoint_archive'.split())
42
42
  EXPERIMENT_ENDPOINTS = set('submit_job get_job get_job_result get_job_logs list_jobs job_action job_events stop_job list_trials get_task_run get_trial_detail get_trial_training list_trial_metrics list_trial_checkpoints get_task_result get_task_snapshot stop_task list_trial_artifacts open_trial_artifact'.split())
43
43
 
44
44
 
@@ -47,6 +47,7 @@ _register("CONFLICT VERSION_CONFLICT RESOURCE_VERSION_CONFLICT PRECONDITION_FAIL
47
47
  _register("BAD_REQUEST VALIDATION_ERROR VALIDATION_FAILED INVALID_REQUEST INVALID_ARGUMENT INVALID_CURSOR INVALID_PROFILE INVALID_PROFILE_SECRETS", "The request or input is invalid.")
48
48
  _register("PROFILE_SECRET_NAME_INVALID", "A Secret parameter name must look like a credential, as the platform decides: it ends with API_KEY or _TOKEN, or contains PASSWORD, SECRET, CREDENTIAL, AUTHORIZATION, ACCESS_TOKEN, AUTH_TOKEN, BEARER_TOKEN or PRIVATE_KEY. Otherwise list the name in the Profile's secret_params. Names use letters, digits and underscores.")
49
49
  _register("PROFILE_SECRET_VALUE_INVALID", "A Secret parameter value is missing or unusable: it must be non-empty UTF-8 text of at most 64 KiB from a prompt, stdin, an environment variable or a file.")
50
+ _register("PROFILE_MODEL_KEY_UNSUPPORTED", "--model-api-key-stdin and --prompt-model-api-key only set the encrypted key of a managed model connection (params.model_connection). Store other keys as a Secret parameter, for example --secret MODEL_API_KEY=stdin.")
50
51
  _register("PROFILE_SECRET_CONFLICT", "Give each Secret parameter once, by --secret only (not also in the Profile file or patch), and read at most one value from stdin.")
51
52
  _register("RUNNER_PACKAGE_INVALID", "The Runner package directory is invalid. It needs runner.toml whose [runner] name matches the Runner and has no version, the [execution] entrypoint main.py or main.sh, at most 100 regular files, no symlinks, and path parts of letters, digits, '_', '.' or '-' that do not start with '.'.")
52
53
  _register("RUNNER_REVISION_INVALID", "Use the full lowercase 40- or 64-character source commit as --revision and a NAMESPACE/NAME Runner name.")
@@ -105,6 +106,11 @@ _register("INVALID_PROFILE_RUNNER", "The Profile Runner binding is invalid.")
105
106
  _register("PROFILE_RUNNER_CONFLICT", "The explicit Runner conflicts with the Profile binding.")
106
107
  _register("PROFILE_RUNNER_UNSUPPORTED", "This submission path cannot execute the Profile-bound Runner.")
107
108
  _register("PROFILE_ARCHIVED PROFILE_HASH_MISMATCH", "The selected Profile is archived or does not match its frozen version.")
109
+ _register("NAMED_PROFILE_INVALID PROFILE_INPUT_INVALID PROFILE_CHECKPOINT_MODEL_MISMATCH", "The named Profile or input binding is incompatible. Use its declared input slots and allowed parameter replacements.")
110
+ _register("PROFILE_AUTHORIZATION_UNAVAILABLE", "Current Profile authorization could not be verified. Retry the same request after authorization is available.")
111
+ _register("VISIBILITY_CONFLICT", "Visibility changed since it was read. Read the resource and use its current visibility and ACL revision before retrying.")
112
+ _register("VISIBILITY_INVALID", "Choose private or public visibility for a supported resource.")
113
+ _register("PUBLIC_DEPENDENCY_UNAVAILABLE PUBLIC_CONTENT_UNSAFE PUBLICATION_REVIEW_REQUIRED", "Public sharing requires reviewed content and currently readable public dependencies. Private dependencies are never published automatically.")
108
114
  _register("CHECKPOINT_AMBIGUOUS", "More than one checkpoint matches this selection.")
109
115
  _register("CHECKPOINT_FILES_UNAVAILABLE ARTIFACT_NOT_READY", "The requested download is not available yet.")
110
116
  _register("CHECKPOINT_FILES_INVALID ARTIFACT_LISTING_INVALID ARTIFACT_NAME_UNSAFE UNSAFE_ARTIFACT_REDIRECT ARTIFACT_SIZE_MISMATCH ARTIFACT_HASH_MISMATCH", "The download failed a safety or integrity check.")
@@ -305,6 +311,9 @@ def format_error(error: BaseException) -> str:
305
311
  code = remote.code
306
312
  local = _http_message(status) if code == "HTTP_ERROR" or code not in _MESSAGES else _MESSAGES[code]
307
313
  extra: dict[str, Any] = {"hint": remote.hint, "details": remote.details, "request_id": remote.request_id} if remote else {}
314
+ if remote and remote.message and remote.details:
315
+ # A detail that repeats the message (one refused field) only adds where it is: show the field alone.
316
+ extra["details"] = [line.removesuffix(": " + remote.message) for line in remote.details if line != remote.message]
308
317
  if remote and remote.message:
309
318
  # Local text only adds guidance for codes the CLI documents.
310
319
  # A gateway timeout always adds that the request may have been processed.
@@ -320,14 +329,18 @@ def format_error(error: BaseException) -> str:
320
329
  def upload_recovery(error: BaseException) -> str:
321
330
  """Display only server upload IDs and keys generated locally for recovery."""
322
331
  lines = []
332
+ running = isinstance(error, TimeoutError)
323
333
  staging_id = getattr(error,'staging_id',None)
324
334
  if isinstance(staging_id,str) and re.fullmatch(r'pub_[a-f0-9]{64}',staging_id):
325
- lines.append(f' Staging retained: {staging_id}. Retry the same create or update input.')
335
+ lines.append(f' Native publication {staging_id} is still running on the platform. Re-run the same create or update '
336
+ 'input to keep waiting.' if running else f' Staging retained: {staging_id}. Retry the same create or update input.')
326
337
  if getattr(error,'retirement_pending',False) is True:
327
338
  lines.append(' Retirement is pending; retry deletion of the same resource to complete it.')
328
339
  upload_id = getattr(error, 'upload_id', None)
329
340
  if isinstance(upload_id, str) and re.fullmatch(r'upload_[a-f0-9]{32}', upload_id):
330
341
  lines.extend([f' Upload retained: {upload_id}', f' Inspect with: el data upload get {upload_id}'])
342
+ if running:
343
+ lines.append(f' Poll publication with: el data upload complete {upload_id}')
331
344
  generated = getattr(error, 'generated_idempotency_key', None)
332
345
  # A definite refusal (permission, validation, not found) fails the same way again; offer the key only
333
346
  # when the outcome is unknown or retryable.
@@ -33,10 +33,10 @@ class Client:
33
33
  raise RuntimeError(INTERACTIVE_TRAINING_REMOVED)
34
34
 
35
35
  @classmethod
36
- def remote(cls, api_url: str | None = None, *, timeout: float = 90, api_key: str | None = None, workspace_id: str | None = None, project_id: str | None = None, config: bool = True):
36
+ def remote(cls, api_url: str | None = None, *, timeout: float = 120, api_key: str | None = None, workspace_id: str | None = None, project_id: str | None = None, config: bool = True):
37
37
  from .http import HttpService
38
38
 
39
- # The default matches http.DEFAULT_TIMEOUT_SEC (longer than the hosted proxy's 60 s wait).
39
+ # The default matches http.DEFAULT_TIMEOUT_SEC (well beyond the hosted proxy's bounded long-polls).
40
40
  return cls(HttpService(api_url, timeout, api_key=api_key, workspace_id=workspace_id, project_id=project_id, config=config))
41
41
 
42
42
  @classmethod
@@ -71,9 +71,10 @@ def retry_after_seconds(value: str | None) -> float | None:
71
71
  return None
72
72
 
73
73
 
74
- # The hosted API proxy waits up to 60 s for the platform. Wait longer by default so a slow answer, or the
74
+ # The hosted API proxy bounds its slow platform hops (a native Data publication answers 202 and is polled by
75
+ # repeating the request) and long-polls about 20 s. Wait well beyond that by default so a slow answer, or the
75
76
  # proxy's own gateway timeout, reaches the caller instead of a client-side timeout. Explicit values are kept.
76
- DEFAULT_TIMEOUT_SEC = 90.0
77
+ DEFAULT_TIMEOUT_SEC = 120.0
77
78
  # The proxy or edge stopped waiting while the platform was still working: the request may have been processed.
78
79
  GATEWAY_TIMEOUT_STATUSES = frozenset({504, 524})
79
80
 
@@ -127,6 +128,9 @@ def _text(value: Any, limit: int, secrets: tuple[str | None, ...] = ()) -> str |
127
128
  return (value[:limit - 1] + "\u2026" if len(value) > limit else value) or None
128
129
 
129
130
 
131
+ _DETAIL_TEXT = frozenset({"field", "loc", "name", "message", "msg", "error"})
132
+
133
+
130
134
  def _detail_lines(value: Any, secrets: tuple[str | None, ...]) -> list[str]:
131
135
  """Field-level validation detail from `fields`/`details`, as at most 10 short lines."""
132
136
  if isinstance(value, dict):
@@ -137,10 +141,13 @@ def _detail_lines(value: Any, secrets: tuple[str | None, ...]) -> list[str]:
137
141
  field = item.get("field") or item.get("loc") or item.get("name")
138
142
  field = ".".join(map(str, field)) if isinstance(field, list) else field
139
143
  message = item.get("message") or item.get("msg") or item.get("error")
140
- # A flat record such as {task, size_bytes, limit_bytes} reads as key=value pairs.
141
- item = f"{field}: {message}" if field and message else message or field or ", ".join(
142
- f"{key}={value}" for key, value in list(item.items())[:16]
143
- if isinstance(key, str) and isinstance(value, (str, int, float)) and not isinstance(value, bool))
144
+ # A flat record such as {task, size_bytes, limit_bytes} reads as key=value pairs; next to a field the
145
+ # same pairs locate it, e.g. `records (record_index=2): ...`.
146
+ pairs = ", ".join(f"{key}={value}" for key, value in list(item.items())[:16]
147
+ if isinstance(key, str) and key not in _DETAIL_TEXT
148
+ and isinstance(value, (str, int, float)) and not isinstance(value, bool))
149
+ located = f"{field} ({pairs})" if field and pairs else field
150
+ item = f"{located}: {message}" if field and message else message or located or pairs
144
151
  if line := _text(item, 200, secrets):
145
152
  lines.append(line)
146
153
  return lines
@@ -0,0 +1,118 @@
1
+ """Project lifecycle commands nested under Console Settings."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ TIMEOUT_HELP = ('Seconds to wait (default 600); on timeout the command exits 1 with WAIT_TIMEOUT and prints the '
9
+ 'Operation, and cleanup continues on the server')
10
+ OPERATION_READ = ('Reading an Operation needs the Key permission Resource cleanup, under MANAGE (resources.read); without '
11
+ 'it the read returns ACCESS_DENIED (HTTP 403).')
12
+ OPERATION = ('An Operation is the persisted record of one cleanup request. el setting cleanup, el setting '
13
+ 'resource-scope cleanup, el job adapter delete and el checkpoint delete return one (operation_id), and '
14
+ 'a stopped Inference Job names its own in inference.cleanup_operation_id. Status is PENDING or RUNNING '
15
+ 'while cleanup works, RETRYING after a failure the server retries by itself, and SUCCEEDED when every '
16
+ 'resource is released; resources_deleted, retained and errors give the outcome per resource. '
17
+ 'FAILED, BLOCKED, RETRYABLE_FAILED, CANCELLED or SUCCEEDED with errors mean cleanup is incomplete: '
18
+ 'fix the named cause and run el setting operation retry OPERATION_ID. ' + OPERATION_READ)
19
+ DENIED_HINT = ('This Key cannot read cleanup Operations: it needs the Resource cleanup permission, under MANAGE '
20
+ '(resources.read). Without it, check the resource itself: el job get JOB_ID shows cleanup_confirmed, '
21
+ 'and el job adapter get ID returns 404 once the Adapter is deleted.')
22
+
23
+
24
+ def wait_options(parser: argparse.ArgumentParser):
25
+ parser.add_argument('--wait', action='store_true',
26
+ help='Then wait for the cleanup Operation to finish (see el setting operation wait --help). If '
27
+ 'this Key cannot read Operations, print the Operation and exit 0, since the request '
28
+ 'itself succeeded')
29
+ parser.add_argument('--timeout-seconds', type=float, default=600, help=TIMEOUT_HELP)
30
+
31
+
32
+ def wait_after_request(client: Any, result: Any, *, timeout: float, check: str) -> Any:
33
+ """``--wait`` after an accepted cleanup request (delete, cleanup, scope cleanup).
34
+
35
+ The request already succeeded. A Key may delete without being allowed to read Operations; a
36
+ denied read then reports the Operation and how to confirm the outcome instead of failing.
37
+ """
38
+ if not isinstance(result, dict) or result.get('status') == 'SUCCEEDED' and not result.get('errors'):
39
+ return result
40
+ from .http import RemoteError
41
+
42
+ try:
43
+ return client.operations.wait(result['operation_id'], timeout=timeout)
44
+ except RemoteError as error:
45
+ if error.status_code != 403:
46
+ raise
47
+ print(f"Cleanup accepted as Operation {result['operation_id']}, but this Key cannot read cleanup Operations "
48
+ f"(resources.read), so --wait stopped. {check}", file=sys.stderr)
49
+ return result
50
+
51
+
52
+ def add_management_commands(settings: "argparse._SubParsersAction[argparse.ArgumentParser]"):
53
+ operations = settings.add_parser('operation', help='Inspect, wait for or retry a cleanup Operation',
54
+ description=OPERATION).add_subparsers(dest='operation_action', required=True)
55
+ get = operations.add_parser('get', help='Show a cleanup Operation once', description='Show the current state of a '
56
+ 'cleanup Operation without waiting. ' + OPERATION)
57
+ retry = operations.add_parser('retry', help='Retry an incomplete cleanup Operation', description=(
58
+ 'Start the remaining work of an incomplete cleanup Operation again; needs Resource cleanup edit '
59
+ 'permission, under MANAGE (resources.cleanup). ' + OPERATION))
60
+ wait = operations.add_parser('wait', help='Poll a cleanup Operation until it finishes', description=(
61
+ 'Read the Operation every 2 seconds until it finishes, then print it. Exit 0 when it is SUCCEEDED without '
62
+ 'errors, exit 1 with CLEANUP_INCOMPLETE when cleanup is incomplete, and exit 1 with WAIT_TIMEOUT after '
63
+ '--timeout-seconds (default 600) while cleanup continues on the server; run wait again later. ' + OPERATION))
64
+ for command in (get, retry, wait):
65
+ command.add_argument('identifier', metavar='OPERATION_ID', help='Operation ID (op_...)')
66
+ wait.add_argument('--timeout-seconds', type=float, default=600, help=TIMEOUT_HELP)
67
+ cleanup = settings.add_parser('cleanup', help='Clean an explicit set of Project resource IDs')
68
+ cleanup.add_argument('--file', type=Path, required=True,
69
+ help='JSON array of {"kind": KIND, "id": ID} objects; KIND is job (a Train Job), endpoint, adapter '
70
+ 'or checkpoint, for example [{"kind": "job", "id": "job_..."}]')
71
+ cleanup.add_argument('--request-id', required=True)
72
+ wait_options(cleanup)
73
+ scopes = settings.add_parser('resource-scope', help='Manage temporary resources with server TTL').add_subparsers(dest='scope_action', required=True)
74
+ create = scopes.add_parser('create')
75
+ create.add_argument('--ttl-seconds', type=int, default=1800)
76
+ create.add_argument('--request-id', required=True)
77
+ for action in ('get', 'cleanup', 'retain'):
78
+ command = scopes.add_parser(action)
79
+ command.add_argument('identifier', metavar='RESOURCE_SCOPE_ID')
80
+ if action == 'cleanup':
81
+ wait_options(command)
82
+ if action == 'retain':
83
+ command.add_argument('--file', type=Path, required=True, help='JSON array of resources to retain')
84
+
85
+
86
+ def run_management(client: Any, args: argparse.Namespace):
87
+ from .resources import _id
88
+
89
+ if args.action == 'operation':
90
+ from .http import RemoteError
91
+
92
+ try:
93
+ return (client.operations.wait(args.identifier, timeout=args.timeout_seconds) if args.operation_action == 'wait'
94
+ else getattr(client.operations, args.operation_action)(args.identifier))
95
+ except RemoteError as error:
96
+ if error.status_code == 403 and args.operation_action != 'retry' and not error.hint:
97
+ error.hint = DENIED_HINT
98
+ raise
99
+ if args.action == 'resource-scope':
100
+ if args.scope_action == 'create':
101
+ client.temporary_resources(ttl_seconds=args.ttl_seconds)
102
+ base = client.operations.project_path + '/temporary-resource-scopes'
103
+ if args.scope_action == 'create':
104
+ result = client._transport.request('POST', base, {'ttl_seconds': args.ttl_seconds, 'request_id': args.request_id})
105
+ else:
106
+ path = base + '/' + _id(args.identifier)
107
+ result = (client._transport.request('POST', path + '/retain', {'resources': json.loads(args.file.read_text())})
108
+ if args.scope_action == 'retain' else client._transport.request('DELETE' if args.scope_action == 'cleanup' else 'GET', path))
109
+ if args.scope_action != 'cleanup':
110
+ return result
111
+ check = f'Check with: el setting resource-scope get {args.identifier} (status CLEANED).'
112
+ else:
113
+ result = client.operations.cleanup(json.loads(args.file.read_text()), request_id=args.request_id)
114
+ check = ('Check each resource: el job get JOB_ID (training.cleanup_confirmed true), el job adapter get ID '
115
+ '(404 = deleted), el checkpoint list (deleted Checkpoints are gone).')
116
+ if not getattr(args, 'wait', False):
117
+ return result
118
+ return wait_after_request(client, result, timeout=args.timeout_seconds, check=check)
@@ -32,8 +32,13 @@ def profile_payload(spec: Mapping[str, Any], secrets: Mapping[str, Any] | None =
32
32
  raise InvalidProfileSecrets()
33
33
  result = dict(spec)
34
34
  if secrets is not None:
35
- if (not isinstance(secrets, Mapping) or set(secrets) != {"model_api_key"}
36
- or not isinstance(secrets["model_api_key"], str)
35
+ if not isinstance(secrets, Mapping) or set(secrets) != {"model_api_key"}:
36
+ raise InvalidProfileSecrets()
37
+ if not _managed_model_connection(spec):
38
+ # The platform encrypts this key only for a managed params.model_connection and otherwise answers a bare
39
+ # INVALID_PROFILE. Other credentials are Secret parameters (`--secret MODEL_API_KEY=stdin`).
40
+ raise InvalidProfileSecrets("PROFILE_MODEL_KEY_UNSUPPORTED")
41
+ if (not isinstance(secrets["model_api_key"], str)
37
42
  or not secrets["model_api_key"].strip()
38
43
  or secrets["model_api_key"] != secrets["model_api_key"].strip()
39
44
  or secrets["model_api_key"] == "••••••••"
@@ -44,6 +49,12 @@ def profile_payload(spec: Mapping[str, Any], secrets: Mapping[str, Any] | None =
44
49
  return result
45
50
 
46
51
 
52
+ def _managed_model_connection(spec: Mapping[str, Any]) -> bool:
53
+ """Mirrors EnvPlatform profilePolicyView: v1 params or v2 spec.params; v3 Profiles have no model connection."""
54
+ params = _params(spec) if spec.get("schema_version") != "envloop.profile/v3" else None
55
+ return isinstance(params, Mapping) and isinstance(params.get("model_connection"), Mapping)
56
+
57
+
47
58
  def _params(spec: Mapping[str, Any]) -> Any:
48
59
  return spec.get("spec", {}).get("params") if spec.get("schema_version") == PROFILE_V2 else spec.get("params")
49
60
 
@@ -1,10 +1,22 @@
1
1
  import argparse
2
2
  import sys
3
3
  from collections.abc import Sequence
4
+ from datetime import datetime, timedelta, timezone
4
5
  from typing import Any
5
6
 
6
7
  from .navigation_resources import billing_timestamp
7
8
 
9
+ USAGE_HELP = ('List recorded usage in a time window; without --start and --end, the last 7 days ending now (UTC). '
10
+ 'Example: el billing usage list --start 2026-11-01 --end 2026-11-05 --group-by day')
11
+ USAGE_DAYS = 7
12
+
13
+
14
+ def usage_window(start: str | None, end: str | None) -> tuple[str, str]:
15
+ """An omitted end is now (UTC, whole seconds); an omitted start is USAGE_DAYS before the end."""
16
+ end_at = datetime.fromisoformat(end) if end else datetime.now(timezone.utc).replace(microsecond=0)
17
+ start_at = datetime.fromisoformat(start) if start else end_at - timedelta(days=USAGE_DAYS)
18
+ return start_at.isoformat(), end_at.isoformat()
19
+
8
20
 
9
21
  def listing(commands: "argparse._SubParsersAction[argparse.ArgumentParser]", *, name: str = 'list', paged: bool = True, help: str = 'List visible resources') -> argparse.ArgumentParser:
10
22
  parser = commands.add_parser(name, help=help)
@@ -23,10 +35,13 @@ def add_resource_commands(groups: "argparse._SubParsersAction[argparse.ArgumentP
23
35
  billing = groups.add_parser('billing', help='Inspect Project billing and recorded usage').add_subparsers(dest='resource', required=True)
24
36
  for resource in ('account', 'usage', 'ledger', 'price'):
25
37
  commands = billing.add_parser(resource, help=f'Inspect billing {resource}').add_subparsers(dest='action', required=True)
26
- command = commands.add_parser('get', help='Show the billing account') if resource == 'account' else listing(commands, paged=False)
38
+ command = (commands.add_parser('get', help='Show the billing account') if resource == 'account'
39
+ else listing(commands, paged=False, help=USAGE_HELP) if resource == 'usage' else listing(commands, paged=False))
27
40
  if resource == 'usage':
28
- command.add_argument('--start', required=True, type=billing_timestamp, help='Start: YYYY-MM-DD (UTC) or ISO timestamp with timezone')
29
- command.add_argument('--end', required=True, type=billing_timestamp, help='Exclusive end: YYYY-MM-DD (UTC) or ISO timestamp with timezone')
41
+ command.add_argument('--start', type=billing_timestamp,
42
+ help='Start: YYYY-MM-DD (UTC) or ISO timestamp with timezone (default: 7 days before the end)')
43
+ command.add_argument('--end', type=billing_timestamp,
44
+ help='Exclusive end: YYYY-MM-DD (UTC) or ISO timestamp with timezone (default: now, UTC)')
30
45
  command.add_argument('--group-by', choices=['day', 'product', 'endpoint', 'sku'])
31
46
  if resource == 'ledger':
32
47
  command.add_argument('--limit', type=int, default=25)
@@ -194,7 +209,8 @@ def execute(args: argparse.Namespace, client: Any) -> Any:
194
209
  return client.dashboard.get()
195
210
  if group == 'billing':
196
211
  if args.resource == 'usage':
197
- return client.billing.usage(start=args.start, end=args.end, group_by=args.group_by)
212
+ start, end = usage_window(args.start, args.end)
213
+ return client.billing.usage(start=start, end=end, group_by=args.group_by)
198
214
  if args.resource == 'ledger':
199
215
  return client.billing.ledger(limit=args.limit)
200
216
  return getattr(client.billing, {'account': 'account', 'price': 'prices'}[args.resource])()
@@ -105,6 +105,15 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]")
105
105
  fork.add_argument('name', metavar='NAME')
106
106
  fork.add_argument('version', metavar='VERSION')
107
107
  secret_option(fork)
108
+ for item in (put, update, fork):
109
+ item.add_argument('--visibility', choices=('private', 'public'),
110
+ help='Visibility metadata; fork defaults to private. Public requires reviewed public dependencies')
111
+ visibility = profiles.add_parser('set-visibility', help='Change visibility with an ACL revision check')
112
+ visibility.add_argument('name', metavar='NAME')
113
+ visibility.add_argument('version', metavar='VERSION')
114
+ visibility.add_argument('--visibility', choices=('private', 'public'), required=True)
115
+ visibility.add_argument('--expected-visibility', choices=('private', 'public'), required=True)
116
+ visibility.add_argument('--expected-acl-revision', type=int, required=True)
108
117
  get = profiles.add_parser("get")
109
118
  get.add_argument("name", metavar="NAME")
110
119
  get.add_argument("--version")
@@ -113,6 +122,7 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]")
113
122
  listing.add_argument("--include-archived", action="store_true")
114
123
  listing.add_argument("--limit", type=int, default=50)
115
124
  listing.add_argument("--cursor")
125
+ listing.add_argument('--visibility', choices=('all','private','public'))
116
126
  listing.add_argument("--json", action="store_true", help="Output the complete response as JSON (default: table)")
117
127
  default = profiles.add_parser("set-default")
118
128
  default.add_argument("name", metavar="NAME")
@@ -127,6 +137,7 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]")
127
137
 
128
138
  def execute_profile(args: argparse.Namespace, client: Any, cli: Any) -> Any:
129
139
  from envloop._optional import CommandExit
140
+ visibility_options: dict[str, Any] = {} if getattr(args, 'visibility', None) is None else {'visibility': args.visibility}
130
141
  if args.action in {"create", "update"}:
131
142
  from envloop_data.profile_updates import read_profile_patch, with_runner
132
143
 
@@ -143,14 +154,17 @@ def execute_profile(args: argparse.Namespace, client: Any, cli: Any) -> Any:
143
154
  secrets = {"model_api_key": sys.stdin.readline(4098).rstrip("\r\n")}
144
155
  if args.action == "update":
145
156
  result = client.profiles.update(args.name, args.version,
146
- patch=patch, from_version=args.from_version, secrets=secrets, secret_values=values)
157
+ patch=patch, from_version=args.from_version, secrets=secrets, secret_values=values, **visibility_options)
147
158
  else:
148
159
  result = client.profiles.import_spec(
149
- raw, name=args.name, version=args.version, secrets=secrets, runner=args.runner, secret_values=values
160
+ raw, name=args.name, version=args.version, secrets=secrets, runner=args.runner, secret_values=values, **visibility_options
150
161
  )
151
162
  elif args.action == 'fork':
152
163
  result = client.profiles.fork(args.source_name, args.source_version, name=args.name, version=args.version,
153
- secret_values=read_secret_values(args))
164
+ secret_values=read_secret_values(args), **visibility_options)
165
+ elif args.action == 'set-visibility':
166
+ result = client.profiles.set_visibility(args.name, args.version, visibility=args.visibility,
167
+ expected_visibility=args.expected_visibility, expected_acl_revision=args.expected_acl_revision)
154
168
  elif args.action == "get":
155
169
  result = client.profiles.get(args.name, args.version)
156
170
  elif args.action == "list":
@@ -159,6 +173,7 @@ def execute_profile(args: argparse.Namespace, client: Any, cli: Any) -> Any:
159
173
  include_archived=args.include_archived,
160
174
  limit=args.limit,
161
175
  cursor=args.cursor,
176
+ **({} if args.visibility is None else {'visibility': args.visibility}),
162
177
  )
163
178
  elif args.action == "set-default":
164
179
  result = client.profiles.set_default(
@@ -16,6 +16,7 @@ class ProfileService(Protocol):
16
16
  include_archived: bool = False,
17
17
  limit: int = 50,
18
18
  cursor: str | None = None,
19
+ visibility: str | None = None,
19
20
  ) -> dict[str, Any]: ...
20
21
  def resolve_profile(
21
22
  self,
@@ -41,6 +42,10 @@ class ProfileService(Protocol):
41
42
  version: str | None = None,
42
43
  secrets: Mapping[str, Any] | None = None,
43
44
  ) -> dict[str, Any]: ...
45
+ def set_profile_visibility(self, name: str, version: str, *, visibility: str,
46
+ expected_visibility: str, expected_acl_revision: int) -> dict[str, Any]: ...
47
+ def fork_profile(self, source_name: str, source_version: str, *, name: str, version: str,
48
+ visibility: str) -> dict[str, Any]: ...
44
49
 
45
50
 
46
51
  class RunnerService(Protocol):
@@ -59,7 +64,7 @@ class Profiles:
59
64
  return self._server.init_repository(root)
60
65
 
61
66
  def put(self, spec: Mapping[str, Any], *, secrets: Mapping[str, Any] | None = None,
62
- secret_values: Mapping[str, str] | None = None) -> dict[str, Any]:
67
+ secret_values: Mapping[str, str] | None = None, visibility: str | None = None) -> dict[str, Any]:
63
68
  """Create an immutable version; model keys and Secret parameters are explicit and write-only.
64
69
 
65
70
  `secret_values` maps parameter names to values the platform stores as Secret
@@ -70,12 +75,13 @@ class Profiles:
70
75
  if secret_values is not None:
71
76
  spec, original = with_secret_values(spec, secret_values), spec
72
77
  reject_supplied(original, secret_values)
73
- return self._server.put_profile(profile_payload(spec, secrets))
78
+ payload = profile_payload(spec, secrets)
79
+ return self._server.put_profile(payload if visibility is None else {'spec': payload, 'visibility': _visibility(visibility)})
74
80
 
75
81
  create = put
76
82
 
77
83
  def update(self, name: str, version: str, *, patch: dict[str, Any], from_version: str | None = None, secrets: Mapping[str, Any] | None = None,
78
- secret_values: Mapping[str, str] | None = None):
84
+ secret_values: Mapping[str, str] | None = None, visibility: str | None = None):
79
85
  """Merge parameter keys into a new immutable version of an existing Profile.
80
86
 
81
87
  Omitted fields and Secret markers are preserved. Supplied metadata,
@@ -87,7 +93,8 @@ class Profiles:
87
93
  from envloop_data.profile_updates import checked_patch, merge_v2_params
88
94
 
89
95
  patch = checked_patch(patch, name, version)
90
- original = self.get(name, from_version)["spec"]
96
+ source = self.get(name, from_version)
97
+ original = source['spec']
91
98
  spec = {**original, **patch, "name": name, "version": version}
92
99
  if original.get('schema_version') == 'envplatform.profile/v2':
93
100
  if 'params' in patch:
@@ -95,16 +102,25 @@ class Profiles:
95
102
  raise RemoteError('INVALID_PROFILE', 422)
96
103
  before, changes = original.get('spec', {}), patch.get('spec', {})
97
104
  spec['spec'] = {**before, **changes, 'params': merge_v2_params(before.get('params', {}), changes.get('params', {}), spec.get('secret_params', []))}
105
+ elif original.get('schema_version') == 'envloop.profile/v3':
106
+ spec['parameters'] = {**original.get('parameters', {}), **patch.get('parameters', {})}
107
+ if visibility is None:
108
+ visibility = source.get('visibility', 'private')
98
109
  else:
99
110
  spec['params'] = {**original.get('params', {}), **patch.get('params', {})}
100
- return self.put(_with_secrets(spec, patch, secret_values), secrets=secrets)
111
+ return self.put(_with_secrets(spec, patch, secret_values), secrets=secrets, visibility=visibility)
101
112
 
102
113
  def fork(self, source_name: str, source_version: str, *, name: str, version: str, patch: dict[str, Any] | None = None, secrets: Mapping[str, Any] | None = None,
103
- secret_values: Mapping[str, str] | None = None):
114
+ secret_values: Mapping[str, str] | None = None, visibility: str | None = None):
104
115
  """Publish a new identity from an authorized source; never change its default."""
105
116
  from envloop_data.profile_updates import checked_patch, merge_v2_params
106
117
 
107
118
  original = self.get(source_name, source_version)['spec']
119
+ if original.get('schema_version') == 'envloop.profile/v3':
120
+ if patch or secrets or secret_values:
121
+ raise ValueError('Fork a v3 Profile first, then publish an updated version')
122
+ return self._server.fork_profile(source_name, source_version, name=name, version=version,
123
+ visibility=_visibility(visibility or 'private'))
108
124
  changes = checked_patch({} if patch is None else patch, name, version)
109
125
  result = {**original, **changes, 'name': name, 'version': version}
110
126
  if original.get('schema_version') == 'envplatform.profile/v2':
@@ -112,7 +128,7 @@ class Profiles:
112
128
  result['spec'] = {**before, **updates, 'params': merge_v2_params(before.get('params', {}), updates.get('params', {}), result.get('secret_params', []))}
113
129
  else:
114
130
  result['params'] = {**original.get('params', {}), **changes.get('params', {})}
115
- return self.put(_with_secrets(result, changes, secret_values), secrets=secrets)
131
+ return self.put(_with_secrets(result, changes, secret_values), secrets=secrets, visibility=visibility)
116
132
 
117
133
  def get(self, name: str, version: str | None = None) -> dict[str, Any]:
118
134
  return self._server.get_profile(name, version)
@@ -131,6 +147,13 @@ class Profiles:
131
147
  def archive(self, name: str, version: str):
132
148
  return self._server.archive_profile(name, version)
133
149
 
150
+ def set_visibility(self, name: str, version: str, *, visibility: str,
151
+ expected_visibility: str, expected_acl_revision: int):
152
+ if type(expected_acl_revision) is not int or expected_acl_revision < 0:
153
+ raise ValueError('expected_acl_revision must be a nonnegative integer')
154
+ return self._server.set_profile_visibility(name, version, visibility=_visibility(visibility),
155
+ expected_visibility=_visibility(expected_visibility), expected_acl_revision=expected_acl_revision)
156
+
134
157
  def export(self, name: str, version: str):
135
158
  return self._server.export_profile(name, version)
136
159
 
@@ -139,7 +162,7 @@ class Profiles:
139
162
  return self._server.revoke_profile_secret(name, version)
140
163
 
141
164
  def import_spec(self, raw: bytes, *, name: str | None = None, version: str | None = None, secrets: Mapping[str, Any] | None = None, runner: str | None = None,
142
- secret_values: Mapping[str, str] | None = None):
165
+ secret_values: Mapping[str, str] | None = None, visibility: str | None = None):
143
166
  import json
144
167
 
145
168
  from envloop.http import RemoteError
@@ -168,10 +191,20 @@ class Profiles:
168
191
  value, original = with_secret_values(value, secret_values), value
169
192
  reject_supplied(original, secret_values)
170
193
  raw = json.dumps(value, allow_nan=False, ensure_ascii=False).encode('utf-8')
194
+ if visibility is not None:
195
+ if not isinstance(value, dict) or (name is not None and value.get('name') != name) or (version is not None and value.get('version') != version):
196
+ raise RemoteError('INVALID_PROFILE', 422)
197
+ return self.put(value, secrets=secrets, visibility=visibility)
171
198
  options = {} if secrets is None else {"secrets": secrets}
172
199
  return self._server.import_profile(raw, name=name, version=version, **options)
173
200
 
174
201
 
202
+ def _visibility(value: str) -> str:
203
+ if value not in ('private', 'public'):
204
+ raise ValueError('visibility must be private or public')
205
+ return value
206
+
207
+
175
208
  def _with_secrets(spec: dict[str, Any], patch: Mapping[str, Any], values: Mapping[str, str] | None) -> dict[str, Any]:
176
209
  """Replace stored Secret parameters of a derived version; the patch may not also set them."""
177
210
  if values is None: