envloop-cli 2.0.0__py3-none-any.whl → 2.1.0__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.
envloop/cli.py CHANGED
@@ -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)
envloop/cli_errors.py CHANGED
@@ -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:
envloop/http.py CHANGED
@@ -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):
envloop_asset/assets.py CHANGED
@@ -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'])
@@ -1,14 +1,54 @@
1
1
  """Coordinate Checkpoint upload plans, provider strategies and metadata-only completion."""
2
2
  import hashlib
3
3
  import re
4
+ import socket
5
+ import ssl
4
6
  from typing import Any
5
- from urllib.error import HTTPError
7
+ from urllib.error import HTTPError, URLError
6
8
  from urllib.parse import urlencode
7
9
 
8
10
  from envloop.http import RemoteError
9
11
  from envloop_asset.upload_strategy import strategy_for
10
12
 
11
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
+
12
52
  def upload_part(transport: Any, upload_path: str, number: int, content: bytes) -> dict[str, Any]:
13
53
  digest = hashlib.sha256(content).hexdigest()
14
54
  path = upload_path + f'/parts/{number}'
@@ -30,16 +70,14 @@ def upload_part(transport: Any, upload_path: str, number: int, content: bytes) -
30
70
  try:
31
71
  strategy_for(plan.get('provider')).upload(plan, content, api_base=transport.base)
32
72
  except Exception as error:
73
+ failure = error if isinstance(error, RemoteError) else storage_failure(error)
33
74
  if isinstance(error, HTTPError):
34
75
  error.close()
35
76
  try:
36
77
  report('failed')
37
78
  except Exception:
38
79
  pass
39
- if isinstance(error, RemoteError):
40
- raise
41
- # Storage exceptions can contain the signed URL. Never include their message in a CLI error.
42
- raise RemoteError('CHECKPOINT_STORAGE_UPLOAD_FAILED') from None
80
+ raise failure from None
43
81
  result = report('stored')
44
82
  if result != expected:
45
83
  raise RemoteError('INVALID_RESPONSE')
@@ -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')
envloop_asset/tags.py CHANGED
@@ -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(':')
envloop_asset/transfer.py CHANGED
@@ -1,12 +1,15 @@
1
1
  """Project-scoped EL Assets CRUD and verified, resumable transfers."""
2
2
  import base64
3
3
  import hashlib
4
+ import inspect
4
5
  import json
5
6
  import os
6
7
  import re
7
8
  import stat
9
+ import threading
8
10
  import time
9
11
  from collections.abc import Mapping, Sequence
12
+ from concurrent.futures import Future, ThreadPoolExecutor
10
13
  from contextlib import contextmanager
11
14
  from dataclasses import dataclass
12
15
  from functools import partial
@@ -177,6 +180,17 @@ class AssetTransfer:
177
180
  def download_directory(self, uri: str, destination: str | Path, *, split: str | None = None, config: str | None = None,
178
181
  content_digest: str | None = None, task_id: str | None = None, task_digest: str | None = None):
179
182
  """Download a complete ANS directory using EnvHub and temporary URLs; `uri` may be an Asset ID."""
183
+ started = time.perf_counter()
184
+ timings: dict[str, Any] = {'queries': [], 'files': [], 'plan_validation_seconds': 0.0}
185
+ managed_timings = os.environ.get('ENVLOOP_DATA_TIMINGS') == '1'
186
+
187
+ def query(operation: str, call: Callable[[], Any]) -> Any:
188
+ before = time.perf_counter()
189
+ try:
190
+ return call()
191
+ finally:
192
+ timings['queries'].append({'operation': operation, 'seconds': time.perf_counter() - before})
193
+
180
194
  from envloop._optional import require_asset_dependencies
181
195
 
182
196
  require_asset_dependencies()
@@ -187,7 +201,7 @@ class AssetTransfer:
187
201
  'runners':'runner', 'recipes':'recipe'}
188
202
  resource = None
189
203
  if isinstance(uri, str) and not uri.startswith('envloop://'):
190
- resource = self.get(uri)
204
+ resource = query('resolve_resource', lambda: self.get(uri))
191
205
  ref = resource.get('ref') or resource.get('model_uri')
192
206
  if not isinstance(ref, str) or not ref:
193
207
  raise ValueError('this Asset resource has no downloadable ANS reference')
@@ -215,48 +229,159 @@ class AssetTransfer:
215
229
  raise ValueError('Task download requires paired task_id namespace/name and task_digest sha256:SHA256')
216
230
  endpoint = self._path(uri) + '/download'
217
231
  parameters = {'split': split, 'config': config, 'content_digest': content_digest, **task_selection}
218
- plan = self.transport.request('GET', self._query(endpoint, **parameters))
232
+ plan = query('download_plan', lambda: self.transport.request('GET', self._query(endpoint, **parameters)))
219
233
  from envhub.ans.client import validate_download_plan
234
+ before_validation = time.perf_counter()
220
235
  try:
221
- validate_download_plan(plan, uri=uri, split=split, content_digest=content_digest,
236
+ manifest, _, _ = validate_download_plan(plan, uri=uri, split=split, content_digest=content_digest,
222
237
  **({'config': config} if config is not None else {}), **task_selection)
223
238
  except (ANSError, InvalidManifest, ValueError, TypeError, KeyError):
224
239
  raise RemoteError('ASSET_INTEGRITY_FAILED', 409) from None
240
+ timings['plan_validation_seconds'] += time.perf_counter() - before_validation
225
241
  originals = {entry['url']: entry['path'] for entry in plan.get('files', [])}
226
242
  current = {entry['path']: entry['url'] for entry in plan.get('files', [])}
227
243
  pins = [{key: entry[key] for key in ('path','size','sha256','mode')} for entry in plan.get('files', [])]
244
+ files = {entry['path']: {'index': index, 'bytes': 0, 'requests': 0,
245
+ 'connect_seconds': 0.0, 'read_seconds': 0.0}
246
+ for index, entry in enumerate(plan.get('files', []))}
247
+ sizes = {entry['path']: entry['size'] for entry in manifest['files']}
248
+ renewal_lock = threading.Lock()
249
+
250
+ def open_file(path: str, url: str) -> Any:
251
+ row = files[path]
252
+ row['requests'] += 1
253
+ before = time.perf_counter()
254
+ try:
255
+ return self.transport.open_download(url)
256
+ finally:
257
+ row['connect_seconds'] += time.perf_counter() - before
228
258
 
229
- def read(url: str):
259
+ def network_read(url: str):
230
260
  path = originals[url]
261
+ with renewal_lock:
262
+ attempted = current[path]
231
263
  try:
232
- stream = self.transport.open_download(current[path])
264
+ stream = open_file(path, attempted)
233
265
  except RemoteError as error:
234
266
  if error.status_code != 403:
235
267
  raise
236
- renewed = self.transport.request('GET', self._query(endpoint, **(parameters | {'content_digest': plan['content_digest']})))
237
- if (renewed.get('uri') != uri or renewed.get('split') != split
238
- or renewed.get('config') != config
239
- or renewed.get('task_id') != task_id or renewed.get('task_digest') != task_digest
240
- or renewed.get('content_digest') != plan['content_digest']
241
- or [{key: entry.get(key) for key in ('path','size','sha256','mode')}
242
- for entry in renewed.get('files', [])] != pins):
243
- raise RemoteError('ASSET_PIN_CONFLICT', 409)
244
- # EnvHub validates renewed URLs before any storage request.
245
- validate_download_plan(renewed, uri=uri, split=split, content_digest=plan['content_digest'],
246
- **({'config': config} if config is not None else {}), **task_selection)
247
- current.update({entry['path']: entry['url'] for entry in renewed['files']})
248
- stream = self.transport.open_download(current[path])
268
+ with renewal_lock:
269
+ if current[path] == attempted:
270
+ renew()
271
+ replacement = current[path]
272
+ stream = open_file(path, replacement)
249
273
  with stream:
250
- while chunk := stream.read(1024 * 1024):
274
+ while True:
275
+ before = time.perf_counter()
276
+ try:
277
+ chunk = stream.read(1024 * 1024)
278
+ finally:
279
+ files[path]['read_seconds'] += time.perf_counter() - before
280
+ if not chunk:
281
+ break
282
+ files[path]['bytes'] += len(chunk)
283
+ if files[path]['bytes'] > sizes[path]:
284
+ raise RemoteError('ASSET_INTEGRITY_FAILED', 409)
251
285
  yield chunk
252
286
 
287
+ def renew() -> None:
288
+ renewed = query('renew_download_plan', lambda: self.transport.request(
289
+ 'GET', self._query(endpoint, **(parameters | {'content_digest': plan['content_digest']}))))
290
+ if (renewed.get('uri') != uri or renewed.get('split') != split
291
+ or renewed.get('config') != config
292
+ or renewed.get('task_id') != task_id or renewed.get('task_digest') != task_digest
293
+ or renewed.get('content_digest') != plan['content_digest']
294
+ or [{key: entry.get(key) for key in ('path','size','sha256','mode')}
295
+ for entry in renewed.get('files', [])] != pins):
296
+ raise RemoteError('ASSET_PIN_CONFLICT', 409)
297
+ # EnvHub validates renewed URLs before any storage request.
298
+ before_validation = time.perf_counter()
299
+ validate_download_plan(renewed, uri=uri, split=split, content_digest=plan['content_digest'],
300
+ **({'config': config} if config is not None else {}), **task_selection)
301
+ timings['plan_validation_seconds'] += time.perf_counter() - before_validation
302
+ current.update({entry['path']: entry['url'] for entry in renewed['files']})
303
+
304
+ # A bounded look-ahead hides connection latency for directory trees of
305
+ # tiny source files. Large files keep the existing streaming path.
306
+ small_paths = [entry['path'] for entry in manifest['files'] if entry['size'] <= 1024 * 1024]
307
+ parallel = len(small_paths) >= 4
308
+ small = iter(small_paths)
309
+ pending: dict[str, Future[bytes]] = {}
310
+ pool = ThreadPoolExecutor(max_workers=4) if parallel else None
311
+ activated = False
312
+ waiting_seconds = 0.0
313
+
314
+ def fetch_small(url: str) -> bytes:
315
+ return b''.join(network_read(url))
316
+
317
+ def schedule() -> None:
318
+ path = next(small, None)
319
+ if path is not None and pool is not None:
320
+ pending[path] = pool.submit(fetch_small, plan['files'][files[path]['index']]['url'])
321
+
322
+ def read(url: str):
323
+ nonlocal activated, waiting_seconds
324
+ path = originals[url]
325
+ if parallel and not activated:
326
+ # Called only after EnvHub has checked the quota, destination
327
+ # and entire plan. No speculative object requests before that.
328
+ activated = True
329
+ for _ in range(4):
330
+ schedule()
331
+ if path in pending:
332
+ before = time.perf_counter()
333
+ try:
334
+ payload = pending.pop(path).result()
335
+ finally:
336
+ waiting_seconds += time.perf_counter() - before
337
+ schedule()
338
+ yield payload
339
+ return
340
+ source = iter(network_read(url))
341
+ while True:
342
+ before = time.perf_counter()
343
+ try:
344
+ chunk = next(source)
345
+ except StopIteration:
346
+ return
347
+ finally:
348
+ waiting_seconds += time.perf_counter() - before
349
+ yield chunk
350
+
351
+ # This reader owns the four bounded look-ahead workers and its wait
352
+ # clock. New Hub versions also parallelize custom readers by default;
353
+ # keep one materialization coordinator. Older Hub readers are serial.
354
+ materialization_options: dict[str, Any] = (
355
+ {'max_workers': 1} if 'max_workers' in inspect.signature(download_directory).parameters else {})
356
+ materialize_started = time.perf_counter()
357
+ materialize_cpu_started = time.thread_time()
358
+ query_count = len(timings['queries'])
359
+ validation_before_materialize = timings['plan_validation_seconds']
253
360
  try:
254
361
  target = download_directory(plan, Path(destination), uri=uri, split=split, content_digest=content_digest, read_url=read,
255
- **({'config': config} if config is not None else {}), **task_selection)
362
+ **materialization_options, **({'config': config} if config is not None else {}), **task_selection)
256
363
  except (ANSError, InvalidManifest, ValueError, TypeError, KeyError):
257
364
  raise RemoteError('ASSET_INTEGRITY_FAILED', 409) from None
365
+ finally:
366
+ if pool is not None:
367
+ pool.shutdown(wait=True, cancel_futures=True)
368
+ timings['files'] = list(files.values())[:256]
369
+ timings['files_truncated'] = len(files) > 256
370
+ materialize_seconds = time.perf_counter() - materialize_started
371
+ network_seconds = sum(row['connect_seconds'] + row['read_seconds'] for row in files.values())
372
+ renewal_seconds = sum(row['seconds'] for row in timings['queries'][query_count:])
373
+ renewal_validation = timings['plan_validation_seconds'] - validation_before_materialize
374
+ timings['materialize_verify_seconds'] = max(0.0, materialize_seconds - (
375
+ waiting_seconds if parallel else network_seconds + renewal_seconds + renewal_validation))
376
+ timings['materialize_verify_cpu_seconds'] = time.thread_time() - materialize_cpu_started
377
+ timings['network_wait_seconds'] = waiting_seconds
378
+ timings['small_file_workers'] = 4 if parallel else 1
379
+ timings['queries_truncated'] = len(timings['queries']) > 256
380
+ timings['queries'] = timings['queries'][:256]
381
+ timings['total_seconds'] = time.perf_counter() - started
258
382
  return {'ref': uri, 'split': split, 'content_digest': plan['content_digest'],
259
- 'directory': str(target), 'verified': True, **({'config': config} if config is not None else {}), **task_selection}
383
+ 'directory': str(target), 'verified': True, **({'config': config} if config is not None else {}), **task_selection,
384
+ **({'timings': timings} if managed_timings else {})}
260
385
 
261
386
  def create(self, *, type: str, ref: str | None = None, manifest: dict[str, Any] | None = None, files: dict[str, Any] | None = None, model: str | None = None, revision: str | None = None,
262
387
  executables: Sequence[str] = (), dry_run: bool = False, idempotency_key: str | None = None, visibility: str | None = None, wait: bool = True,
@@ -0,0 +1 @@
1
+ """Optional Job chat; install envloop-cli[chat] to load the OpenAI SDK."""
envloop_chat/cli.py ADDED
@@ -0,0 +1,116 @@
1
+ """Single-turn and terminal chat; model traffic stays in the optional SDK module."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ from collections.abc import Generator
6
+ from contextlib import closing
7
+ from pathlib import Path
8
+ from typing import Any, cast
9
+
10
+ from envloop.http import RemoteError
11
+ from envloop.terminal import safe_text
12
+
13
+ from .client import require_dependencies, validate
14
+
15
+
16
+ def register(jobs: Any) -> None:
17
+ parser = jobs.add_parser('chat', help='Chat with an Inference Job (install envloop-cli[chat])')
18
+ parser.add_argument('job_id', metavar='JOB_ID')
19
+ parser.add_argument('prompt', metavar='PROMPT', nargs='?', help='One question; omitted reads stdin or starts terminal chat')
20
+ parser.add_argument('--spec', type=Path, metavar='CHAT.json', help='Chat request JSON; mutually exclusive with prompt/stdin')
21
+ parser.add_argument('--system', help='System message; use messages in --spec instead when supplying a file')
22
+ parser.add_argument('--temperature', type=float)
23
+ parser.add_argument('--max-tokens', type=int)
24
+ parser.add_argument('--timeout-seconds', type=float, default=120, help='Per-request connection/read timeout (default: 120)')
25
+ parser.add_argument('--json', action='store_true', help='Return a complete non-streamed response for one question')
26
+
27
+
28
+ def prepare(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None:
29
+ piped = '' if sys.stdin.isatty() else sys.stdin.read(1024 * 1024 + 1)
30
+ if args.spec is not None and (args.prompt is not None or piped or args.system is not None):
31
+ parser.error('--spec is mutually exclusive with PROMPT, stdin and --system')
32
+ if args.prompt is not None and piped:
33
+ parser.error('provide a question once, as PROMPT or stdin')
34
+ payload: dict[str, Any] = {}
35
+ if args.spec is not None:
36
+ try:
37
+ with args.spec.open(encoding='utf-8') as source:
38
+ raw = source.read(1024 * 1024 + 1)
39
+ if len(raw.encode()) > 1024 * 1024:
40
+ raise ValueError
41
+ payload = json.loads(raw)
42
+ if not isinstance(payload, dict) or 'messages' not in payload:
43
+ raise ValueError
44
+ except (OSError, UnicodeError, ValueError):
45
+ parser.error('--spec requires a readable chat JSON object smaller than 1 MiB with messages')
46
+ args.chat_interactive = args.prompt is None and args.spec is None and sys.stdin.isatty()
47
+ if args.chat_interactive and args.json:
48
+ parser.error('--json requires PROMPT, stdin or --spec')
49
+ if not payload:
50
+ messages = [{'role': 'system', 'content': args.system}] if args.system is not None else []
51
+ if not args.chat_interactive:
52
+ prompt = args.prompt if args.prompt is not None else piped
53
+ if not prompt.strip():
54
+ parser.error('chat requires a non-empty question')
55
+ messages.append({'role': 'user', 'content': prompt})
56
+ payload['messages'] = messages
57
+ if 'stream' in payload:
58
+ parser.error('omit stream from --spec; text output streams and --json returns a complete response')
59
+ for field in ('temperature', 'max_tokens'):
60
+ if (value := getattr(args, field)) is not None:
61
+ payload[field] = value
62
+ try:
63
+ validate([{'role': 'user', 'content': 'validation'}] if args.chat_interactive else payload['messages'], args.timeout_seconds,
64
+ {k: v for k, v in payload.items() if k != 'messages'})
65
+ except (ValueError, TypeError):
66
+ parser.error('chat requires valid messages, sampling parameters and a finite positive timeout')
67
+ args.chat_payload = payload
68
+
69
+
70
+ def _answer(jobs: Any, job_id: str, payload: dict[str, Any], timeout_seconds: float) -> str:
71
+ text: list[str] = []
72
+ iterator = cast(Generator[dict[str, Any], None, None], jobs.chat(job_id, stream=True, timeout_seconds=timeout_seconds, **payload))
73
+ with closing(iterator):
74
+ for chunk in iterator:
75
+ for choice in chunk['choices']:
76
+ delta = choice['delta']
77
+ if delta.get('tool_calls') or delta.get('function_call'):
78
+ raise RemoteError('CHAT_TEXT_UNAVAILABLE')
79
+ content = delta.get('content')
80
+ if content is not None and not isinstance(content, str):
81
+ raise RemoteError('INVALID_RESPONSE')
82
+ if content:
83
+ text.append(content)
84
+ print(safe_text(content), end='', flush=True)
85
+ if not text:
86
+ raise RemoteError('CHAT_TEXT_UNAVAILABLE')
87
+ print(flush=True)
88
+ return ''.join(text)
89
+
90
+
91
+ def run(args: argparse.Namespace, client: Any) -> int:
92
+ require_dependencies()
93
+ payload = args.chat_payload
94
+ if not args.chat_interactive:
95
+ if args.json:
96
+ response = client.jobs.chat(args.job_id, timeout_seconds=args.timeout_seconds, **payload)
97
+ print(json.dumps(response, ensure_ascii=False))
98
+ else:
99
+ _answer(client.jobs, args.job_id, payload, args.timeout_seconds)
100
+ return 0
101
+ history = list(payload['messages'])
102
+ initial = list(history)
103
+ print('Enter a message. /clear resets history; /exit, Ctrl+D or Ctrl+C exits. The Job stays running.', file=sys.stderr)
104
+ while True:
105
+ print('You> ', end='', file=sys.stderr, flush=True)
106
+ line = sys.stdin.readline()
107
+ if not line or line.strip() == '/exit':
108
+ return 0
109
+ if line.strip() == '/clear':
110
+ history = list(initial)
111
+ continue
112
+ if not line.strip():
113
+ continue
114
+ messages = [*history, {'role': 'user', 'content': line.rstrip('\n')}]
115
+ answer = _answer(client.jobs, args.job_id, {**payload, 'messages': messages}, args.timeout_seconds)
116
+ history = [*messages, {'role': 'assistant', 'content': answer}]
envloop_chat/client.py ADDED
@@ -0,0 +1,146 @@
1
+ """Job-bound OpenAI-compatible chat with explicit EnvLoop authentication."""
2
+ import copy
3
+ import importlib.util
4
+ import json
5
+ import math
6
+ import re
7
+ from collections.abc import Generator
8
+ from typing import TYPE_CHECKING, Any, cast, override
9
+ from urllib.parse import quote
10
+
11
+ from envloop._optional import MissingFeatureError
12
+ from envloop.http import USER_AGENT, HttpService, RemoteError, retry_after_seconds
13
+
14
+ if TYPE_CHECKING:
15
+ from openai.types.chat import ChatCompletionMessageParam
16
+
17
+
18
+ def require_dependencies() -> None:
19
+ if importlib.util.find_spec('openai') is None:
20
+ raise MissingFeatureError('chat')
21
+
22
+
23
+ def validate(messages: Any, timeout_seconds: float, options: dict[str, Any]) -> None:
24
+ if (not isinstance(messages, list) or not messages or any(not isinstance(m, dict)
25
+ or m.get('role') not in {'system', 'developer', 'user', 'assistant', 'tool', 'function'} for m in messages)):
26
+ raise ValueError('chat requires a non-empty messages array with valid roles')
27
+ if isinstance(timeout_seconds, bool) or not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
28
+ raise ValueError('chat timeout_seconds must be finite and positive')
29
+ if options.get('n', 1) != 1:
30
+ raise ValueError('chat supports one completion per request')
31
+ if 'max_tokens' in options and (type(options['max_tokens']) is not int or options['max_tokens'] <= 0):
32
+ raise ValueError('max_tokens must be a positive integer')
33
+ if 'temperature' in options:
34
+ value = options['temperature']
35
+ if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
36
+ raise ValueError('temperature must be finite and nonnegative')
37
+ if set(options) & {'extra_body', 'extra_headers', 'extra_query', 'base_url', 'api_key', 'timeout'}:
38
+ raise ValueError('chat connection settings come from the EnvLoop client')
39
+ try:
40
+ if len(json.dumps({'messages': messages, **options}, allow_nan=False).encode()) > 1024 * 1024 - 1024:
41
+ raise ValueError
42
+ except (ValueError, TypeError):
43
+ raise ValueError('chat request must be JSON and smaller than 1 MiB') from None
44
+
45
+
46
+ def _error(error: Exception) -> RemoteError:
47
+ from openai import (
48
+ APIConnectionError,
49
+ APIError,
50
+ APIResponseValidationError,
51
+ APIStatusError,
52
+ APITimeoutError,
53
+ )
54
+
55
+ if isinstance(error, APITimeoutError):
56
+ return RemoteError('REQUEST_TIMEOUT')
57
+ if isinstance(error, APIStatusError):
58
+ code = error.code
59
+ # Never retain arbitrary provider text, request bodies or exception messages.
60
+ safe = code if isinstance(code, str) and re.fullmatch(r'[A-Z][A-Z0-9_]{0,127}', code) else 'HTTP_ERROR'
61
+ return RemoteError(safe, error.status_code,
62
+ retry_after=retry_after_seconds(error.response.headers.get('Retry-After')))
63
+ if isinstance(error, APIConnectionError):
64
+ return RemoteError('NETWORK_ERROR')
65
+ if isinstance(error, APIResponseValidationError):
66
+ return RemoteError('INVALID_RESPONSE')
67
+ if isinstance(error, APIError):
68
+ return RemoteError('MODEL_CONNECTION_FAILED')
69
+ return RemoteError('INVALID_RESPONSE')
70
+
71
+
72
+ def _stream(connection: Any, model: str, messages: list[dict[str, Any]], options: dict[str, Any]) -> Generator[dict[str, Any], None, None]:
73
+ finished = False
74
+ try:
75
+ with connection, connection.chat.completions.create(
76
+ model=model, messages=messages, stream=True, extra_body=options) as response:
77
+ for event in response:
78
+ value = event.model_dump(mode='json')
79
+ choices = value.get('choices')
80
+ if not isinstance(choices, list):
81
+ raise RemoteError('INVALID_RESPONSE')
82
+ for choice in choices:
83
+ if not isinstance(choice, dict) or not isinstance(choice.get('delta'), dict):
84
+ raise RemoteError('INVALID_RESPONSE')
85
+ if choice.get('finish_reason') is not None:
86
+ finished = True
87
+ yield value
88
+ if not finished:
89
+ raise RemoteError('RESPONSE_INTERRUPTED')
90
+ except RemoteError:
91
+ raise
92
+ except Exception as error:
93
+ raise _error(error) from None
94
+
95
+
96
+ def chat(server: Any, job_id: str, *, messages: list[dict[str, Any]], stream: bool = False,
97
+ timeout_seconds: float = 120, **options: Any) -> dict[str, Any] | Generator[dict[str, Any], None, None]:
98
+ require_dependencies()
99
+ validate(messages, timeout_seconds, options)
100
+ if not isinstance(job_id, str) or not job_id.strip() or type(stream) is not bool:
101
+ raise ValueError('chat requires a Job ID and a boolean stream option')
102
+ if not isinstance(server, HttpService):
103
+ raise ValueError('chat requires Client.remote with an EnvLoop API connection')
104
+ query = copy.copy(server)
105
+ query.timeout = timeout_seconds
106
+ job = query.request('GET', '/v1/jobs/' + quote(job_id, safe=''))
107
+ if not isinstance(job, dict) or job.get('job_id') != job_id or job.get('type') != 'inference':
108
+ raise ValueError('chat requires an Inference Job')
109
+ inference = job.get('inference') or {}
110
+ if not isinstance(inference, dict) or inference.get('service_status') != 'READY':
111
+ raise RemoteError('ENDPOINT_NOT_READY')
112
+ model = inference.get('model')
113
+ if not isinstance(model, str) or not model:
114
+ raise RemoteError('INVALID_RESPONSE')
115
+ if options.pop('model', model) != model:
116
+ raise ValueError('chat model must match the Inference Job model')
117
+ from openai import DefaultHttpxClient, OpenAI
118
+
119
+ class JobOpenAI(OpenAI):
120
+ @property
121
+ @override
122
+ def default_headers(self) -> dict[str, Any]:
123
+ # The SDK merges OPENAI_CUSTOM_HEADERS into defaults even when a Key is
124
+ # explicit. Only the EnvLoop connection owns headers for this client.
125
+ return {'Accept': 'application/json', 'User-Agent': USER_AGENT, **server.headers}
126
+
127
+ connection = JobOpenAI(base_url=server.base + '/v1/jobs/' + quote(job_id, safe='') + '/inference',
128
+ api_key=server.secret or '', admin_api_key='', organization='', project='', max_retries=0,
129
+ timeout=timeout_seconds, default_headers=dict(server.headers),
130
+ _strict_response_validation=True,
131
+ http_client=DefaultHttpxClient(follow_redirects=False, trust_env=False))
132
+ if stream:
133
+ return _stream(connection, model, messages, options)
134
+ try:
135
+ with connection:
136
+ result = connection.chat.completions.create(model=model, messages=cast('list[ChatCompletionMessageParam]', messages),
137
+ stream=False, extra_body=options)
138
+ value = result.model_dump(mode='json')
139
+ if (not isinstance(value.get('choices'), list) or not value['choices']
140
+ or any(choice.get('finish_reason') is None for choice in value['choices'])):
141
+ raise RemoteError('INVALID_RESPONSE')
142
+ return value
143
+ except RemoteError:
144
+ raise
145
+ except Exception as error:
146
+ raise _error(error) from None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: envloop-cli
3
- Version: 2.0.0
3
+ Version: 2.1.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
@@ -11,6 +11,8 @@ Requires-Python: >=3.12
11
11
  Provides-Extra: asset
12
12
  Requires-Dist: boto3==1.44.3; extra == 'asset'
13
13
  Requires-Dist: envloop-envhub==1.23.0; extra == 'asset'
14
+ Provides-Extra: chat
15
+ Requires-Dist: openai==3.55.1; extra == 'chat'
14
16
  Provides-Extra: default
15
17
  Provides-Extra: experiment
16
18
  Provides-Extra: rsi-loop
@@ -33,6 +35,7 @@ unreleased features.
33
35
 
34
36
  | Unreleased source enhancement | Published 1.33.0 |
35
37
  | --- | --- |
38
+ | `el job chat JOB_ID [PROMPT]` and the `chat` extra | not available |
36
39
  | Explicit `--json` for `el runner get\|create\|update\|delete` | These commands already output JSON; omit `--json` |
37
40
  | `el dataset create --format harbor --update-digests` | not available; set `[[tasks]] digest` values by hand |
38
41
  | `el trial artifact download TRIAL_ID --output DIRECTORY` | positional `DIRECTORY` only |
@@ -104,6 +107,21 @@ python -m pip install "envloop-cli[asset]"
104
107
 
105
108
  ## Connect
106
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
+
107
125
  Use an authorized EnvLoop account and project. Browser authorization:
108
126
 
109
127
  ```bash
@@ -215,14 +233,19 @@ Sandbox Job without a Dataset:
215
233
  ```bash
216
234
  el job submit --type sandbox --runner base --command 'python --version'
217
235
  el job submit --type sandbox --runner base --image python:3.11 --wait
236
+ el job submit --type sandbox --provider e2b --spec REQUEST.json
218
237
  el job list --type sandbox
219
238
  el job log JOB_ID --follow
220
239
  ```
221
240
 
222
241
  The platform resolves `base` to the registered `envloop/base@main` source ref and
223
242
  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.
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.
226
249
  Failures include a code, readable explanation, HTTP status when available, and
227
250
  recovery guidance without echoing arbitrary response bodies or credentials.
228
251
 
@@ -3,13 +3,13 @@ envloop/_optional.py,sha256=u3BAnO7_POlD3b5ZK3iDXJwefe7MySSj4DcoOqaQGPk,9799
3
3
  envloop/auth_cli.py,sha256=xxMxvsBeeIRht0fWaXSV7tstMKlCzqBBVBcXEvNpwGU,17874
4
4
  envloop/auth_login.py,sha256=uOqPHqgzi0Y5eDMiZJH-EI_HxY55F9bRr8CoBb8OHfk,7231
5
5
  envloop/auth_workspace.py,sha256=g92Dok4eSp6P-Du5qkwzZG4JDeSrdYTXJbn5WCzCFMo,14927
6
- envloop/cli.py,sha256=2RT9fLF2fIjt6y9QOXXkS3Yr7XaVXkh7ukFZsnh5lc8,16007
7
- envloop/cli_errors.py,sha256=6PUwwGw_ipp9IP2oimjHvrv3sukycn-1RaScTefBnC8,47819
6
+ envloop/cli.py,sha256=aOgpG-JnBvjviBOizqgQQhm8by8EZvSJblNKebLhTVc,16165
7
+ envloop/cli_errors.py,sha256=_1ZvVu69fyrVZYz7aD-PPFa7R7iEfGZvONO52bfhC1E,48392
8
8
  envloop/cli_output.py,sha256=s5LwMHhDIbD6cqvmRYvIFTkgGehbUe4NJcmf6R-8BV0,6135
9
9
  envloop/client.py,sha256=Bj0oY1NPPRWpf5IOnXmoWKIKPXusUsrMK-IXOwcEgME,3293
10
10
  envloop/config.py,sha256=1Wr2lNdNNZzsQDPNGsk-TsnEUvDqOtocy9TgUpmOZO0,22494
11
11
  envloop/downloads.py,sha256=ADeNSbiWBOwOxQ19w-KRwdSzvsiPKy1ZT7s9BR_jf-s,3335
12
- envloop/http.py,sha256=dVoApg2dqRQXA-QV4BGKIV_8vlAm2bBLVqfSbQYlaM4,21514
12
+ envloop/http.py,sha256=MAlhC7pVfMrSU1B-VWGLW9Svxek0aBTTXbhrt09LWrc,21642
13
13
  envloop/lifecycle_cli.py,sha256=YwudbcpolVdYOcNcyCztTEEJOWUXNqDqHSjJCNDILvg,7814
14
14
  envloop/navigation_resources.py,sha256=vH9jmrfiYARl5kugFAgWzH2b5NXo5SxEi8X0OAyT6jQ,10382
15
15
  envloop/profile_secrets.py,sha256=A0i-mB7Mg3qclqQAtJXjvOcYnwvMyURwR8tubBh4R0E,9636
@@ -19,7 +19,7 @@ envloop/terminal.py,sha256=YcUXw0qfLki0I10Ul3nF73pylq-OJ4SJMPh_FMV0kZE,3698
19
19
  envloop/utils/__init__.py,sha256=huB3qPQuKNr3JxfH3Ys09YWFtHiDamCHFsBa4epANgQ,25
20
20
  envloop/utils/logging.py,sha256=rXN0qyxhfGEq4vWXxjwfaczPPZf_7atnOkkBTgNNRPc,1017
21
21
  envloop_asset/__init__.py,sha256=nKDGmzFNAQv2mq16YijiI3Q-gDL_smNyZD-AQaqoz7Y,68
22
- envloop_asset/assets.py,sha256=aO27UX8b_Vvw2YgLy5xGbO9ALfM0SjPXBlcfpJ1P-vM,31640
22
+ envloop_asset/assets.py,sha256=12S_SP5GY-4Sf1dyBaFA_gHEUEwu8qq784yORC3YlG8,32127
23
23
  envloop_asset/checkpoint_download.py,sha256=86pq8IXoJCEP6dVaLtgocp8b8rTyuEccK_ecOQLGiec,4622
24
24
  envloop_asset/checkpoint_upload.py,sha256=BwvLDb862B15MJGjr1lTTu8H6GIyDN5wsVcyoD30WRA,5317
25
25
  envloop_asset/cli.py,sha256=mISKgX1xz6UjSwP_4TQeOm89ugmcKctsZUC9DpWpcIw,3776
@@ -27,9 +27,9 @@ envloop_asset/cli_output.py,sha256=cdHvncKxHnLpKp7-QaNAFFaaWEI6AO-wgTpHMbSopYI,5
27
27
  envloop_asset/client.py,sha256=QJvs617WFCD67-r9R8VC1Dx5-1yaa6z0Bs_eSqVnTUA,20306
28
28
  envloop_asset/dataset_upload.py,sha256=G1lwQvqsqD5d-U80hYzCb83dvfPz73Yg4_7JKh3Mrys,19574
29
29
  envloop_asset/direct_artifact.py,sha256=1564EPw64MbGiUfMGRFfqHvyocxwA0gx1V5lhaH-jhM,10774
30
- envloop_asset/direct_checkpoint.py,sha256=kXUGGa2QPY2Ir2Ij741Cyq0i0hbDd8szzV6A7qa5PwY,6711
31
- envloop_asset/direct_publication.py,sha256=sAqZBSl2dJ2iCucT_R7uVy_retggypI_b98_k3wzGog,1877
32
- envloop_asset/direct_storage.py,sha256=hHf9uaA8bWbZj-XmzID40J5-QZlHyzO2pXXfs26d5cI,13026
30
+ envloop_asset/direct_checkpoint.py,sha256=sL00wpBfax75G5hYzwJimZ4hE2BeRbpOUntzWEoM9Yw,8718
31
+ envloop_asset/direct_publication.py,sha256=zKBoAWnR6CGzdvsKS5ZZPLWAFDwiC0VFHLp9TxYE2O4,4103
32
+ envloop_asset/direct_storage.py,sha256=z3dZFlrPUFbLzOWVbN4PS1R_kHYkdJXjvIz0QsJjY70,13207
33
33
  envloop_asset/direct_worker_artifact.py,sha256=LS5SuglxglbrkDxbr8AhLvJ5KFS1IWKAG5bprqKcd1Q,4631
34
34
  envloop_asset/execution_content.py,sha256=rP_blkZet1ZualA--a7vwZnz1r5jwD87mFtyDN7S3cQ,916
35
35
  envloop_asset/http.py,sha256=v0gLHZFnsjaPnx5Jg3I-ktn-O7rCPu8UnB10zEGhMqg,7965
@@ -40,22 +40,25 @@ envloop_asset/publications.py,sha256=Xn794hX1n7nHwqQJzOzlmFFgIlA9h1XNDRAm5DZiBJM
40
40
  envloop_asset/r2_upload.py,sha256=m-L1Z7L7fQvJNVA9pGzwSGGOTv1_COC5OVSjUIQfxMU,1605
41
41
  envloop_asset/recipe_packages.py,sha256=S2MIIhqitZQjB822PPXlpNIfpCGGBa-6nA9hlhkKtKk,5961
42
42
  envloop_asset/recipes.py,sha256=We2TZWdRl-ialV-uLFvUSvJng9P2HGquqGtqKYKllgs,1442
43
- envloop_asset/resource_cli.py,sha256=A34EqeYXWNJSAjfTft4tYEGckl5bERWitNa7UwMij2o,20916
43
+ envloop_asset/resource_cli.py,sha256=JIbgXG1UY8JsvrcaeGFFMVpL4F5vu3M-Wue6EN6d2w8,20946
44
44
  envloop_asset/runner_packages.py,sha256=ZY6XWI3yCwsrVnyeq8xXP46uc59s7WqajR0_qNGH6U4,5474
45
- envloop_asset/tags.py,sha256=rVTgSfG6aE2cHkOAa3CUjW-gr8HYzJqydOhL0f4ugKE,1154
46
- envloop_asset/transfer.py,sha256=tt3AENww-6fZC5iJYZwhP6O7F-flZOm_QLXWd6oNXoM,47035
45
+ envloop_asset/tags.py,sha256=wFP0Rg-avOmYkpyYqNGdJrnGreHEli-O5_eH9Liat6c,2016
46
+ envloop_asset/transfer.py,sha256=OK__2bDd_Yiy1FRgVaWuKSOl_ss1KBUp9FWtXEvJ99E,53161
47
47
  envloop_asset/upload_strategy.py,sha256=RP-mNtM4yHQ0YmwocsTKD7MOS2asCoWnI44AtCI9LVw,605
48
+ envloop_chat/__init__.py,sha256=pEW8SHBlrQr2_9UFm45unSUg-GP6rY04V3O27bspOuQ,75
49
+ envloop_chat/cli.py,sha256=aUoflpsBWl-U4vrzZP4xsZrvc0md-zuSsCB6APeIk8Q,5783
50
+ envloop_chat/client.py,sha256=CUCG0jBXJplsXsDNOdu-R-v9O-dVrMMVycNMZUS5b9M,7215
48
51
  envloop_experiment/__init__.py,sha256=nKDGmzFNAQv2mq16YijiI3Q-gDL_smNyZD-AQaqoz7Y,68
49
- envloop_experiment/cli.py,sha256=zI1M3b--_zTKUTIviqSEz1rDjlhvRoprJbBDyVZVkwo,42936
52
+ envloop_experiment/cli.py,sha256=kWXlcY_cznUB3D1y6OInkZebjBa0fjQ6V9ciWtkOiAY,43336
50
53
  envloop_experiment/cli_output.py,sha256=aM6eajuMDheWb2GA956UE0_y-6_tC0MCdC23ulROHi4,5196
51
- envloop_experiment/client.py,sha256=7NnO8lohNC39aDbYN_0_aZRQ8qOer7E2-wGJBEHcidM,41102
54
+ envloop_experiment/client.py,sha256=XKoeoIz4OZgbLh55CqvZmnWKEcnk-jMsI6XQ9SQHTC8,41757
52
55
  envloop_experiment/decision.py,sha256=HJTj-jSJJ5kcxQQzFXwrA9IICWXA6zSNBFL9EbbrxqI,918
53
- envloop_experiment/http.py,sha256=wCLiLBsGVEcxE2LX9PSyyNX_atGN0vAaFgUBax-9INQ,7063
56
+ envloop_experiment/http.py,sha256=wQ81Pz_daVRGFDIZQnIgTKRyOWWBgxF8xi4kM9UE6tQ,6970
54
57
  envloop_experiment/inference.py,sha256=qSObsdo9suHhG5i_xlCh6-lt-NJkhQzAoF9KzCdVWws,5640
55
58
  envloop_experiment/job_cost.py,sha256=gZB69-pdsJM4wManw44AIS9T3ZtsxxQTqrJs-cHjwJU,2214
56
59
  envloop_experiment/job_logs.py,sha256=RLipbj89e5hQdBeXtszsxSYYw7By1hscwSTGFQzQ3Qw,1340
57
- envloop_experiment/job_spec_cli.py,sha256=m07IqYw84chkZt9YfapW1ZitApwH95SYcpKjbTJbNC8,14358
58
- envloop_experiment/named_profile.py,sha256=U8_gbHAwKhvApLFYjgyfNzv14SmRs_Ez02hpQi61fhg,9181
60
+ envloop_experiment/job_spec_cli.py,sha256=2q-_Txt0xkeBEjeWfoY9tkWhJnf2ZNhueAk9s4ahNYQ,14468
61
+ envloop_experiment/named_profile.py,sha256=niaJm3WZPH98PNfqpN8RMg18AO5zWTlI88rOnJ2DgSY,9349
59
62
  envloop_experiment/navigation_resources.py,sha256=sbatQySVNKftZZ-HKU1mwihoJWaTPYGeLO_dJLr2EHY,1755
60
63
  envloop_experiment/resource_cli.py,sha256=BfzQrvaq_Y_EL1OQUSxYtlWhf_SdTwJyU2omxFccn-g,2002
61
64
  envloop_experiment/resources.py,sha256=m-kAHFklU9idPg2RtLUoyPBoiIyfl1lECxnu--spdTU,7142
@@ -72,7 +75,7 @@ envloop_rsi_loop/cli.py,sha256=egat_Keygh9V1VAYgfEmqBKDmntCWe7ES_SFjhh26Yg,4102
72
75
  envloop_rsi_loop/cli_output.py,sha256=o5XzAkcddBOZ2h_AQ-pUPqJIWUOIMfZPWaPxqm0AtUM,4840
73
76
  envloop_rsi_loop/loop_cli.py,sha256=V_LEyWTsps2G1UNuMiWhrDDRdO0H4Z1bXGuWsYTOo0c,4491
74
77
  envloop_rsi_loop/loops.py,sha256=MGVe3uXxGlnzT_Sc7OHU97kyYA_FSFpXIUtlpXQ8ha0,8924
75
- envloop_cli-2.0.0.dist-info/METADATA,sha256=lrDYKgOba_itPlCcgWvMMoOAxxKrr2nTJeW_oQb2wFw,21670
76
- envloop_cli-2.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
77
- envloop_cli-2.0.0.dist-info/entry_points.txt,sha256=8aXOpgtVk4GndhChA4XNecShkb1w0xGHBHrKla78ofI,67
78
- envloop_cli-2.0.0.dist-info/RECORD,,
78
+ envloop_cli-2.1.0.dist-info/METADATA,sha256=aw0BZHd1UhFjz9apkQky6oecRzX7WpSn6QVideTN7qw,22759
79
+ envloop_cli-2.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
80
+ envloop_cli-2.1.0.dist-info/entry_points.txt,sha256=8aXOpgtVk4GndhChA4XNecShkb1w0xGHBHrKla78ofI,67
81
+ envloop_cli-2.1.0.dist-info/RECORD,,
envloop_experiment/cli.py CHANGED
@@ -112,7 +112,8 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]"):
112
112
  jobs = groups.add_parser("job", help="Submit and manage Bench, Sandbox, Train and Inference Jobs").add_subparsers(dest="action", required=True)
113
113
  job_submit = jobs.add_parser("submit", help="Submit an Bench, Sandbox, Train or Inference Job", allow_abbrev=False)
114
114
  job_submit.add_argument("--type", choices=("bench", "sandbox", "train", "inference"), default=None, help="Job type (default: spec type, otherwise bench)")
115
- job_submit.add_argument("--provider", choices=("local",), help="Sandbox only: explicitly use the server-enabled local provider for local testing")
115
+ job_submit.add_argument("--provider", metavar="NAME",
116
+ help="Request a Bench/Sandbox provider by name. The connected platform validates the selection.")
116
117
  job_submit.add_argument("--image", metavar="IMAGE", help="Sandbox image override (default: registered Runner image); Train Runner: public spelling of --docker")
117
118
  from envloop_experiment.train_runner_cli import memory_mebibytes, positive_integer
118
119
 
@@ -211,6 +212,8 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]"):
211
212
  decision.add_argument("job_id", metavar="JOB_ID")
212
213
  decision.add_argument("--model", required=True)
213
214
  decision.add_argument("--spec", type=Path, required=True, metavar="PAYLOAD.json")
215
+ from envloop_chat.cli import register as register_chat
216
+ register_chat(jobs)
214
217
  from envloop_experiment.resource_cli import add_job_resources
215
218
  add_job_resources(jobs)
216
219
  listing = jobs.add_parser("list")
@@ -294,6 +297,9 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]"):
294
297
  command.add_argument('--json', action='store_true')
295
298
 
296
299
  def validate(args: argparse.Namespace, cli: argparse.ArgumentParser):
300
+ if args.group == 'job' and args.action == 'chat':
301
+ from envloop_chat.cli import prepare
302
+ prepare(args, args._help_parser)
297
303
  if args.group == 'trial' and args.action == 'artifact':
298
304
  if args.artifact_action == 'download' and (args.trial_id is None) == (args.ref is None):
299
305
  cli.error('give exactly one TRIAL_ID or --ref REF')
@@ -369,8 +375,8 @@ def validate(args: argparse.Namespace, cli: argparse.ArgumentParser):
369
375
  cli.error('--harbor_env applies only to Bench/Sandbox Jobs')
370
376
  if any(key.lower() == 'harbor_env' for key in (getattr(args, 'named_parameters', None) or {})):
371
377
  cli.error('--harbor_env and --params cannot both set harbor_env')
372
- if args.provider is not None and args.type != 'sandbox':
373
- cli.error('--provider local requires --type sandbox')
378
+ if args.provider is not None and args.type not in {'bench', 'sandbox'}:
379
+ cli.error('--provider requires a Bench/Sandbox Job')
374
380
  named_mode = args.spec is None and args.profile is not None and (
375
381
  args.type in {'train', 'sandbox'} or args.type == 'bench' and (
376
382
  bool(args.input) or all(getattr(args,key,None) is None for key in ('dataset','dataset_option','source','runner','task_id','seed'))))
@@ -379,7 +385,7 @@ def validate(args: argparse.Namespace, cli: argparse.ArgumentParser):
379
385
  if named_mode:
380
386
  incompatible = ('dataset', 'dataset_option', 'source', 'task_id', 'revision',
381
387
  'runner', 'job_id', 'tag', 'priority', 'attempts', 'seed', 'command',
382
- 'image', 'delete_delay_seconds', 'timeout_seconds', 'provider',
388
+ 'image', 'delete_delay_seconds', 'timeout_seconds',
383
389
  *(SHORTCUT_FIELDS if args.type == 'train' else TRAIN_ONLY_FIELDS))
384
390
  if any(getattr(args, key, None) is not None for key in incompatible):
385
391
  cli.error('Named Profiles accept --input with Dataset config/split, --params, --request-id and --max-cost-usd, '
@@ -393,7 +399,7 @@ def validate(args: argparse.Namespace, cli: argparse.ArgumentParser):
393
399
  args.named_request = submission(args.profile, type=args.type, inputs=inputs,
394
400
  parameters=getattr(args, 'named_parameters', None), request_id=args.request_id,
395
401
  budget={'max_cost_usd': args.max_cost_usd} if args.max_cost_usd is not None else None,
396
- resources=requested_resources(args) or None)
402
+ resources=requested_resources(args) or None, provider=args.provider)
397
403
  if args.harbor_env is not None:
398
404
  args.named_request['parameters']['harbor_env'] = args.harbor_env
399
405
  except (TypeError, ValueError) as exc:
@@ -551,6 +557,9 @@ def execute_job(args: argparse.Namespace, client: Any, cli: argparse.ArgumentPar
551
557
  # success, like a failed one; the JSON on stdout says why (error, cost).
552
558
  print(json.dumps(result, ensure_ascii=False))
553
559
  raise CommandExit(1)
560
+ elif args.action == 'chat':
561
+ from envloop_chat.cli import run
562
+ raise CommandExit(run(args, client))
554
563
  elif args.action == "decision":
555
564
  result = client.decision.evaluate(args.job_id, model=args.model, payload=args.payload)
556
565
  elif args.action == 'resolve':
@@ -10,7 +10,7 @@ from urllib.parse import urlencode
10
10
  from uuid import uuid4
11
11
 
12
12
  from envloop.downloads import ArtifactError, artifact_path, download_file
13
- from envloop.http import RemoteError
13
+ from envloop.http import RemoteError, validate_public_execution
14
14
  from envloop.utils.logging import get_logger
15
15
 
16
16
  logger = get_logger(__name__)
@@ -426,6 +426,14 @@ class Jobs:
426
426
  from .http import configure_transport
427
427
  configure_transport(self._server)
428
428
 
429
+ def chat(self, job_id: str, *, messages: list[dict[str, Any]], stream: bool = False,
430
+ timeout_seconds: float = 120, **options: Any):
431
+ """Chat with this Inference Job; install envloop-cli[chat]. Close streamed iterators on early exit."""
432
+ from envloop_chat.client import chat
433
+
434
+ return chat(self._server, job_id, messages=messages, stream=stream,
435
+ timeout_seconds=timeout_seconds, **options)
436
+
429
437
  def submit(self, dataset: str | Mapping[str, Any] | None = None, *, source: Any = None,
430
438
  task_ref: Mapping[str, Any] | None = None, task_id: str | None = None,
431
439
  request_id: str | None = None, attempts: int = 1, namespace: str | None = None,
@@ -447,6 +455,7 @@ class Jobs:
447
455
  ``error=BUDGET_EXCEEDED`` when it is reached and its result reports ``cost``.
448
456
  ``resources`` (``cpus``, ``memory_mb``, ``storage_mb``, ``gpus``) overrides the Runner and
449
457
  Profile shape of each Trial for this Job.
458
+ Bench/Sandbox Jobs can request a ``provider`` name. The connected platform validates the selection.
450
459
  """
451
460
  if type not in {'bench', 'sandbox'}:
452
461
  raise ValueError('Jobs.submit type must be bench or sandbox; use training_jobs.submit for train')
@@ -454,13 +463,14 @@ class Jobs:
454
463
  options['profile'] = dict(profile)
455
464
  profile = None
456
465
  if profile is not None:
466
+ provider = options.pop('provider', None)
457
467
  if (any(value is not None for value in (dataset, source, task_ref, task_id, namespace, config, split,
458
468
  revision, runner, profile_id, job_id, tag, command, source_job_id, source_trial_id, image, params))
459
469
  or attempts != 1 or queue_id != 'default' or priority != 0 or options):
460
470
  raise ValueError('Named Profiles accept inputs, parameters, request_id and max_cost_usd; execution is frozen by the Profile')
461
471
  return self.submit_profile(profile, type=type, inputs=inputs, parameters=parameters, request_id=request_id,
462
472
  budget=job_budget(max_cost_usd) if max_cost_usd is not None else None,
463
- resources=resources)
473
+ resources=resources, provider=provider)
464
474
  if inputs is not None or parameters is not None:
465
475
  raise ValueError('inputs and parameters require a named profile')
466
476
  if image is not None and type != 'sandbox':
@@ -481,7 +491,6 @@ class Jobs:
481
491
  if resources is not None:
482
492
  options['resources'] = job_resources(resources)
483
493
  if type == 'sandbox':
484
- from envloop.http import validate_public_execution
485
494
  from envloop_experiment.sandbox import (
486
495
  sandbox_runner_selector,
487
496
  validate_image,
@@ -553,7 +562,10 @@ class Jobs:
553
562
  return job
554
563
 
555
564
  def submit_spec(self, body: dict[str, Any], *, params: Mapping[str, Any] | None = None):
556
- """Submit a canonical four-type JobSpec envelope or a Bench/Sandbox request in the legacy shape."""
565
+ """Submit a canonical four-type JobSpec envelope or a Bench/Sandbox request in the legacy shape.
566
+
567
+ Explicit Bench/Sandbox provider selection belongs at the top level of either request shape.
568
+ """
557
569
  if isinstance(body, dict) and isinstance(body.get("spec"), dict) and 'schema' in body['spec']:
558
570
  if body['spec']['schema'] != 'envloop.job/v2':
559
571
  raise ValueError('New submissions require envloop.job/v2; use bench for evaluation')
@@ -567,9 +579,7 @@ class Jobs:
567
579
  body = deepcopy(body)
568
580
  overrides = body.setdefault("overrides", {})
569
581
  overrides["params"] = {**overrides.get("params", {}), **deepcopy(dict(params))}
570
- from envloop.http import validate_public_execution
571
- validate_public_execution(body['spec'], allow_local_sandbox=False)
572
- validate_public_execution(body.get('overrides'), allow_local_sandbox=False)
582
+ validate_public_execution(body)
573
583
  request_id = body.get('request_id', str(uuid4()))
574
584
  if not isinstance(request_id, str) or not request_id.strip() or len(request_id) > 128:
575
585
  raise ValueError('request_id must be a non-empty string of at most 128 characters')
@@ -582,7 +592,9 @@ class Jobs:
582
592
  request_id = body.get('request_id', str(uuid4()))
583
593
  if not isinstance(request_id, str) or not request_id.strip() or len(request_id) > 128:
584
594
  raise ValueError('request_id must be a non-empty string of at most 128 characters')
585
- return self._server.submit_job({'type': 'bench', 'request_id': request_id, **body})
595
+ request = {'type': 'bench', 'request_id': request_id, **body}
596
+ validate_public_execution(request)
597
+ return self._server.submit_job(request)
586
598
 
587
599
  def resolve(self, spec: Mapping[str, Any]) -> dict[str, Any]:
588
600
  """Resolve an ``envloop.job/v2`` envelope (``spec``, optional ``overrides``) without submitting it.
@@ -610,7 +622,8 @@ class Jobs:
610
622
 
611
623
  def submit_profile(self, profile: str, *, type: str = 'bench', inputs: Mapping[str, str | Mapping[str, str]] | None = None,
612
624
  parameters: Mapping[str, Any] | None = None, request_id: str | None = None,
613
- budget: Mapping[str, Any] | None = None, resources: Mapping[str, Any] | None = None):
625
+ budget: Mapping[str, Any] | None = None, resources: Mapping[str, Any] | None = None,
626
+ provider: str | None = None):
614
627
  """Submit only Profile intent and ANS inputs; resolution runs on the platform."""
615
628
  from envloop_experiment.named_profile import (
616
629
  profile_record,
@@ -618,7 +631,7 @@ class Jobs:
618
631
  submission,
619
632
  )
620
633
  body = submission(profile, type=type, inputs=inputs, parameters=parameters,
621
- request_id=request_id, budget=budget, resources=resources)
634
+ request_id=request_id, budget=budget, resources=resources, provider=provider)
622
635
  return self._server.submit_job(profile_request(body, lambda name, version: profile_record(self._server, name, version)))
623
636
 
624
637
  def regrade(self, *, job_id: str | None = None, trial_ids: Sequence[str] | None = None,
@@ -34,8 +34,7 @@ class Endpoints:
34
34
 
35
35
  def resolve_job(self, body: dict[str, Any]):
36
36
  """Resolve a JobSpec without admission; the platform creates no Job and reserves no budget."""
37
- validate_public_execution(body.get('spec'), allow_local_sandbox=False)
38
- validate_public_execution(body.get('overrides'), allow_local_sandbox=False)
37
+ validate_public_execution(body, allow_sandbox_provider=False)
39
38
  configure_transport(self)
40
39
  return self.request("POST", "/v1/jobs/resolve", body)
41
40
 
@@ -6,6 +6,7 @@ from copy import deepcopy
6
6
  from types import SimpleNamespace
7
7
  from typing import Any, cast
8
8
 
9
+ from envloop.http import validate_public_execution
9
10
  from envloop_experiment.client import dataset_selector, runner_selector
10
11
  from envloop_experiment.train_runner_cli import (
11
12
  SHORTCUT_FIELDS,
@@ -78,7 +79,6 @@ def spec_request(args: argparse.Namespace):
78
79
  raise ValueError('--harbor_env requires a canonical --spec with schema envloop.job/v1 or a named --profile')
79
80
  if getattr(args, 'provider', None) is not None:
80
81
  request['provider'] = args.provider
81
- from envloop.http import validate_public_execution
82
82
  validate_public_execution(request)
83
83
  if args.request_id is not None:
84
84
  request['request_id'] = args.request_id
@@ -211,7 +211,7 @@ def spec_request(args: argparse.Namespace):
211
211
 
212
212
 
213
213
  def unified_request(args: argparse.Namespace, request: dict[str, Any]) -> dict[str, Any]:
214
- """Keep the canonical JobSpec envelope and put explicit CLI values in overrides."""
214
+ """Apply CLI values to the canonical JobSpec envelope or its overrides."""
215
215
  spec = request['spec']
216
216
  kind = spec.get('type')
217
217
  if kind not in ('bench', 'sandbox', 'train', 'inference') or args.type is not None and args.type != kind:
@@ -220,7 +220,7 @@ def unified_request(args: argparse.Namespace, request: dict[str, Any]) -> dict[s
220
220
  if args.harbor_env is not None and kind not in {'bench', 'sandbox'}:
221
221
  raise ValueError('--harbor_env applies only to Bench/Sandbox Jobs')
222
222
  incompatible = ('dataset', 'dataset_option', 'source', 'task_id', 'config', 'split', 'revision',
223
- 'job_id', 'tag', 'attempts', 'profile', 'delete_delay_seconds', 'provider', *TRAIN_ONLY_FIELDS)
223
+ 'job_id', 'tag', 'attempts', 'profile', 'delete_delay_seconds', *TRAIN_ONLY_FIELDS)
224
224
  if any(getattr(args, key, None) is not None for key in incompatible):
225
225
  raise ValueError('Unified JobSpec uses spec.inputs and spec fields for legacy submission options')
226
226
  if kind == 'inference' and (args.wait or any(getattr(args, key, None) is not None for key in
@@ -254,4 +254,7 @@ def unified_request(args: argparse.Namespace, request: dict[str, Any]) -> dict[s
254
254
  request['overrides'] = overrides
255
255
  if args.request_id is not None:
256
256
  request['request_id'] = args.request_id
257
+ if getattr(args, 'provider', None) is not None:
258
+ request['provider'] = args.provider
259
+ validate_public_execution(request)
257
260
  return request
@@ -107,7 +107,7 @@ def input_selectors(values: Mapping[str, str | Mapping[str, str]]) -> dict[str,
107
107
  def submission(profile: str, *, type: str, inputs: Mapping[str, str | Mapping[str, str]] | None = None,
108
108
  parameters: Mapping[str, Any] | None = None, request_id: str | None = None,
109
109
  budget: Mapping[str, Any] | None = None,
110
- resources: Mapping[str, Any] | None = None) -> dict[str, Any]:
110
+ resources: Mapping[str, Any] | None = None, provider: str | None = None) -> dict[str, Any]:
111
111
  from envloop.http import validate_public_execution
112
112
  from envloop_experiment.runtime_params import validate_params
113
113
 
@@ -123,6 +123,8 @@ def submission(profile: str, *, type: str, inputs: Mapping[str, str | Mapping[st
123
123
  body: dict[str, Any] = {'type': type, 'profile_name': name, 'request_id': request_id,
124
124
  'inputs': input_selectors(inputs or {}),
125
125
  'parameters': dict(parameters or {})}
126
+ if provider is not None:
127
+ body['provider'] = provider
126
128
  if separator:
127
129
  body['profile_version'] = version
128
130
  if budget is not None:
@@ -170,6 +172,8 @@ def profile_request(body: dict[str, Any], lookup: Callable[[str, str | None], An
170
172
  profile += '@' + body['profile_version']
171
173
  request: dict[str, Any] = {'request_id': body['request_id'],
172
174
  'spec': {'schema': 'envloop.job/v2', 'type': body['type'], 'profile': profile}}
175
+ if 'provider' in body:
176
+ request['provider'] = body['provider']
173
177
  overrides = {key: deepcopy(body[source]) for key, source in
174
178
  (('params', 'parameters'), ('budget', 'budget'), ('resources', 'resources')) if body.get(source)}
175
179
  if overrides: