envloop-cli 2.0.0__tar.gz → 2.1.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 (82) hide show
  1. envloop_cli-2.0.0/README.pypi.md → envloop_cli-2.1.0/PKG-INFO +43 -2
  2. envloop_cli-2.0.0/PKG-INFO → envloop_cli-2.1.0/README.pypi.md +23 -20
  3. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/cli.py +3 -0
  4. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/cli_errors.py +4 -1
  5. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/http.py +10 -8
  6. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/assets.py +15 -6
  7. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/direct_checkpoint.py +41 -3
  8. envloop_cli-2.1.0/packages/asset/envloop_asset/direct_publication.py +84 -0
  9. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/direct_storage.py +6 -2
  10. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/resource_cli.py +1 -1
  11. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/tags.py +20 -0
  12. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/transfer.py +146 -21
  13. envloop_cli-2.1.0/packages/chat/envloop_chat/__init__.py +1 -0
  14. envloop_cli-2.1.0/packages/chat/envloop_chat/cli.py +116 -0
  15. envloop_cli-2.1.0/packages/chat/envloop_chat/client.py +146 -0
  16. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/cli.py +14 -5
  17. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/client.py +23 -10
  18. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/http.py +1 -2
  19. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/job_spec_cli.py +6 -3
  20. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/named_profile.py +5 -1
  21. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/pyproject.toml +8 -7
  22. envloop_cli-2.0.0/packages/asset/envloop_asset/direct_publication.py +0 -46
  23. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/.gitignore +0 -0
  24. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/__init__.py +0 -0
  25. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/_optional.py +0 -0
  26. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/auth_cli.py +0 -0
  27. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/auth_login.py +0 -0
  28. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/auth_workspace.py +0 -0
  29. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/cli_output.py +0 -0
  30. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/client.py +0 -0
  31. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/config.py +0 -0
  32. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/downloads.py +0 -0
  33. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/lifecycle_cli.py +0 -0
  34. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/navigation_resources.py +0 -0
  35. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/profile_secrets.py +0 -0
  36. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/resource_cli.py +0 -0
  37. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/resources.py +0 -0
  38. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/terminal.py +0 -0
  39. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/utils/__init__.py +0 -0
  40. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/envloop/utils/logging.py +0 -0
  41. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/__init__.py +0 -0
  42. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/checkpoint_download.py +0 -0
  43. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/checkpoint_upload.py +0 -0
  44. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/cli.py +0 -0
  45. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/cli_output.py +0 -0
  46. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/client.py +0 -0
  47. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/dataset_upload.py +0 -0
  48. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/direct_artifact.py +0 -0
  49. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/direct_worker_artifact.py +0 -0
  50. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/execution_content.py +0 -0
  51. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/http.py +0 -0
  52. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/navigation_resources.py +0 -0
  53. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/profile_updates.py +0 -0
  54. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/publication_cli.py +0 -0
  55. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/publications.py +0 -0
  56. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/r2_upload.py +0 -0
  57. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/recipe_packages.py +0 -0
  58. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/recipes.py +0 -0
  59. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/runner_packages.py +0 -0
  60. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/asset/envloop_asset/upload_strategy.py +0 -0
  61. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/__init__.py +0 -0
  62. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/cli_output.py +0 -0
  63. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/decision.py +0 -0
  64. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/inference.py +0 -0
  65. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/job_cost.py +0 -0
  66. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/job_logs.py +0 -0
  67. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/navigation_resources.py +0 -0
  68. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/resource_cli.py +0 -0
  69. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/resources.py +0 -0
  70. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/runtime_params.py +0 -0
  71. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/sandbox.py +0 -0
  72. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/train.py +0 -0
  73. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/train_log_cli.py +0 -0
  74. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/train_metrics_cli.py +0 -0
  75. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/train_progress.py +0 -0
  76. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/train_runner_cli.py +0 -0
  77. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/experiment/envloop_experiment/training/__init__.py +0 -0
  78. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/rsi-loop/envloop_rsi_loop/__init__.py +0 -0
  79. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/rsi-loop/envloop_rsi_loop/cli.py +0 -0
  80. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/rsi-loop/envloop_rsi_loop/cli_output.py +0 -0
  81. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/rsi-loop/envloop_rsi_loop/loop_cli.py +0 -0
  82. {envloop_cli-2.0.0 → envloop_cli-2.1.0}/packages/rsi-loop/envloop_rsi_loop/loops.py +0 -0
@@ -1,3 +1,23 @@
1
+ Metadata-Version: 2.5
2
+ Name: envloop-cli
3
+ Version: 2.1.0
4
+ Summary: EnvLoop CLI and Python SDK for jobs, training, checkpoints and inference
5
+ Project-URL: Homepage, https://envloop.ai
6
+ Project-URL: Documentation, https://docs.envloop.ai
7
+ Project-URL: Repository, https://github.com/EnvLoop/envloop-cli
8
+ Project-URL: Issues, https://github.com/EnvLoop/envloop-cli/issues
9
+ Project-URL: Agent instructions, https://docs.envloop.ai/skill.md
10
+ Requires-Python: >=3.12
11
+ Provides-Extra: asset
12
+ Requires-Dist: boto3==1.44.3; extra == 'asset'
13
+ Requires-Dist: envloop-envhub==1.23.0; extra == 'asset'
14
+ Provides-Extra: chat
15
+ Requires-Dist: openai==3.55.1; extra == 'chat'
16
+ Provides-Extra: default
17
+ Provides-Extra: experiment
18
+ Provides-Extra: rsi-loop
19
+ Description-Content-Type: text/markdown
20
+
1
21
  # envloop-cli: EnvLoop CLI and Python SDK
2
22
 
3
23
  Install the public client to run agent Jobs, inspect Trials, manage training and
@@ -15,6 +35,7 @@ unreleased features.
15
35
 
16
36
  | Unreleased source enhancement | Published 1.33.0 |
17
37
  | --- | --- |
38
+ | `el job chat JOB_ID [PROMPT]` and the `chat` extra | not available |
18
39
  | Explicit `--json` for `el runner get\|create\|update\|delete` | These commands already output JSON; omit `--json` |
19
40
  | `el dataset create --format harbor --update-digests` | not available; set `[[tasks]] digest` values by hand |
20
41
  | `el trial artifact download TRIAL_ID --output DIRECTORY` | positional `DIRECTORY` only |
@@ -86,6 +107,21 @@ python -m pip install "envloop-cli[asset]"
86
107
 
87
108
  ## Connect
88
109
 
110
+ For Job-bound chat, install the optional dependency in the same environment:
111
+
112
+ ```bash
113
+ python -m pip install "envloop-cli[chat]"
114
+ el job chat JOB_ID "Introduce yourself."
115
+ el job chat JOB_ID
116
+ el job chat JOB_ID "Hello" --json
117
+ ```
118
+
119
+ Text answers stream by default. `--json` returns one complete response.
120
+ The command uses the configured EnvLoop connection and automatically reads the
121
+ Job's model. The `chat` extra uses the official OpenAI Python SDK against EnvLoop;
122
+ it does not use an OpenAI account. `/clear` resets terminal history, `/exit` leaves,
123
+ and Ctrl+C exits without stopping the Job.
124
+
89
125
  Use an authorized EnvLoop account and project. Browser authorization:
90
126
 
91
127
  ```bash
@@ -197,14 +233,19 @@ Sandbox Job without a Dataset:
197
233
  ```bash
198
234
  el job submit --type sandbox --runner base --command 'python --version'
199
235
  el job submit --type sandbox --runner base --image python:3.11 --wait
236
+ el job submit --type sandbox --provider e2b --spec REQUEST.json
200
237
  el job list --type sandbox
201
238
  el job log JOB_ID --follow
202
239
  ```
203
240
 
204
241
  The platform resolves `base` to the registered `envloop/base@main` source ref and
205
242
  freezes its immutable Revision. The Sandbox image defaults to the registered Runner image;
206
- `--image` accepts an image name, tag or digest. The execution provider is configured
207
- by the server. Job logs retain the actual captured output and collection metadata.
243
+ `--image` accepts an image name, tag or digest. Bench and Sandbox submissions can request a
244
+ platform-enabled provider by name. In a request file, `provider` is a
245
+ top-level field alongside `spec` and optional `overrides` in an `envloop.job/v2`
246
+ envelope. The `--provider` flag overrides that field and also works with the
247
+ named `--profile` shortcut. Omit the selection to use the platform default.
248
+ Job logs retain the actual captured output and collection metadata.
208
249
  Failures include a code, readable explanation, HTTP status when available, and
209
250
  recovery guidance without echoing arbitrary response bodies or credentials.
210
251
 
@@ -1,21 +1,3 @@
1
- Metadata-Version: 2.5
2
- Name: envloop-cli
3
- Version: 2.0.0
4
- Summary: EnvLoop CLI and Python SDK for jobs, training, checkpoints and inference
5
- Project-URL: Homepage, https://envloop.ai
6
- Project-URL: Documentation, https://docs.envloop.ai
7
- Project-URL: Repository, https://github.com/EnvLoop/envloop-cli
8
- Project-URL: Issues, https://github.com/EnvLoop/envloop-cli/issues
9
- Project-URL: Agent instructions, https://docs.envloop.ai/skill.md
10
- Requires-Python: >=3.12
11
- Provides-Extra: asset
12
- Requires-Dist: boto3==1.44.3; extra == 'asset'
13
- Requires-Dist: envloop-envhub==1.23.0; extra == 'asset'
14
- Provides-Extra: default
15
- Provides-Extra: experiment
16
- Provides-Extra: rsi-loop
17
- Description-Content-Type: text/markdown
18
-
19
1
  # envloop-cli: EnvLoop CLI and Python SDK
20
2
 
21
3
  Install the public client to run agent Jobs, inspect Trials, manage training and
@@ -33,6 +15,7 @@ unreleased features.
33
15
 
34
16
  | Unreleased source enhancement | Published 1.33.0 |
35
17
  | --- | --- |
18
+ | `el job chat JOB_ID [PROMPT]` and the `chat` extra | not available |
36
19
  | Explicit `--json` for `el runner get\|create\|update\|delete` | These commands already output JSON; omit `--json` |
37
20
  | `el dataset create --format harbor --update-digests` | not available; set `[[tasks]] digest` values by hand |
38
21
  | `el trial artifact download TRIAL_ID --output DIRECTORY` | positional `DIRECTORY` only |
@@ -104,6 +87,21 @@ python -m pip install "envloop-cli[asset]"
104
87
 
105
88
  ## Connect
106
89
 
90
+ For Job-bound chat, install the optional dependency in the same environment:
91
+
92
+ ```bash
93
+ python -m pip install "envloop-cli[chat]"
94
+ el job chat JOB_ID "Introduce yourself."
95
+ el job chat JOB_ID
96
+ el job chat JOB_ID "Hello" --json
97
+ ```
98
+
99
+ Text answers stream by default. `--json` returns one complete response.
100
+ The command uses the configured EnvLoop connection and automatically reads the
101
+ Job's model. The `chat` extra uses the official OpenAI Python SDK against EnvLoop;
102
+ it does not use an OpenAI account. `/clear` resets terminal history, `/exit` leaves,
103
+ and Ctrl+C exits without stopping the Job.
104
+
107
105
  Use an authorized EnvLoop account and project. Browser authorization:
108
106
 
109
107
  ```bash
@@ -215,14 +213,19 @@ Sandbox Job without a Dataset:
215
213
  ```bash
216
214
  el job submit --type sandbox --runner base --command 'python --version'
217
215
  el job submit --type sandbox --runner base --image python:3.11 --wait
216
+ el job submit --type sandbox --provider e2b --spec REQUEST.json
218
217
  el job list --type sandbox
219
218
  el job log JOB_ID --follow
220
219
  ```
221
220
 
222
221
  The platform resolves `base` to the registered `envloop/base@main` source ref and
223
222
  freezes its immutable Revision. The Sandbox image defaults to the registered Runner image;
224
- `--image` accepts an image name, tag or digest. The execution provider is configured
225
- by the server. Job logs retain the actual captured output and collection metadata.
223
+ `--image` accepts an image name, tag or digest. Bench and Sandbox submissions can request a
224
+ platform-enabled provider by name. In a request file, `provider` is a
225
+ top-level field alongside `spec` and optional `overrides` in an `envloop.job/v2`
226
+ envelope. The `--provider` flag overrides that field and also works with the
227
+ named `--profile` shortcut. Omit the selection to use the platform default.
228
+ Job logs retain the actual captured output and collection metadata.
226
229
  Failures include a code, readable explanation, HTTP status when available, and
227
230
  recovery guidance without echoing arbitrary response bodies or credentials.
228
231
 
@@ -278,6 +278,9 @@ def _main(argv: list[str] | None = None):
278
278
  if args.group == 'setting' and args.action == 'update' and not any(getattr(args, key) is not None for key in ('name', 'slug', 'region')):
279
279
  cli.error('provide at least one of --name, --slug or --region')
280
280
  try:
281
+ if args.group == 'job' and args.action == 'chat':
282
+ from envloop_chat.client import require_dependencies
283
+ require_dependencies()
281
284
  if args.group == 'loop':
282
285
  from ._optional import feature_module
283
286
  feature_module('rsi-loop', 'loop_cli').validate(args)
@@ -162,6 +162,8 @@ _register("RESOURCE_IN_USE", "Remove or release the listed references first. A r
162
162
  _register("PUBLIC_DEPENDENCY_UNAVAILABLE", "A shared resource needs dependencies at least as readable as itself: a public Recipe needs public dependencies, and an internal Recipe needs dependencies readable in this workspace (internal or public). Change the dependencies' visibility first (the owning resource set-visibility ASSET_ID), then retry; private dependencies are never shared automatically.")
163
163
  _register("PUBLIC_CONTENT_UNSAFE PUBLICATION_REVIEW_REQUIRED", "Content review failed for one of this name's current revisions, so it cannot be shared. Fix or retire the flagged revision, then retry.")
164
164
  _register("CHECKPOINT_AMBIGUOUS", "More than one checkpoint matches this selection.")
165
+ _register("CHECKPOINT_METADATA_PENDING", "Checkpoint files are committed, but their metadata is not complete. Retry checkpoint upload complete with the same OPERATION_ID; keep the original tags and do not upload the files again.")
166
+ _register("ASSET_PIN_CONFLICT", "This immutable asset already has different content or tags. Keep the existing publication unchanged and use a new immutable asset identity for a different publication.")
165
167
  _register("CHECKPOINT_UPLOAD_UNAVAILABLE", "The platform checkpoint upload service is unavailable. Ask a platform operator to check the upload service and temporary-credential configuration, then let the worker retry.")
166
168
  _register("CHECKPOINT_UPLOAD_FORBIDDEN", "Checkpoint publication requires the current Train worker's platform-issued credential in its own workspace and project. Check the worker connection and checkpoints.write permission.")
167
169
  _register("CHECKPOINT_UPLOAD_CLOSED", "The checkpoint upload session or its producing Trial is no longer open for publication. Check the Trial state and worker credential expiry; a stopped Trial cannot publish.")
@@ -174,6 +176,7 @@ _register("CHECKPOINT_FILES_UNAVAILABLE ARTIFACT_NOT_READY", "The requested down
174
176
  _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.")
175
177
  _register("ARTIFACT_DOWNLOAD_FAILED", "The artifact download service rejected the request.")
176
178
  _register("ENDPOINT_NOT_READY", "The inference endpoint is not ready.")
179
+ _register("CHAT_TEXT_UNAVAILABLE", "The model did not return a text answer. Use --json to inspect the complete response.")
177
180
  _register("WAIT_TIMEOUT", "The resource did not reach the requested state before the wait timeout.")
178
181
  _register("CLEANUP_INCOMPLETE", "The persisted cleanup operation did not complete successfully.")
179
182
  _register("CLI_ERROR", "The command could not be completed.")
@@ -294,7 +297,7 @@ def _http_message(status: int | None) -> str:
294
297
  return _MESSAGES["HTTP_ERROR"]
295
298
 
296
299
 
297
- _OWN_PACKAGES = frozenset({"envloop", "envloop_asset", "envloop_experiment", "envloop_rsi_loop"})
300
+ _OWN_PACKAGES = frozenset({"envloop", "envloop_asset", "envloop_experiment", "envloop_rsi_loop", "envloop_chat"})
298
301
 
299
302
 
300
303
  def validation_message(error: BaseException) -> str | None:
@@ -21,23 +21,25 @@ REDIRECT_STATUSES = {301, 302, 303, 307, 308}
21
21
  RESOLVED_OWNER_FIELDS = ("dataset_owners", "checkpoint_owners", "checkpoint_owner", "runner_owner", "runner_storage_prefix")
22
22
 
23
23
 
24
- def validate_public_execution(value: Any, *, allow_local_sandbox: bool = True) -> None:
25
- """Only an explicit top-level local Sandbox selection is public."""
24
+ def validate_public_execution(value: Any, *, allow_sandbox_provider: bool = True) -> None:
25
+ """Allow provider selection only on the outer Bench/Sandbox submit request."""
26
26
  if not isinstance(value, dict):
27
27
  return
28
- spec = value.get("spec")
29
- if any(key in value for key in RESOLVED_OWNER_FIELDS) or isinstance(spec, dict) and any(key in spec for key in RESOLVED_OWNER_FIELDS):
28
+ if any(key in value for key in RESOLVED_OWNER_FIELDS):
30
29
  raise ValueError("the owning project of each input is resolved by the platform; select a Dataset copy by its "
31
30
  "asset_id and remove dataset_owners, checkpoint_owners, checkpoint_owner and runner_owner")
32
31
  if any(key in value for key in ("executor", "backend")):
33
32
  raise ValueError("execution backend is configured by the server")
34
- if "provider" in value and not (allow_local_sandbox and value.get("type") == "sandbox" and value["provider"] == "local"):
35
- raise ValueError("provider must be local and requires a Sandbox Job")
33
+ if "provider" in value:
34
+ spec = value.get("spec")
35
+ kind = spec.get("type") if isinstance(spec, dict) and spec.get("schema") == "envloop.job/v2" else value.get("type")
36
+ if not (allow_sandbox_provider and kind in {"bench", "sandbox"} and value.get("type", kind) == kind):
37
+ raise ValueError("provider is only accepted as a top-level Bench/Sandbox Job submission field")
36
38
  execution = value.get("execution")
37
39
  if isinstance(execution, dict) and any(key in execution for key in ("executor", "provider", "backend")):
38
40
  raise ValueError("execution backend is configured by the server")
39
- for key in ("profile", "profile_overrides", "params"):
40
- validate_public_execution(value.get(key), allow_local_sandbox=False)
41
+ for key in ("spec", "overrides", "profile", "profile_overrides", "params"):
42
+ validate_public_execution(value.get(key), allow_sandbox_provider=False)
41
43
 
42
44
 
43
45
  class WaitTimeoutError(TimeoutError):
@@ -167,6 +167,9 @@ class ContentResource:
167
167
  from .publications import INLINE_BYTES, hf_source, prepare, publication_ref
168
168
  if type(wait) is not bool or not 0 <= timeout < float('inf'):
169
169
  raise ValueError('wait must be boolean and timeout must be nonnegative')
170
+ if self.kind == 'checkpoint' and source.get('tags') is not None:
171
+ from .tags import validate_checkpoint_tags
172
+ source['tags'] = validate_checkpoint_tags(source['tags'])
170
173
  if self.kind == 'recipe' and version is not None:
171
174
  raise ValueError('Recipe versions are derived from content; omit --version')
172
175
  source_format = source.pop('format', None)
@@ -179,22 +182,24 @@ class ContentResource:
179
182
  if update_digests:
180
183
  raise ValueError('--update-digests requires --format harbor')
181
184
  if self.kind == 'checkpoint' and source.get('result') is not None:
182
- if name is not None or version is not None or any(value is not None for key,value in source.items() if key not in {'result','directory','checkpoint_name'}):
183
- raise ValueError('Worker Checkpoints accept only saved result, directory and checkpoint_name')
185
+ if name is not None or version is not None or any(value is not None for key,value in source.items() if key not in {'result','directory','checkpoint_name','tags'}):
186
+ raise ValueError('Worker Checkpoints accept only saved result, directory, checkpoint_name and tags')
184
187
  if parent is not None:
185
188
  raise ValueError('A worker publishes each new save with create, never update')
186
- from .direct_checkpoint import publish
189
+ from .direct_checkpoint import check_metadata, publish
187
190
  from .direct_storage import _DomainTransport
188
191
  adapter = _DomainTransport(self.transport,'checkpoints')
192
+ tags = source.pop('tags', None)
189
193
  try:
190
194
  receipt = publish(adapter, source.pop('directory'), result=source.pop('result'),
191
- checkpoint_name=source.pop('checkpoint_name', None), single=True,
195
+ checkpoint_name=source.pop('checkpoint_name', None), tags=tags, single=True,
192
196
  upload_path=scope(self.transport) + '/checkpoints/uploads')
197
+ value = self.get(receipt.get('asset_id') or receipt['uri'])
198
+ check_metadata(value, tags=tags)
193
199
  except BaseException as error:
194
200
  if adapter.last is not None:
195
201
  cast(Any,error).last = adapter.last
196
202
  raise
197
- value = self.get(receipt.get('asset_id') or receipt['uri'])
198
203
  asset = value['asset']
199
204
  asset['details'] = {**receipt, 'durable':True, 'upload_actor':'worker', **asset.get('details',{})}
200
205
  return value
@@ -408,7 +413,11 @@ class ContentResource:
408
413
  return envelope(self.transport.request('GET', self._operation_path(operation_id)))
409
414
 
410
415
  def upload_complete(self, operation_id: str) -> dict[str, Any]:
411
- return envelope(self.transport.request('POST', self._operation_path(operation_id) + '/complete'))
416
+ value = envelope(self.transport.request('POST', self._operation_path(operation_id) + '/complete'))
417
+ if self.kind == 'checkpoint':
418
+ from .direct_checkpoint import check_metadata
419
+ check_metadata(value)
420
+ return value
412
421
 
413
422
  def upload_abort(self, operation_id: str) -> dict[str, Any]:
414
423
  return envelope(self.transport.request('POST', self._operation_path(operation_id) + '/abort'))
@@ -2,8 +2,9 @@
2
2
  import json
3
3
  import re
4
4
  import stat
5
+ from collections.abc import Mapping
5
6
  from pathlib import Path
6
- from typing import Any
7
+ from typing import Any, cast
7
8
 
8
9
  from envloop.http import RemoteError
9
10
 
@@ -17,6 +18,7 @@ from .direct_storage import (
17
18
  _Storage,
18
19
  )
19
20
  from .publications import open_file
21
+ from .tags import validate_checkpoint_tags, validate_tags
20
22
 
21
23
 
22
24
  def _inventory(saved: Path) -> list[dict[str, Any]]:
@@ -99,7 +101,40 @@ def _receipt(value: Any, *, step: int, uri: str | None = None) -> dict[str, Any]
99
101
  return receipt
100
102
 
101
103
 
102
- def publish(transport: Any, directory: str | Path, *, result: str | Path | dict[str, Any], upload_path: str, checkpoint_name: str | None = None, single: bool = False) -> dict[str, Any]:
104
+ def check_metadata(value: dict[str, Any], *, tags: Mapping[str, str] | None = None) -> dict[str, Any]:
105
+ """A byte receipt alone does not finish a labelled publication."""
106
+ operation = value.get('operation')
107
+ operation = operation if isinstance(operation, dict) else {}
108
+ upload = operation.get('upload')
109
+ upload = upload if isinstance(upload, dict) else {}
110
+ state = upload.get('state')
111
+ failure = operation.get('error')
112
+ code = failure.get('code') if isinstance(failure, dict) else None
113
+ if state == 'metadata_conflict' or code == 'ASSET_PIN_CONFLICT':
114
+ error = RemoteError('ASSET_PIN_CONFLICT', 409)
115
+ elif (state == 'metadata_pending' or code == 'CHECKPOINT_METADATA_PENDING'
116
+ or state == 'committed' and operation.get('status') != 'succeeded'):
117
+ error = RemoteError('CHECKPOINT_METADATA_PENDING', 503)
118
+ else:
119
+ labels = tags if tags is not None else upload.get('tags') if state == 'committed' else None
120
+ try:
121
+ labels = validate_tags(labels) if labels is not None else {}
122
+ except ValueError:
123
+ error = RemoteError('INVALID_RESPONSE')
124
+ else:
125
+ asset = value.get('asset')
126
+ details = asset.get('details') if isinstance(asset, dict) else None
127
+ actual = (details.get('tags') if isinstance(details, dict) and 'tags' in details
128
+ else asset.get('tags') if isinstance(asset, dict) else None)
129
+ if not labels or isinstance(actual, dict) and all(actual.get(key) == item for key, item in labels.items()):
130
+ return value
131
+ error = RemoteError('CHECKPOINT_METADATA_PENDING', 503)
132
+ cast(Any, error).last = value
133
+ raise error
134
+
135
+
136
+ def publish(transport: Any, directory: str | Path, *, result: str | Path | dict[str, Any], upload_path: str, checkpoint_name: str | None = None, tags: Mapping[str, str] | None = None, single: bool = False) -> dict[str, Any]:
137
+ labels = validate_checkpoint_tags(tags) if tags is not None else None
103
138
  prepared = _prepare(directory, result)
104
139
  if single:
105
140
  if checkpoint_name is None and len(prepared) != 1:
@@ -112,7 +147,10 @@ def publish(transport: Any, directory: str | Path, *, result: str | Path | dict[
112
147
  for item, saved, entries in prepared:
113
148
  descriptor = {key: item[key] for key in ('step', 'kind', 'model', 'model_revision', 'directory', 'format') if key in item}
114
149
  descriptor['name'] = f"checkpoint-{item['step']}"
115
- session = _request(transport, upload_path, dict(type='checkpoint', checkpoint=descriptor, files=entries),
150
+ body = dict(type='checkpoint', checkpoint=descriptor, files=entries)
151
+ if labels is not None:
152
+ body['tags'] = labels
153
+ session = _request(transport, upload_path, body,
116
154
  phase='checkpoint_upload_init')
117
155
  if isinstance(session, dict) and session.get('state') == 'committed':
118
156
  receipt = _receipt(session, step=item['step'])
@@ -0,0 +1,84 @@
1
+ """Coordinate Checkpoint upload plans, provider strategies and metadata-only completion."""
2
+ import hashlib
3
+ import re
4
+ import socket
5
+ import ssl
6
+ from typing import Any
7
+ from urllib.error import HTTPError, URLError
8
+ from urllib.parse import urlencode
9
+
10
+ from envloop.http import RemoteError
11
+ from envloop_asset.upload_strategy import strategy_for
12
+
13
+
14
+ def storage_failure(error: Exception) -> RemoteError:
15
+ reason = error.reason if isinstance(error, URLError) else error
16
+ response = getattr(error, 'response', None)
17
+ response = response if isinstance(response, dict) else {}
18
+ storage_error = response.get('Error')
19
+ storage_error = storage_error if isinstance(storage_error, dict) else {}
20
+ metadata = response.get('ResponseMetadata')
21
+ metadata = metadata if isinstance(metadata, dict) else {}
22
+ transport_kind = {'ConnectTimeoutError': 'timeout', 'ReadTimeoutError': 'timeout',
23
+ 'SSLError': 'tls_error', 'EndpointConnectionError': 'connection_error',
24
+ 'ConnectionClosedError': 'connection_error', 'ProxyConnectionError': 'connection_error'}
25
+ kind = ('http_error' if isinstance(error, HTTPError) or storage_error else
26
+ transport_kind[type(error).__name__] if type(error).__name__ in transport_kind else
27
+ 'timeout' if isinstance(reason, TimeoutError) else
28
+ 'tls_error' if isinstance(reason, ssl.SSLError) else
29
+ 'dns_error' if isinstance(reason, socket.gaierror) else
30
+ 'connection_error' if isinstance(reason, ConnectionError) else 'transport_error')
31
+ details = ['Storage failure: ' + kind]
32
+ allowed = {'SignatureDoesNotMatch', 'AccessDenied', 'ExpiredToken', 'RequestTimeTooSkewed',
33
+ 'RequestExpired', 'SlowDown', 'ServiceUnavailable', 'InternalError',
34
+ 'XAmzContentSHA256Mismatch', 'InvalidRequest', 'EntityTooLarge',
35
+ 'AuthorizationQueryParametersError', 'RequestTimeout'}
36
+ status = error.code if isinstance(error, HTTPError) else metadata.get('HTTPStatusCode')
37
+ if type(status) is int and 400 <= status <= 599:
38
+ details.append('Storage HTTP status: ' + str(status))
39
+ code = storage_error.get('Code')
40
+ if isinstance(error, HTTPError):
41
+ try:
42
+ body = error.read(4096)
43
+ except Exception:
44
+ body = b''
45
+ match = re.search(rb'<Code>([A-Za-z][A-Za-z0-9]{0,63})</Code>', body)
46
+ code = match.group(1).decode('ascii') if match is not None else None
47
+ if isinstance(code, str) and code in allowed:
48
+ details.append('Storage error code: ' + code)
49
+ return RemoteError('CHECKPOINT_STORAGE_UPLOAD_FAILED', details=details)
50
+
51
+
52
+ def upload_part(transport: Any, upload_path: str, number: int, content: bytes) -> dict[str, Any]:
53
+ digest = hashlib.sha256(content).hexdigest()
54
+ path = upload_path + f'/parts/{number}'
55
+ query = {'sha256': digest}
56
+ plan = transport.request('POST', path + '/url?' + urlencode(query))
57
+ expected = {'number': number, 'size': len(content), 'sha256': digest}
58
+ if not isinstance(plan, dict) or plan.get('transport') != 'direct' or plan.get('part') != expected:
59
+ raise RemoteError('INVALID_RESPONSE')
60
+ if plan.get('stored') is True:
61
+ strategy_for(plan.get('provider'))
62
+ return expected
63
+ lease = plan.get('lease')
64
+ if not isinstance(lease, str) or not re.fullmatch(r'[a-f0-9]{32}', lease):
65
+ raise RemoteError('INVALID_RESPONSE')
66
+
67
+ def report(outcome: str) -> Any:
68
+ return transport.request('POST', path + '/staged?' + urlencode({**query, 'lease': lease, 'outcome': outcome}))
69
+
70
+ try:
71
+ strategy_for(plan.get('provider')).upload(plan, content, api_base=transport.base)
72
+ except Exception as error:
73
+ failure = error if isinstance(error, RemoteError) else storage_failure(error)
74
+ if isinstance(error, HTTPError):
75
+ error.close()
76
+ try:
77
+ report('failed')
78
+ except Exception:
79
+ pass
80
+ raise failure from None
81
+ result = report('stored')
82
+ if result != expected:
83
+ raise RemoteError('INVALID_RESPONSE')
84
+ return expected
@@ -153,8 +153,9 @@ class _Storage:
153
153
  if code in ('ExpiredToken', 'ExpiredTokenException', 'InvalidToken') and attempt < 2:
154
154
  self.renew()
155
155
  continue
156
- # Storage exceptions may contain signed URLs, headers or credential material.
157
- raise RemoteError(self.kind.upper() + '_STORAGE_UPLOAD_FAILED', phase=self.kind + '_upload_storage') from None
156
+ from .direct_publication import storage_failure
157
+ raise RemoteError(self.kind.upper() + '_STORAGE_UPLOAD_FAILED', phase=self.kind + '_upload_storage',
158
+ details=storage_failure(error).details) from None
158
159
  raise RemoteError(self.kind.upper() + '_STORAGE_UPLOAD_FAILED', phase=self.kind + '_upload_storage')
159
160
 
160
161
  def send(self, saved: Path, entry: dict[str, Any]) -> None:
@@ -229,6 +230,9 @@ class _DomainTransport:
229
230
  if not isinstance(value,dict) or 'asset' not in value:
230
231
  return value
231
232
  self.last = value
233
+ if self.collection == 'checkpoints':
234
+ from .direct_checkpoint import check_metadata
235
+ check_metadata(value)
232
236
  operation = value.get('operation')
233
237
  if isinstance(operation,dict) and isinstance(operation.get('upload'),dict):
234
238
  upload_id, operation_id = operation['upload'].get('upload_id'), operation.get('operation_id')
@@ -46,7 +46,7 @@ def add_resource_commands(groups: "argparse._SubParsersAction[argparse.ArgumentP
46
46
  command.add_argument('--revision', help='Full immutable source commit')
47
47
  command.add_argument('--idempotency-key')
48
48
  command.add_argument('--ref', dest='publication_ref', help='Exact immutable ANS reference; must agree with the declaration')
49
- command.add_argument('--tags', help='Custom key:value labels')
49
+ command.add_argument('--tags', help='String labels as key:value,key:value or a JSON object')
50
50
  if kind == 'dataset':
51
51
  command.add_argument('--format', choices=('harbor',), help='Convert a native Harbor Dataset before publication')
52
52
  command.add_argument('--update-digests', action='store_true')
@@ -1,5 +1,6 @@
1
1
  """Generic string labels, kept outside content manifests."""
2
2
 
3
+ import json
3
4
  from collections.abc import Mapping
4
5
 
5
6
 
@@ -16,7 +17,26 @@ def validate_tags(value: object) -> dict[str, str]:
16
17
  return result
17
18
 
18
19
 
20
+ def validate_checkpoint_tags(value: object) -> dict[str, str]:
21
+ labels = validate_tags(value)
22
+ if 'decision-model' in labels and labels['decision-model'] not in ('true', 'false'):
23
+ raise ValueError('tags decision-model must be the string true or false')
24
+ return labels
25
+
26
+
19
27
  def parse_tags(text: str) -> dict[str, str]:
28
+ if text.lstrip().startswith('{'):
29
+ def unique(pairs: list[tuple[str, object]]) -> dict[str, object]:
30
+ value: dict[str, object] = {}
31
+ for key, item in pairs:
32
+ if key in value:
33
+ raise ValueError('tags JSON must use unique keys')
34
+ value[key] = item
35
+ return value
36
+ try:
37
+ return validate_tags(json.loads(text, object_pairs_hook=unique))
38
+ except json.JSONDecodeError:
39
+ raise ValueError('tags must be a valid JSON string mapping') from None
20
40
  result: dict[str, str] = {}
21
41
  for entry in text.split(','):
22
42
  key, separator, value = entry.partition(':')