envloop-cli 1.32.0__py3-none-any.whl → 1.33.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.
Files changed (43) hide show
  1. envloop/_optional.py +9 -4
  2. envloop/auth_cli.py +48 -8
  3. envloop/cli.py +6 -13
  4. envloop/cli_errors.py +94 -16
  5. envloop/cli_output.py +1 -1
  6. envloop/http.py +61 -11
  7. envloop/navigation_resources.py +1 -1
  8. envloop/profile_secrets.py +46 -1
  9. envloop/resource_cli.py +31 -4
  10. envloop/terminal.py +19 -0
  11. {envloop_cli-1.32.0.dist-info → envloop_cli-1.33.0.dist-info}/METADATA +22 -5
  12. envloop_cli-1.33.0.dist-info/RECORD +67 -0
  13. envloop_data/checkpoint_upload.py +94 -0
  14. envloop_data/cli.py +2 -0
  15. envloop_data/cli_output.py +74 -13
  16. envloop_data/client.py +62 -9
  17. envloop_data/data.py +52 -17
  18. envloop_data/data_cli.py +139 -20
  19. envloop_data/data_publications.py +10 -3
  20. envloop_data/data_upload.py +0 -4
  21. envloop_data/http.py +6 -2
  22. envloop_data/navigation_resources.py +24 -0
  23. envloop_data/profile_updates.py +1 -1
  24. envloop_data/recipe_packages.py +125 -0
  25. envloop_data/recipes.py +1 -1
  26. envloop_data/resource_cli.py +85 -27
  27. envloop_data/runner_packages.py +41 -1
  28. envloop_experiment/cli.py +67 -40
  29. envloop_experiment/client.py +57 -10
  30. envloop_experiment/inference.py +18 -2
  31. envloop_experiment/job_spec_cli.py +78 -10
  32. envloop_experiment/named_profile.py +86 -10
  33. envloop_experiment/train.py +2 -0
  34. envloop_experiment/train_runner_cli.py +23 -11
  35. envloop_rsi_loop/cli.py +49 -29
  36. envloop_rsi_loop/cli_output.py +77 -43
  37. envloop_rsi_loop/loop_cli.py +113 -0
  38. envloop_rsi_loop/loops.py +203 -0
  39. envloop_cli-1.32.0.dist-info/RECORD +0 -65
  40. envloop_rsi_loop/agent_runs.py +0 -249
  41. envloop_rsi_loop/rsi_cli.py +0 -65
  42. {envloop_cli-1.32.0.dist-info → envloop_cli-1.33.0.dist-info}/WHEEL +0 -0
  43. {envloop_cli-1.32.0.dist-info → envloop_cli-1.33.0.dist-info}/entry_points.txt +0 -0
envloop/_optional.py CHANGED
@@ -19,19 +19,22 @@ FEATURE_COMMANDS = {
19
19
  'dataset': 'Discover Datasets, revisions and tasks',
20
20
  'data': 'Manage versioned Data resources and verified file downloads',
21
21
  'runner': 'Discover available Runner revisions',
22
- 'checkpoint': 'List and download saved training Checkpoints',
22
+ 'checkpoint': 'List, share and download saved training Checkpoints',
23
23
  'profile': 'Manage platform runtime Profiles',
24
24
  },
25
25
  'experiment': {
26
26
  'job': 'Submit and manage Agent, Sandbox, Train and Inference Jobs',
27
27
  'trial': 'Inspect and control existing Trials',
28
28
  },
29
+ 'rsi-loop': {
30
+ 'loop': 'Start, observe and steer RSI Loops and their Iterations',
31
+ },
29
32
  }
30
33
 
31
34
  MODULES: dict[str, str] = {
32
35
  **dict.fromkeys('data data_publications data_upload data_cli profile_updates recipes'.split(), 'data'),
33
36
  **dict.fromkeys('train train_progress train_metrics_cli train_runner_cli train_log_cli job_logs job_cost inference decision sandbox runtime_params job_spec_cli training'.split(), 'experiment'),
34
- **dict.fromkeys('agent_runs rsi_cli'.split(), 'rsi-loop'),
37
+ **dict.fromkeys('loops'.split(), 'rsi-loop'),
35
38
  }
36
39
  CLIENTS = {
37
40
  **{name: ('data', 'client') for name in ('ProfileService', 'RunnerService', 'Profiles', 'Runners')},
@@ -148,8 +151,8 @@ def client_resource(client: Any, name: str):
148
151
  return feature_attribute('experiment', 'train', 'TrainJobs')(server)
149
152
  if name == 'decision':
150
153
  return feature_attribute('experiment', 'decision', 'DecisionClient')(server)
151
- if name == 'agent_runs':
152
- return feature_attribute('rsi-loop', 'agent_runs', 'AgentRuns')(client.training_jobs)
154
+ if name == 'loops':
155
+ return feature_attribute('rsi-loop', 'loops', 'Loops')(client.training_jobs)
153
156
  if name in {'endpoints', 'adapters'}:
154
157
  return feature_attribute('experiment', 'resources', name.capitalize())(server)
155
158
  if name == 'inference':
@@ -160,6 +163,8 @@ def client_resource(client: Any, name: str):
160
163
  def execute_command(args: argparse.Namespace, client: Any, cli: Any):
161
164
  if args.group in {'job', 'trial'}:
162
165
  return getattr(feature_module('experiment', 'cli'), 'execute_' + args.group)(args, client, cli)
166
+ if args.group == 'loop':
167
+ return feature_module('rsi-loop', 'loop_cli').execute(args, client)
163
168
  if args.group == 'profile':
164
169
  return feature_module('data', 'cli').execute_profile(args, client, cli)
165
170
  if args.group in {'data', 'dataset', 'runner', 'checkpoint'}:
envloop/auth_cli.py CHANGED
@@ -2,6 +2,7 @@
2
2
  import argparse
3
3
  import json
4
4
  import os
5
+ import re
5
6
  import sys
6
7
  from typing import Any, cast
7
8
 
@@ -43,8 +44,9 @@ def add_auth_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParse
43
44
  show.add_argument("--json", action="store_true")
44
45
  remove = actions.add_parser("unset", help="Delete a saved field; does not revoke the server key")
45
46
  remove.add_argument("field", metavar="FIELD", choices=CONFIG_FIELDS, help=FIELD_HELP)
46
- status = commands.add_parser("status", help="Inspect local credentials; --check verifies read access")
47
- status.add_argument("--check", action="store_true", help="Make a read-only request to the effective Base URL")
47
+ status = commands.add_parser("status", help="Inspect local credentials; --check verifies them with the API")
48
+ status.add_argument("--check", action="store_true",
49
+ help="Confirm the API key and scope with GET /v1/me; other read probes are reported as warnings")
48
50
  status.add_argument("--json", action="store_true")
49
51
  commands.add_parser("logout", help="Remove the saved key for the stored default Base URL (local only)")
50
52
  workspace = commands.add_parser("workspace", help="Select and verify the active Workspace")
@@ -113,13 +115,14 @@ def _report(args: argparse.Namespace, store: ConfigStore):
113
115
  from .cli import resolve_cli_connection
114
116
 
115
117
  connection = resolve_cli_connection()
116
- return {
118
+ report: dict[str, Any] = {
117
119
  "saved": {**saved, "api_key": "configured" if configured else "missing"},
118
120
  "effective": {"api_url": connection.api_url, "workspace_id": connection.workspace_id, "project_id": connection.project_id,
119
121
  "api_key": "configured" if connection.api_key is not None else "missing"},
120
122
  "sources": connection.sources,
121
123
  "check": "not_checked",
122
- }, connection
124
+ }
125
+ return report, connection
123
126
 
124
127
 
125
128
  def _verify_key(url: str, key: str, workspace_id: str | None = None, project_id: str | None = None):
@@ -164,6 +167,8 @@ def _print(report: dict[str, Any], as_json: bool = False) -> None:
164
167
  print(f"Saved workspace: {report['saved'].get('workspace_id') or 'server default'}")
165
168
  print(f"Saved project: {report['saved'].get('project_id') or 'key scope'}")
166
169
  print(f"Check: {report['check']}")
170
+ for name, result in report.get("probes", {}).items():
171
+ print(f"Probe {name}: {result}")
167
172
 
168
173
 
169
174
  def run_auth(args: argparse.Namespace, parser: argparse.ArgumentParser):
@@ -278,10 +283,14 @@ def run_auth(args: argparse.Namespace, parser: argparse.ArgumentParser):
278
283
 
279
284
  try:
280
285
  require_remote(connection)
281
- HttpService(connection.api_url, api_key=connection.api_key,
282
- workspace_id=connection.workspace_id, project_id=connection.project_id,
283
- config=False, environment=False).list_jobs(limit=1)
284
- report["check"] = "access_confirmed" if connection.api_key else "reachable_anonymous"
286
+ if connection.api_key is None:
287
+ raise ConfigError('API_KEY_REQUIRED')
288
+ service = HttpService(connection.api_url, api_key=connection.api_key,
289
+ workspace_id=connection.workspace_id, project_id=connection.project_id,
290
+ config=False, environment=False)
291
+ # `/v1/me` is the identity check; it alone decides whether the key works.
292
+ _confirm_identity(service.request("GET", "/v1/me"), connection.workspace_id, connection.project_id)
293
+ report["check"] = "access_confirmed"
285
294
  except (ConfigError, RemoteError) as error:
286
295
  from .cli_errors import format_error, safe_error_code
287
296
 
@@ -291,5 +300,36 @@ def run_auth(args: argparse.Namespace, parser: argparse.ArgumentParser):
291
300
  _print(report, args.json)
292
301
  print(format_error(error), file=sys.stderr)
293
302
  return 1
303
+ # Further probes describe service health, not the credential: report them as warnings.
304
+ report["probes"], report["warnings"] = _probe(service)
294
305
  _print(report, getattr(args, "json", False))
306
+ for warning in report.get("warnings", []):
307
+ print("Warning: " + warning, file=sys.stderr)
295
308
  return 0
309
+
310
+
311
+ def _confirm_identity(response: Any, workspace_id: str | None, project_id: str | None) -> None:
312
+ """Require API key authentication; when the server names the scope, it must match the selected one."""
313
+ if not isinstance(response, dict) or response.get("auth_method") != "api_key":
314
+ raise ConfigError("AUTH_CHECK_UNCONFIRMED")
315
+ if response.get("workspace") is not None:
316
+ from .auth_workspace import _scope
317
+
318
+ _scope(response, workspace_id, project_id)
319
+
320
+
321
+ def _probe(service: Any) -> tuple[dict[str, str], list[str]]:
322
+ """Read one Job page; a failure here is a service problem, not a credential problem."""
323
+ from .cli_errors import safe_error_code
324
+ from .http import RemoteError
325
+
326
+ try:
327
+ service.list_jobs(limit=1)
328
+ return {"jobs": "ok"}, []
329
+ except RemoteError as error:
330
+ code = error.code if isinstance(error.code, str) and re.fullmatch(r"[A-Z0-9_]{1,128}", error.code) else safe_error_code(error)
331
+ status = error.status_code if isinstance(error.status_code, int) and 100 <= error.status_code <= 599 else None
332
+ retry = status is None or status >= 500
333
+ return {"jobs": code}, [f"GET /v1/jobs failed with {code}" + (f" (HTTP {status})" if status else "")
334
+ + "; the API key is authenticated, but this request did not succeed."
335
+ + (" The service may be degraded; retry later." if retry else "")]
envloop/cli.py CHANGED
@@ -14,7 +14,7 @@ from .http import CLI_VERSION
14
14
 
15
15
  SECTIONS = {
16
16
  'OVERVIEW': ('dashboard',),
17
- 'EXPERIMENT': ('job', 'trial'),
17
+ 'EXPERIMENT': ('job', 'trial', 'loop'),
18
18
  'DATA': ('dataset', 'data', 'runner', 'checkpoint', 'profile'),
19
19
  'MANAGE': ('billing', 'limit', 'member', 'setting'),
20
20
  'TOOLS': ('auth', 'help'),
@@ -227,16 +227,11 @@ def _main(argv: list[str] | None = None):
227
227
  from ._optional import IncompleteInstallationError, available
228
228
  requested = next((value for value in argv if not value.startswith('-')), None)
229
229
  feature = cast(dict[str | None, str], {'job': 'experiment', 'trial': 'experiment', 'data': 'data', 'dataset': 'data',
230
- 'runner': 'data', 'checkpoint': 'data', 'profile': 'data'}).get(requested)
230
+ 'runner': 'data', 'checkpoint': 'data', 'profile': 'data', 'loop': 'rsi-loop'}).get(requested)
231
231
  if feature is not None and not available(feature):
232
232
  from .cli_errors import format_error
233
233
  print(format_error(IncompleteInstallationError(feature)), file=sys.stderr)
234
234
  return 1
235
- job_action = next((value for value in argv[argv.index('job') + 1:] if not value.startswith('-')), None) if requested == 'job' else None
236
- if job_action == 'run' and not available('rsi-loop'):
237
- from .cli_errors import format_error
238
- print(format_error(IncompleteInstallationError('rsi-loop')), file=sys.stderr)
239
- return 1
240
235
  args = cli.parse_args(argv)
241
236
  if args.group == "help":
242
237
  cli.parse_args([*args.command, "--help"])
@@ -265,6 +260,9 @@ def _main(argv: list[str] | None = None):
265
260
  if args.group == 'setting' and args.action == 'update' and not any(getattr(args, key) is not None for key in ('name', 'slug', 'region')):
266
261
  cli.error('provide at least one of --name, --slug or --region')
267
262
  try:
263
+ if args.group == 'loop':
264
+ from ._optional import feature_module
265
+ feature_module('rsi-loop', 'loop_cli').validate(args)
268
266
  resolved = resolve_cli_connection(args.api_url, args.workspace_id)
269
267
  args.api_url = resolved.api_url
270
268
  connection = Client.remote(args.api_url, api_key=resolved.api_key, workspace_id=resolved.workspace_id,
@@ -279,12 +277,7 @@ def _main(argv: list[str] | None = None):
279
277
  if result.get('status') in {'FAILED', 'CANCELLED', 'RETRYABLE_FAILED', 'BLOCKED'}:
280
278
  raise CleanupError(result)
281
279
  result = operation_output(result)
282
- if args.group == 'job' and args.action == 'run' and args.run_action == 'get' and not args.json:
283
- from .cli_output import run_output
284
-
285
- print(run_output(result))
286
- elif (args.action == 'list' or getattr(args, '_list_view', False)
287
- or (args.group == 'job' and args.action == 'run' and args.run_action == 'list')) and not args.json:
280
+ if (args.action == 'list' or getattr(args, '_list_view', False)) and not args.json:
288
281
  from .cli_output import list_output
289
282
 
290
283
  print(list_output(result, args, cli.prog))
envloop/cli_errors.py CHANGED
@@ -5,10 +5,11 @@ for any code, including codes this CLI does not know. `http.error_fields`
5
5
  already bounded that text to single printable lines and removed the API key.
6
6
  Local text below only adds guidance, and is the sole text when the server sent
7
7
  none (non-JSON body, network failure). Local failures never reflect exception
8
- messages.
8
+ messages, except the CLI's own validation refusals (see `validation_message`).
9
9
  """
10
10
 
11
11
  import json
12
+ import linecache
12
13
  import os
13
14
  import re
14
15
  import sys
@@ -17,7 +18,7 @@ from collections.abc import Iterable
17
18
  from datetime import datetime
18
19
  from typing import Any, cast
19
20
 
20
- from .http import GATEWAY_TIMEOUT_STATUSES, RemoteError
21
+ from .http import GATEWAY_TIMEOUT_STATUSES, RemoteError, _text
21
22
 
22
23
  _MESSAGES: dict[str, str] = {}
23
24
 
@@ -27,7 +28,7 @@ def _register(codes: str, message: str) -> None:
27
28
  _MESSAGES[code] = message
28
29
 
29
30
 
30
- _register("DATA_ACCESS_REQUIRED", "This key lacks the permission named above on the Dataset, Runner, Profile, Checkpoint or Trial artifact. Run el auth login to issue a new key that follows your project role: every role can read, and Developer or Admin can also write and delete (create, update, delete, upload, runner register). A key from el auth login --read-only cannot write; log in again without --read-only. Or give a key Read or Edit on that page in the Console under CONFIGURE > API Keys. Existing keys never gain permissions.")
31
+ _register("DATA_ACCESS_REQUIRED", "This key lacks the permission named above on the Dataset, Runner, Profile, Checkpoint or Trial artifact. Run el auth login to issue a new key that follows your project role: every role can read, and Developer or Admin can also write and delete (create, update, delete, upload, runner create). A key from el auth login --read-only cannot write; log in again without --read-only. Or give a key Read or Edit on that page in the Console under CONFIGURE > API Keys. Existing keys never gain permissions.")
31
32
  _register("DATA_NATIVE_INCOMPLETE DATA_NATIVE_UNAVAILABLE", "Native catalog registration is incomplete. Retry the same input after the platform is ready.")
32
33
  _register("DATA_DEPENDENCIES_ACTIVE DATA_DEPENDENCIES_UNKNOWN DATA_DEPENDENCIES_CHANGED DATA_DELETE_CONFLICT", "Retirement requires a complete, current dependency check. Resolve active or unknown dependencies, then retry the same resource.")
33
34
  _register("DATA_PUBLICATION_INVALID", "Check the immutable ANS URI, native manifest and exact file sizes and SHA-256 values. A record Dataset source is https://github.com/OWNER/REPO or https://huggingface.co/datasets/ORG/NAME with the full commit, not a branch or tag.")
@@ -38,7 +39,8 @@ _register("DATA_RESUME_MISMATCH", "The saved transfer no longer matches this res
38
39
  _register("DATA_HASH_MISMATCH DATA_SIZE_MISMATCH", "The downloaded bytes do not match the published file. The destination was not installed.")
39
40
  _register("DATA_REDIRECT_REJECTED", "The API returned a redirect. EL Data requires an authenticated proxy; update or contact the platform administrator.")
40
41
  _register("HTTP_ERROR", "The API request failed.")
41
- _register("NOT_FOUND RESOURCE_NOT_FOUND JOB_NOT_FOUND RUNNER_NOT_FOUND DATASET_REVISION_NOT_FOUND PROFILE_NOT_FOUND WORKSPACE_NOT_FOUND CHECKPOINT_NOT_FOUND AGENT_RUN_NOT_FOUND ARTIFACT_NOT_FOUND", "The requested API resource or route was not found.")
42
+ _register("API_KEY_SCOPE_MISMATCH", "An API key works only in the workspace and project it was issued for. Set ENVLOOP_WORKSPACE_ID and ENVLOOP_PROJECT_ID (or el auth workspace) to the key's own scope named above, or use a key issued in the target project.")
43
+ _register("NOT_FOUND RESOURCE_NOT_FOUND JOB_NOT_FOUND RUNNER_NOT_FOUND DATASET_REVISION_NOT_FOUND PROFILE_NOT_FOUND WORKSPACE_NOT_FOUND CHECKPOINT_NOT_FOUND ARTIFACT_NOT_FOUND", "The requested API resource or route was not found.")
42
44
  _register("UNAUTHORIZED UNAUTHENTICATED INVALID_AUTH AUTHENTICATION_REQUIRED AUTHENTICATION_REJECTED API_KEY_REQUIRED", "API key authentication is required or was rejected.")
43
45
  _register("FORBIDDEN ACCESS_DENIED AUTHORIZATION_DENIED PERMISSION_DENIED WORKSPACE_ACCESS_DENIED PROJECT_ACCESS_DENIED", "The current credentials do not have permission for this operation.")
44
46
  _register("EDGE_REJECTED", "The network edge (Cloudflare) rejected the request before it reached the EnvLoop API; this is not a permission decision. Upgrade envloop-cli, check any proxy or custom User-Agent, or contact support with the HTTP status.")
@@ -49,10 +51,42 @@ _register("PROFILE_SECRET_NAME_INVALID", "A Secret parameter name must look like
49
51
  _register("PROFILE_SECRET_VALUE_INVALID", "A Secret parameter value is missing or unusable: it must be non-empty UTF-8 text of at most 64 KiB from a prompt, stdin, an environment variable or a file.")
50
52
  _register("PROFILE_MODEL_KEY_UNSUPPORTED", "--model-api-key-stdin and --prompt-model-api-key only set the encrypted key of a managed model connection (params.model_connection). Store other keys as a Secret parameter, for example --secret MODEL_API_KEY=stdin.")
51
53
  _register("PROFILE_SECRET_CONFLICT", "Give each Secret parameter once, by --secret only (not also in the Profile file or patch), and read at most one value from stdin.")
52
- _register("RUNNER_PACKAGE_INVALID", "The Runner package directory is invalid. It needs runner.toml whose [runner] name matches the Runner and has no version, the [execution] entrypoint main.py or main.sh, at most 100 regular files, no symlinks, and path parts of letters, digits, '_', '.' or '-' that do not start with '.'.")
53
- _register("RUNNER_REVISION_INVALID", "Use the full lowercase 40- or 64-character source commit as --revision and a NAMESPACE/NAME Runner name.")
54
+ _register("RUNNER_PACKAGE_INVALID", "The Runner package directory is invalid. It needs runner.toml whose [runner] name matches the Runner and has no version, an entrypoint main.py or main.sh in [runner] for v6 or [execution] for historical schemas, at most 100 regular files, no symlinks, and path parts of letters, digits, '_', '.' or '-' that do not start with '.'. v6 declarations must satisfy the EnvHub protocol, including supported types and per-type defaults.")
55
+ _register("RUNNER_REVISION_INVALID", "Use the full lowercase 40- or 64-character source commit, or a local branch or tag name, as --revision and a NAMESPACE/NAME Runner name.")
56
+ _register("RUNNER_REVISION_UNRESOLVED", "--revision names no local branch or tag in the Git checkout that holds DIRECTORY, or Git is unavailable. Fetch or create the branch, or pass the full source commit.")
57
+ _register("RUNNER_PACKAGE_UNCOMMITTED", "DIRECTORY differs from the --revision commit: it has uncommitted changes, untracked files or ignored files, all of which would be published. Commit or remove them, or pass a full commit you vouch for.")
54
58
  _register("RUNNER_SOURCE_REF_INVALID", "Use a branch or tag name such as main or v1 with --source-ref-kind branch, tag or commit; HEAD, latest, default, release, '..', spaces and ~^:?*[\\ are not allowed.")
55
59
  _register("RUNNER_REVISION_CONFLICT", "The platform catalog holds different package or index hashes for this Runner revision. Publish a new revision instead of changing an existing one.")
60
+ _register("RECIPE_PACKAGE_INVALID RECIPE_DECLARATION_INVALID RECIPE_INVALID", "--directory must hold recipe.toml with schema_version = \"envloop.recipe/v2\" and the tables [recipe] name, types; [runner] name, abi; [source] paths, optional exclude and optional repository (a https://github.com/OWNER/REPO URL if given; omit it for a local-only repository); optional [inputs], [params], [outputs] and [dependencies]. No other top-level tables or keys are allowed.")
61
+ _register("RECIPE_PACKAGE_SCHEMA_RETIRED", "recipe.toml uses the retired envloop.recipe-publication/v3 format. Rewrite it as schema_version = \"envloop.recipe/v2\" with [recipe], [runner] and [source] tables and add entrypoint.sh next to it; published Recipes stay readable.")
62
+ _register("RECIPE_SCHEMA_UNSUPPORTED RECIPE_PACKAGE_SCHEMA_UNSUPPORTED", "Set schema_version = \"envloop.recipe/v2\" at the top of recipe.toml.")
63
+ _register("RECIPE_ABI_UNSUPPORTED", "Set [runner] abi = \"envloop.recipe/1\"; it is the only Recipe ABI for new Recipes.")
64
+ _register("RECIPE_DECLARATION_NOT_FOUND", "The --revision commit has no recipe.toml in --directory. Commit the declaration, or point --directory at the directory that holds it.")
65
+ _register("RECIPE_ENTRYPOINT_NOT_FOUND", "The --revision commit has no entrypoint.sh next to recipe.toml, or it is not a regular file of at most 512 MiB. Commit entrypoint.sh in the same directory as recipe.toml.")
66
+ _register("RECIPE_DECLARATION_CONFLICT", "[source].paths would place another file at the package root path recipe.toml or entrypoint.sh. Narrow paths or list that file in exclude.")
67
+ _register("RECIPE_PATH_NOT_FOUND", "Every [source].paths entry must match files present at the --revision commit, and every exclude entry must name one of the selected files exactly.")
68
+ _register("RECIPE_PATH_INVALID", "Paths in recipe.toml are relative to the repository root and use only letters, digits, '_', '.' or '-' parts that do not start with '.'.")
69
+ _register("RECIPE_FILE_UNSUPPORTED", "Packaged Recipe paths may contain only regular files; remove symlinks and submodules from paths or list them in exclude.")
70
+ _register("RECIPE_PACKAGE_TOO_LARGE", "A Recipe package holds at most 1000 files, 512 MiB per file and 1 GiB in total. Narrow paths or add exclusions.")
71
+ _register("RECIPE_DEPENDENCY_INVALID", "Each [dependencies.SLOT] needs the uri and manifest_sha256 of an already published Recipe, envloop://recipes/NAMESPACE/NAME@SHA256, with the same digest in both.")
72
+ _register("RECIPE_NAME_INVALID", "[recipe] name is NAMESPACE/NAME using letters, digits, '_', '.' or '-'.")
73
+ _register("RECIPE_NAME_MISMATCH", "[recipe] name in recipe.toml must equal the NAMESPACE/NAME of the Recipe URI. Publish with --directory so the URI is derived from recipe.toml.")
74
+ _register("RECIPE_TYPES_INVALID", "[recipe] types is a non-empty list of distinct Job types from agent, sandbox, train and inference.")
75
+ _register("RECIPE_PARAMS_INVALID", "Each [params.NAME] uses type, default, required, description, enum, minimum, maximum or locked (object params also properties and additional_properties); names are lowercase snake_case. Recipe image accepts only a default pinned with @sha256:<digest> and optional description. command, timeout_seconds and max_retries cannot be declared by a Recipe.")
76
+ _register("RECIPE_PARAM_CONFLICT", "A Recipe param may only narrow the Runner's declaration of the same name: same type, tighter range, enum subset, keep Runner locks and required params. Relax the Recipe declaration.")
77
+ _register("RECIPE_INPUTS_INVALID", "Each [inputs.SLOT] has kind (dataset, checkpoint or artifact) and required (true or false); slot names are lowercase, and train_dataset / eval_dataset must be datasets, checkpoint / resume_from_checkpoint checkpoints.")
78
+ _register("RECIPE_OUTPUTS_INVALID", "[outputs] files lists distinct relative paths under $ENVLOOP_OUTPUT_DIR; result.json is always produced and is not listed.")
79
+ _register("RECIPE_AGENT_DEFINITION_NOT_FOUND", "[agent] definition must name a JSON file selected by [source].paths.")
80
+ _register("RECIPE_SOURCE_INVALID RECIPE_SOURCE_MISMATCH", "[source] repository is optional: omit it for a local-only Git repository, or give https://github.com/OWNER/REPO. It is recorded as provenance only and never fetched.")
81
+ _register("RECIPE_INDEX_INVALID RECIPE_INTEGRITY RECIPE_FILE_NOT_SELECTED RECIPE_DEPENDENCY_MISMATCH", "The uploaded Recipe files do not match their content index. Rebuild and publish with el data create --type recipe --directory DIR instead of a hand-written manifest.")
82
+ _register("RECIPE_ABI_MISMATCH", "The Job's Runner Revision does not implement the Recipe ABI envloop.recipe/1. Use a Runner Revision that does, or a Recipe published for this Runner's ABI.")
83
+ _register("RECIPE_TYPE_UNSUPPORTED", "The Job type must be listed in both the Runner's and the Recipe's types. Submit a supported --type or add the type to [recipe] types.")
84
+ _register("RECIPE_PARAM_REQUIRED RUNNER_PARAM_REQUIRED", "A required param has no value. Set it under params in the Job spec (or the Profile); required params never get a default.")
85
+ _register("RECIPE_REVISION_INVALID", "Use a local branch or tag name, or the full lowercase 40- or 64-character commit, as --revision.")
86
+ _register("RECIPE_REVISION_UNRESOLVED", "--revision names no local branch, tag or commit in the Git checkout that holds --directory, or Git is unavailable. Fetch it, or pass the full commit.")
87
+ _register("RECIPE_PACKAGE_UNCOMMITTED", "recipe.toml or a packaged path differs from the --revision branch or tag: it has uncommitted changes or untracked files that would not be published. Commit them, or pass a full commit to publish exactly that commit.")
88
+ _register("RECIPE_READBACK_MISMATCH", "The platform catalog did not return this Recipe as ready with the published manifest digest. Read it with el data list --type recipe --ref URI before retrying.")
89
+ _register("RECIPE_PACKAGE_UNSUPPORTED", "The installed envloop-envhub cannot build Recipe packages. Upgrade envloop-cli[data] to a release that includes it.")
56
90
  _register("DATASET_REQUIRED", "Missing Dataset input (--dataset or --source) for this Agent Job.")
57
91
  _register("DATASET_CONFIG_REQUIRED", "An explicit Dataset configuration (--config) is required.")
58
92
  _register("RUNNER_REQUIRED", "Missing Runner input (--runner) for this Job.")
@@ -74,6 +108,8 @@ _register("FILE_EXISTS", "The destination already exists.")
74
108
  _register("FILE_ERROR", "A local file could not be read or written.")
75
109
  _register("INVALID_JSON", "The request file is not valid JSON.")
76
110
  _register("INVALID_INPUT", "The request or input is invalid.")
111
+ _register("DATA_FILE_REQUIRED", "This resource has several files. Download one with --file FILE_ID; its files are listed below.")
112
+ _register("DATA_FILE_UNAVAILABLE", "This resource has no downloadable file yet. Check its status with `el data get DATA_ID`.")
77
113
  _register("INVALID_API_KEY", "The supplied API key has an invalid format.")
78
114
  _register("API_URL_REQUIRED INVALID_API_URL", "The API Base URL is missing or invalid.")
79
115
  _register("PROJECT_REQUIRED PROJECT_SCOPE_REQUIRED", "This operation requires a project scope.")
@@ -108,9 +144,18 @@ _register("PROFILE_RUNNER_UNSUPPORTED", "This submission path cannot execute the
108
144
  _register("PROFILE_ARCHIVED PROFILE_HASH_MISMATCH", "The selected Profile is archived or does not match its frozen version.")
109
145
  _register("NAMED_PROFILE_INVALID PROFILE_INPUT_INVALID PROFILE_CHECKPOINT_MODEL_MISMATCH", "The named Profile or input binding is incompatible. Use its declared input slots and allowed parameter replacements.")
110
146
  _register("PROFILE_AUTHORIZATION_UNAVAILABLE", "Current Profile authorization could not be verified. Retry the same request after authorization is available.")
111
- _register("VISIBILITY_CONFLICT", "Visibility changed since it was read. Read the resource and use its current visibility and ACL revision before retrying.")
112
- _register("VISIBILITY_INVALID", "Choose private or public visibility for a supported resource.")
113
- _register("PUBLIC_DEPENDENCY_UNAVAILABLE PUBLIC_CONTENT_UNSAFE PUBLICATION_REVIEW_REQUIRED", "Public sharing requires reviewed content and currently readable public dependencies. Private dependencies are never published automatically.")
147
+ _register("VISIBILITY_CONFLICT", "Visibility changed since it was read. Read the current acl_revision again (el data get DATA_ID or el checkpoint get CHECKPOINT_ID) and retry with it, or omit --expected-acl-revision to use the current value. A Profile also needs its current visibility as --expected-visibility.")
148
+ _register("VISIBILITY_INVALID", "Choose private, internal or public with a nonnegative --expected-acl-revision; a Profile takes private or public. A Hugging Face model registration (metadata only) has no visibility: it stays readable only in the project that registered it, so register it in each project that needs it.")
149
+ _register("RECIPE_GRANTS_UNAVAILABLE", "Recipe sharing could not be checked for this request. This is temporary; retry the same request.")
150
+ _register("RECIPE_GRANTS_LIMIT", "This project can read more shared Recipe names than the platform can apply to one request. Retrying will not help; contact a platform operator.")
151
+ _register("VISIBILITY_PUBLIC_REQUIRES_ADMIN", "Only a platform administrator can make a resource public or withdraw public visibility; API keys never act as platform administrators. Use private or internal (this workspace), or ask a platform administrator.")
152
+ _register("RUNNER_REVISION_AMBIGUOUS", "Several projects share different content under this Runner revision. Publish your own copy in this project with el runner create (your copy takes precedence), or ask the owning project to set theirs private with el data set-visibility.")
153
+ _register("CHECKPOINT_REVISION_AMBIGUOUS", "Several projects share different checkpoints under this URI. Copy the one you need into this project (your copy takes precedence), or ask the owning project to set theirs private with el checkpoint set-visibility.")
154
+ _register("DATASET_REVISION_AMBIGUOUS", "Several projects share different content under this Dataset version. el data list --type dataset shows the entry as unavailable with the data_id of each readable copy under CANDIDATES (--json adds owners and digests); select one copy by passing that data_id as --dataset DATA_ID or --input SLOT=DATA_ID. Or pass another explicit NAME@VERSION, publish your own copy in this project with el data create --type dataset (your copy takes precedence), or ask the owning project to set theirs private with el data set-visibility.")
155
+ _register("DATASET_NAMESPACE_UNAVAILABLE", "This registration ran while Dataset namespaces were still reserved or claimed across projects. Datasets are now stored per project and no namespace is reserved: register the same snapshot again (el data register PUBLICATION_ID --runner NAME@REVISION).")
156
+ _register("RESOURCE_IN_USE", "Remove or release the listed references first. A reference listed with a workspace and project belongs to another project that froze your shared copy (for example an endpoint or adapter holding a checkpoint); ask that project to delete or release it. Narrowing visibility does not release a frozen reference.")
157
+ _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 (el data set-visibility DATA_ID), then retry; private dependencies are never shared automatically.")
158
+ _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.")
114
159
  _register("CHECKPOINT_AMBIGUOUS", "More than one checkpoint matches this selection.")
115
160
  _register("CHECKPOINT_FILES_UNAVAILABLE ARTIFACT_NOT_READY", "The requested download is not available yet.")
116
161
  _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.")
@@ -123,9 +168,12 @@ _register("RUNNER_NOT_FOUND", "The Runner reference was not found or is not read
123
168
  _register("INVALID_SANDBOX_RUNNER", "The Runner revision cannot execute as a standalone Sandbox Job.")
124
169
  _register("INVALID_SANDBOX_IMAGE", "The Sandbox image reference is invalid.")
125
170
 
126
- _register("RSI_RUN_NOT_FOUND", "No RSI run with this name is visible in the current project.")
171
+ _register("RSI_LOOP_NOT_FOUND", "No RSI Loop with this LOOP_ID is visible in the current project. List Loops with el loop list.")
172
+ _register("RSI_ITERATION_NOT_FOUND", "The Loop has no Iteration with this number yet. See its Iterations with el loop get LOOP_ID.")
173
+ _register("INVALID_LOOP_ID", "LOOP_ID must be loop_ followed by 32 lower-case hex characters, as el loop list shows it.")
174
+ _register("INVALID_ITERATION", "ITERATION must be a positive integer; Iterations are numbered from 1.")
127
175
  _register("INVALID_RSI_REQUEST INVALID_STEER INVALID_DIRECTIVE", "The RSI service rejected the request fields.")
128
- _register("RSI_CONFLICT RSI_RUN_NOT_ACTIVE", "The run id exists, the run is not in a state that allows this action, or no loop machine is free.")
176
+ _register("RSI_CONFLICT RSI_LOOP_NOT_ACTIVE", "A Loop with this name exists, the Loop is not in a state that allows this action, or no loop machine is free.")
129
177
  _register("RSI_CONTROL_UNCONFIGURED RSI_CONTROL_UNAVAILABLE RSI_CONTROL_TIMEOUT", "The RSI loop service is not available through this platform right now.")
130
178
 
131
179
  _register("UNSUPPORTED_ADAPTER_SOURCE", 'Register a training checkpoint with {"serving_profile": "NAME", "source": {"type": "train_checkpoint", "uri": "envloop://..."}}. '
@@ -145,7 +193,7 @@ for _code, _resource in {
145
193
  "RUNNER_NOT_FOUND": "Runner revision", "DATASET_NOT_FOUND": "Dataset",
146
194
  "DATASET_REVISION_NOT_FOUND": "Dataset revision", "CHECKPOINT_NOT_FOUND": "checkpoint",
147
195
  "ARTIFACT_NOT_FOUND": "artifact", "WORKSPACE_NOT_FOUND": "workspace",
148
- "AGENT_RUN_NOT_FOUND": "training run", "TRIAL_NOT_FOUND": "Trial",
196
+ "TRIAL_NOT_FOUND": "Trial",
149
197
  }.items():
150
198
  _register(_code, f"The {_resource} was not found or is not readable in the current scope.")
151
199
 
@@ -189,7 +237,7 @@ TEMPORARY_SCOPE_CONFLICT TEMPORARY_SCOPE_EXPIRED TRIAL_IDEMPOTENCY_CONFLICT TRIA
189
237
  PROFILE_CORRUPT ADAPTER_STORAGE_UNAVAILABLE INSUFFICIENT_BALANCE METHOD_NOT_ALLOWED REQUEST_TOO_LARGE
190
238
  BATCH_POLICY_NOT_APPROVED BATCH_PROVIDER_UNAVAILABLE CHECKPOINT_ACCESS_DENIED CHECKPOINT_DOWNLOAD_UNAVAILABLE
191
239
  CHECKPOINT_MANAGEMENT_UNAVAILABLE CHECKPOINT_MANAGEMENT_UNSUPPORTED CHECKPOINT_NOT_DURABLE CHECKPOINT_TRIAL_REQUIRED
192
- CHECKPOINT_SIGNER_UNAVAILABLE INVALID_CHECKPOINT_CURSOR INVALID_CHECKPOINT_TTL INVALID_CHECKPOINT_VISIBILITY
240
+ CHECKPOINT_SIGNER_UNAVAILABLE INVALID_CHECKPOINT_CURSOR INVALID_CHECKPOINT_TTL
193
241
  INVALID_EXECUTION_CONFIG INVALID_METRICS_RANGE INVALID_TRAIN_JOB_CURSOR INVALID_TRAIN_JOB_LIST_LIMIT
194
242
  INVALID_TRAIN_JOB_METADATA INVALID_TRAIN_JOB_SPEC INVALID_TRAIN_JOB_STATUS LOG_RETENTION_EXPIRED
195
243
  TRAINING_RUN_NOT_FOUND TRAIN_JOB_CAPACITY_EXCEEDED TRAIN_JOB_IDEMPOTENCY_CONFLICT TRAIN_JOB_NOT_FOUND
@@ -233,6 +281,30 @@ def _http_message(status: int | None) -> str:
233
281
  return _MESSAGES["HTTP_ERROR"]
234
282
 
235
283
 
284
+ _OWN_PACKAGES = frozenset({"envloop", "envloop_data", "envloop_experiment", "envloop_rsi_loop"})
285
+
286
+
287
+ def validation_message(error: BaseException) -> str | None:
288
+ """The wording of a client-side validation refusal, or None for any other failure.
289
+
290
+ Shown only for a plain `ValueError` constructed by a `raise` statement in this CLI's own
291
+ packages: that text is fixed client wording plus field names or the user's own path. Errors
292
+ from the standard library or dependencies (`int()`, JSON, Unicode), raised from server
293
+ content, or of credential-bearing subclasses (`ConfigError`, `InvalidProfileSecrets`) keep
294
+ the static explanation.
295
+ """
296
+ if type(error) is not ValueError or not (trace := error.__traceback__):
297
+ return None
298
+ while trace.tb_next:
299
+ trace = trace.tb_next
300
+ module = trace.tb_frame.f_globals.get("__name__")
301
+ if not isinstance(module, str) or module.partition(".")[0] not in _OWN_PACKAGES:
302
+ return None
303
+ if not linecache.getline(trace.tb_frame.f_code.co_filename, trace.tb_lineno).lstrip().startswith("raise "):
304
+ return None
305
+ return _text(str(error), 500)
306
+
307
+
236
308
  def safe_error_code(error: Any) -> str:
237
309
  """Select a trusted CLI/report identifier without changing the SDK error."""
238
310
  from ._optional import MissingFeatureError
@@ -245,7 +317,7 @@ def safe_error_code(error: Any) -> str:
245
317
  return error.code
246
318
  if isinstance(error, CleanupError):
247
319
  code = "CLEANUP_INCOMPLETE"
248
- elif isinstance(error, (RemoteError, ConfigError, ArtifactError, InvalidProfileSecrets)) or type(error).__module__ == 'envloop_rsi_loop.agent_runs':
320
+ elif isinstance(error, (RemoteError, ConfigError, ArtifactError, InvalidProfileSecrets)) or type(error).__module__ == 'envloop_rsi_loop.loops':
249
321
  known = _MESSAGES.keys() | _KNOWN_REMOTE_CODES if isinstance(error, RemoteError) else _MESSAGES.keys()
250
322
  code = error.code if isinstance(error.code, str) and error.code in known else (
251
323
  "HTTP_ERROR" if isinstance(error, RemoteError) else "CONFIG_ERROR" if isinstance(error, ConfigError) else "CLI_ERROR")
@@ -272,7 +344,7 @@ def safe_error_code(error: Any) -> str:
272
344
  return code
273
345
 
274
346
 
275
- def error_block(code: str, message: str, *, status: int | None = None, guidance: str | None = None, hint: str | None = None, details: Iterable[str] = (), request_id: str | None = None) -> str:
347
+ def error_block(code: str, message: str, *, status: int | None = None, guidance: str | None = None, hint: str | None = None, details: Iterable[str] = (), request_id: str | None = None, route: str | None = None) -> str:
276
348
  """Render the error on stderr with optional terminal styling."""
277
349
  from .terminal import color_enabled
278
350
 
@@ -287,7 +359,8 @@ def error_block(code: str, message: str, *, status: int | None = None, guidance:
287
359
  detail = textwrap.fill(message, width=max(24, min(columns, 88)),
288
360
  initial_indent=" ", subsequent_indent=" ")
289
361
  lines = [title, detail]
290
- for text in (guidance, f"Hint: {hint}" if hint else None, *(f"- {item}" for item in details)):
362
+ for text in (guidance, f"Hint: {hint}" if hint else None, *(f"- {item}" for item in details),
363
+ f"Request: {route}" if route else None):
291
364
  if text:
292
365
  # Keep flags and identifiers such as `--request-id UUID` copyable on one line.
293
366
  lines.append(textwrap.fill(text, width=max(24, min(columns, 88)), break_on_hyphens=False,
@@ -311,6 +384,9 @@ def format_error(error: BaseException) -> str:
311
384
  code = remote.code
312
385
  local = _http_message(status) if code == "HTTP_ERROR" or code not in _MESSAGES else _MESSAGES[code]
313
386
  extra: dict[str, Any] = {"hint": remote.hint, "details": remote.details, "request_id": remote.request_id} if remote else {}
387
+ if remote and status == 404 and isinstance(getattr(remote, "route", None), str):
388
+ # Name the missing API resource; the platform's 404 text stays generic by design.
389
+ extra["route"] = remote.route
314
390
  if remote and remote.message and remote.details:
315
391
  # A detail that repeats the message (one refused field) only adds where it is: show the field alone.
316
392
  extra["details"] = [line.removesuffix(": " + remote.message) for line in remote.details if line != remote.message]
@@ -320,6 +396,8 @@ def format_error(error: BaseException) -> str:
320
396
  documented = (code in _MESSAGES and code != "HTTP_ERROR") or status in GATEWAY_TIMEOUT_STATUSES
321
397
  guidance = local if documented and local != remote.message else None
322
398
  rendered = error_block(code, remote.message, status=status, guidance=guidance, **extra)
399
+ elif message := validation_message(error):
400
+ rendered = error_block(code, message, guidance=local if local != message else None)
323
401
  else:
324
402
  rendered = error_block(code, local, status=status, **extra)
325
403
  recovery = upload_recovery(error)
envloop/cli_output.py CHANGED
@@ -95,7 +95,7 @@ def list_output(result: Any, args: argparse.Namespace, program: str) -> str:
95
95
  if not isinstance(items, list):
96
96
  items = [{'name': key, 'value': value} for key, value in items.items()]
97
97
  from ._optional import feature_module
98
- feature = ('rsi-loop' if args.group == 'job' and args.action == 'run' else
98
+ feature = ('rsi-loop' if args.group == 'loop' else
99
99
  'experiment' if args.group in {'job', 'trial'} else
100
100
  'data' if args.group in {'data', 'dataset', 'runner', 'checkpoint', 'profile'} else None)
101
101
  if feature is not None:
envloop/http.py CHANGED
@@ -10,21 +10,34 @@ from http.client import HTTPException, HTTPMessage, InvalidURL
10
10
  from importlib.metadata import PackageNotFoundError, version
11
11
  from typing import IO, Any, cast, override
12
12
  from urllib.error import HTTPError, URLError
13
+ from urllib.parse import urlsplit
13
14
  from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
14
15
 
15
16
  LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
16
17
  REDIRECT_STATUSES = {301, 302, 303, 307, 308}
17
18
 
18
19
 
19
- def validate_public_execution(value: Any) -> None:
20
- """Backend selection belongs to JobMaster, including nested Profiles."""
20
+ # The copy a Job reads from another project is resolved and frozen by the platform, never sent by a client.
21
+ RESOLVED_OWNER_FIELDS = ("dataset_owners", "checkpoint_owners", "checkpoint_owner", "runner_owner", "runner_storage_prefix")
22
+
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."""
21
26
  if not isinstance(value, dict):
22
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):
30
+ raise ValueError("the owning project of each input is resolved by the platform; select a Dataset copy by its "
31
+ "data_id and remove dataset_owners, checkpoint_owners, checkpoint_owner and runner_owner")
32
+ if any(key in value for key in ("executor", "backend")):
33
+ 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")
23
36
  execution = value.get("execution")
24
- if isinstance(execution, dict) and any(key in execution for key in ("executor", "provider")):
37
+ if isinstance(execution, dict) and any(key in execution for key in ("executor", "provider", "backend")):
25
38
  raise ValueError("execution backend is configured by the server")
26
39
  for key in ("profile", "profile_overrides", "params"):
27
- validate_public_execution(value.get(key))
40
+ validate_public_execution(value.get(key), allow_local_sandbox=False)
28
41
 
29
42
 
30
43
  class WaitTimeoutError(TimeoutError):
@@ -39,7 +52,8 @@ class RemoteError(RuntimeError):
39
52
  """Platform failure. Server-supplied text lives in bounded attributes, never in str()."""
40
53
 
41
54
  def __init__(self, code: str, status_code: int | None = None, *, retry_after: float | None = None, message: str | None = None, hint: str | None = None,
42
- request_id: str | None = None, details: list[str] | dict[str, Any] | None = None, staging_id: str | None = None, phase: str | None = None, retirement_pending: bool = False):
55
+ request_id: str | None = None, details: list[str] | dict[str, Any] | None = None, staging_id: str | None = None, phase: str | None = None, retirement_pending: bool = False,
56
+ route: str | None = None):
43
57
  self.code = code
44
58
  self.status_code = status_code
45
59
  self.retry_after = retry_after
@@ -50,6 +64,8 @@ class RemoteError(RuntimeError):
50
64
  self.staging_id = staging_id
51
65
  self.phase = phase
52
66
  self.retirement_pending = retirement_pending
67
+ # `METHOD /v1/...` of the failed API call, without query or host, so a 404 names what was missing.
68
+ self.route = route
53
69
  super().__init__(code)
54
70
 
55
71
 
@@ -196,9 +212,28 @@ def error_fields(error: HTTPError, secrets: tuple[str | None, ...] = ()) -> dict
196
212
  result['phase'] = pick('phase')
197
213
  if pick('retirement_pending') is True:
198
214
  result['retirement_pending'] = True
215
+ if dependencies := _dependency_lines(pick('dependencies'), secrets):
216
+ result['details'] = [*result['details'], *dependencies][:20]
199
217
  return result
200
218
 
201
219
 
220
+ def _dependency_lines(value: Any, secrets: tuple[str | None, ...]) -> list[str]:
221
+ """`RESOURCE_IN_USE` references as `endpoint ie_x`; another project's names its workspace and project."""
222
+ def token(item: Any) -> str | None:
223
+ return item if isinstance(item, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}", item) else None
224
+
225
+ lines = []
226
+ for item in value[:10] if isinstance(value, list) else []:
227
+ kind, identifier = (token(item.get(key)) if isinstance(item, dict) else None for key in ("kind", "id"))
228
+ if kind is None or identifier is None:
229
+ continue
230
+ workspace, project = (token(cast(dict[str, Any], item).get(key)) for key in ("workspace_id", "project_id"))
231
+ where = f" in workspace {workspace}, project {project} (another project)" if workspace and project else ""
232
+ if line := _text(f"in use by {kind} {identifier}{where}", 200, secrets):
233
+ lines.append(line)
234
+ return lines
235
+
236
+
202
237
  class Download:
203
238
  """Binary response whose transport failures surface only as sanitized codes."""
204
239
 
@@ -253,11 +288,26 @@ class HttpService:
253
288
  self.timeout = timeout
254
289
  self.opener = build_client_opener()
255
290
 
256
- def remote_error(self, error: HTTPError, body: Any = None, **options: Any) -> RemoteError:
257
- from .profile_secrets import submitted_secrets
291
+ def remote_error(self, error: HTTPError, body: Any = None, *, method: str | None = None, **options: Any) -> RemoteError:
292
+ from .profile_secrets import sensitive_profile_request, submitted_secrets
258
293
 
259
294
  fields = error_fields(error, (self.secret, *submitted_secrets(body)))
260
- return RemoteError(fields.pop("code"), error.code, **fields, **options)
295
+ profile_fork = method == 'POST' and re.fullmatch(
296
+ r'POST /v1/profiles/[A-Za-z0-9_-]+/fork', self._route(error.url, method) or '')
297
+ if sensitive_profile_request(body) or profile_fork:
298
+ # Opaque references and arbitrary JSON may carry Secrets whose original
299
+ # value the client never sees. Equality redaction cannot make echoed text safe.
300
+ fields.update(message=None, hint=None, details=[])
301
+ return RemoteError(fields.pop("code"), error.code, **fields, route=self._route(error.url, method), **options)
302
+
303
+ def _route(self, url: str | None, method: str | None) -> str | None:
304
+ # Only paths under this API base, and only path characters: never a host, query or foreign URL.
305
+ if not isinstance(url, str) or not url.startswith(self.base + '/'):
306
+ return None
307
+ path = urlsplit(url).path.removeprefix(urlsplit(self.base).path)
308
+ if not re.fullmatch(r"/[A-Za-z0-9._~%:@=+-]+(?:/[A-Za-z0-9._~%:@=+-]+)*", path) or len(path) > 300:
309
+ return None
310
+ return f"{method} {path}" if method in {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'} else path
261
311
 
262
312
  def request(self, method: str, path: str, body: Any = None, *, headers: dict[str, str] | None = None) -> Any:
263
313
  policy = self.__dict__.get('_request_policy')
@@ -282,7 +332,7 @@ class HttpService:
282
332
  return json.loads(raw) if raw else None
283
333
  except HTTPError as error:
284
334
  delay = retry_after_seconds(error.headers.get("Retry-After")) if error.code == 429 else None
285
- raise self.remote_error(error, body, retry_after=delay) from None
335
+ raise self.remote_error(error, body, method=method, retry_after=delay) from None
286
336
  except (URLError, TimeoutError, OSError, InvalidURL, HTTPException) as error:
287
337
  raise transport_error(error) from None
288
338
  except ValueError:
@@ -301,7 +351,7 @@ class HttpService:
301
351
  return json.loads(raw)
302
352
  except HTTPError as error:
303
353
  delay = retry_after_seconds(error.headers.get('Retry-After')) if error.code == 429 else None
304
- raise self.remote_error(error, retry_after=delay) from None
354
+ raise self.remote_error(error, method='PUT', retry_after=delay) from None
305
355
  except (URLError, TimeoutError, OSError, InvalidURL, HTTPException) as error:
306
356
  raise transport_error(error) from None
307
357
  except ValueError:
@@ -333,7 +383,7 @@ class HttpService:
333
383
  if error.code in REDIRECT_STATUSES:
334
384
  error.close()
335
385
  raise RemoteError('DATA_REDIRECT_REJECTED', error.code) from None
336
- raise self.remote_error(error, retry_after=retry_after_seconds(error.headers.get('Retry-After'))) from None
386
+ raise self.remote_error(error, method='GET', retry_after=retry_after_seconds(error.headers.get('Retry-After'))) from None
337
387
  except (URLError, TimeoutError, OSError, InvalidURL, HTTPException) as error:
338
388
  raise transport_error(error) from None
339
389
 
@@ -127,7 +127,7 @@ class Project:
127
127
  return self._settings_write('/compose', {'enabled': enabled}, expected_version)
128
128
 
129
129
  def model_access(self):
130
- """Model access grants of this project and whether the platform can deliver them now."""
130
+ """Model access grants and configured delivery routes by Job type; health is not checked."""
131
131
  return self.execution_settings()['model_access']
132
132
 
133
133
  def grant_model_access(self, runner: str, protocols: list[str], *, revision: str | None = None,