envloop-cli 2.4.2__py3-none-any.whl → 2.5.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_errors.py +16 -0
- envloop/http.py +18 -1
- envloop_asset/client.py +7 -3
- envloop_asset/dataset_upload.py +3 -5
- envloop_asset/publications.py +7 -3
- envloop_asset/resource_cli.py +3 -1
- envloop_asset/transfer.py +5 -4
- {envloop_cli-2.4.2.dist-info → envloop_cli-2.5.0.dist-info}/METADATA +30 -2
- {envloop_cli-2.4.2.dist-info → envloop_cli-2.5.0.dist-info}/RECORD +17 -17
- envloop_experiment/cli.py +15 -0
- envloop_experiment/job_spec_cli.py +6 -0
- envloop_rsi_loop/cli.py +15 -0
- envloop_rsi_loop/cli_output.py +21 -0
- envloop_rsi_loop/loop_cli.py +52 -5
- envloop_rsi_loop/loops.py +181 -2
- {envloop_cli-2.4.2.dist-info → envloop_cli-2.5.0.dist-info}/WHEEL +0 -0
- {envloop_cli-2.4.2.dist-info → envloop_cli-2.5.0.dist-info}/entry_points.txt +0 -0
envloop/cli_errors.py
CHANGED
|
@@ -187,6 +187,15 @@ _register("INVALID_SANDBOX_IMAGE", "The Sandbox image reference is invalid.")
|
|
|
187
187
|
_register("RSI_LOOP_NOT_FOUND", "No RSI Loop with this LOOP_ID is visible in the current project. List Loops with el loop list.")
|
|
188
188
|
_register("RSI_ITERATION_NOT_FOUND", "The Loop has no Iteration with this number yet. See its Iterations with el loop get LOOP_ID.")
|
|
189
189
|
_register("INVALID_LOOP_ID", "LOOP_ID must be loop_ followed by 32 lower-case hex characters, as el loop list shows it.")
|
|
190
|
+
_register("INVALID_RECONCILIATION_ID", "The reconciliation ID must be rec_ followed by 32 lower-case hex characters.")
|
|
191
|
+
_register("INVALID_RECONCILIATION_DIGEST", "Use the plan's SHA-256 digest (64 lower-case hex characters).")
|
|
192
|
+
_register("INVALID_RECONCILIATION_MODE", "Supply --digest with --apply. Use --spec or --get alone.")
|
|
193
|
+
_register("INVALID_CLOSE_STATE", "Choose completed, failed or cancelled for --state.")
|
|
194
|
+
_register("INVALID_RSI_RECONCILIATION", "Check the request fields. Request IDs must be 1 to 128 characters without whitespace or control characters.")
|
|
195
|
+
_register("RSI_RECONCILIATION_CONFLICT", "The operation conflicts with the saved plan or the current Loop.")
|
|
196
|
+
_register("RSI_RECONCILIATION_BLOCKED", "Unresolved Loop or resource evidence blocks the operation. Review the reconciliation plan and its blockers.")
|
|
197
|
+
_register("RSI_RECONCILIATION_FORBIDDEN", "This operation requires training.run. Historical exceptions require a personal project administrator.")
|
|
198
|
+
_register("RSI_RECONCILIATION_UNAVAILABLE", "Reconciliation is temporarily unavailable. Use --get for a known operation or repeat the identical plan or close request with its original request ID.")
|
|
190
199
|
_register("INVALID_ITERATION", "ITERATION must be a positive integer; Iterations are numbered from 1.")
|
|
191
200
|
_register("INVALID_RSI_REQUEST INVALID_STEER INVALID_DIRECTIVE", "The RSI service rejected the request fields.")
|
|
192
201
|
_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.")
|
|
@@ -399,6 +408,13 @@ def format_error(error: BaseException) -> str:
|
|
|
399
408
|
if remote and isinstance(remote.code, str) and re.fullmatch(r"[A-Z0-9_]{1,128}", remote.code):
|
|
400
409
|
code = remote.code
|
|
401
410
|
local = _http_message(status) if code == "HTTP_ERROR" or code not in _MESSAGES else _MESSAGES[code]
|
|
411
|
+
if code == "RSI_RECONCILIATION_CONFLICT" and remote and isinstance(remote.route, str):
|
|
412
|
+
if remote.route.endswith("/close"):
|
|
413
|
+
local += " Retry loop close with the original request ID and state to check delivery."
|
|
414
|
+
elif remote.route.endswith("/reconciliations"):
|
|
415
|
+
local += " Retry the original proposal with its request ID. A changed proposal needs a fresh request ID."
|
|
416
|
+
else:
|
|
417
|
+
local += " Inspect the saved operation with el loop reconcile LOOP_ID --get RECONCILIATION_ID."
|
|
402
418
|
extra: dict[str, Any] = {"hint": remote.hint, "details": remote.details, "request_id": remote.request_id} if remote else {}
|
|
403
419
|
if remote and status == 404 and isinstance(getattr(remote, "route", None), str):
|
|
404
420
|
# Name the missing API resource; the platform's 404 text stays generic by design.
|
envloop/http.py
CHANGED
|
@@ -282,9 +282,26 @@ class Download:
|
|
|
282
282
|
self.close()
|
|
283
283
|
|
|
284
284
|
|
|
285
|
+
def _check_utf16_keys(pairs: list[tuple[str, Any]]) -> None:
|
|
286
|
+
seen: dict[bytes, str] = {}
|
|
287
|
+
for key, _ in pairs:
|
|
288
|
+
units = key.encode("utf-16-le", "surrogatepass")
|
|
289
|
+
if seen.setdefault(units, key) != key:
|
|
290
|
+
raise ValueError("JSON object keys must be distinct in UTF-16")
|
|
291
|
+
|
|
292
|
+
|
|
285
293
|
def encode_json(body: Any) -> bytes:
|
|
286
294
|
"""Compact UTF-8 request body: \\uXXXX escapes would make CJK text ~2x larger and trip request size limits."""
|
|
287
|
-
|
|
295
|
+
text = json.dumps(body, allow_nan=False, ensure_ascii=False, separators=(",", ":"))
|
|
296
|
+
try:
|
|
297
|
+
return text.encode("utf-8")
|
|
298
|
+
except UnicodeEncodeError:
|
|
299
|
+
pass
|
|
300
|
+
# Check the serialized keys before folding explicit surrogate pairs into
|
|
301
|
+
# scalars. The hook sees each object's original spellings before any merge.
|
|
302
|
+
json.loads(text, object_pairs_hook=_check_utf16_keys)
|
|
303
|
+
text = text.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "surrogatepass")
|
|
304
|
+
return text.encode("utf-8", "backslashreplace")
|
|
288
305
|
|
|
289
306
|
|
|
290
307
|
|
envloop_asset/client.py
CHANGED
|
@@ -259,10 +259,14 @@ class Runners:
|
|
|
259
259
|
raise ValueError('a Runner Asset resource is required')
|
|
260
260
|
return resource
|
|
261
261
|
|
|
262
|
-
def delete(self, asset_id: str, *, dry_run: bool = False):
|
|
263
|
-
"""Preview or retire a Runner through the public Assets lifecycle protections.
|
|
262
|
+
def delete(self, asset_id: str, *, dry_run: bool = False, force: bool = False):
|
|
263
|
+
"""Preview or retire a Runner through the public Assets lifecycle protections.
|
|
264
|
+
|
|
265
|
+
``force`` skips dependency checks; the platform allows it only for a private Runner
|
|
266
|
+
retired by a project admin.
|
|
267
|
+
"""
|
|
264
268
|
from envloop_asset.execution_content import ExecutionContent
|
|
265
|
-
return ExecutionContent(self._server, 'runner').delete(asset_id, dry_run=dry_run)
|
|
269
|
+
return ExecutionContent(self._server, 'runner').delete(asset_id, dry_run=dry_run, force=force)
|
|
266
270
|
|
|
267
271
|
def set_visibility(self, ref: str, *, visibility: str, expected_acl_revision: int):
|
|
268
272
|
from .execution_content import ExecutionContent
|
envloop_asset/dataset_upload.py
CHANGED
|
@@ -56,7 +56,6 @@ def _invalid(message: str):
|
|
|
56
56
|
# mirrored so the CLI refuses before uploading. The server stays authoritative.
|
|
57
57
|
MAX_TASK_DELIVERY_BYTES = 16 * 1024 * 1024
|
|
58
58
|
MAX_MEMBERS = 500_000
|
|
59
|
-
MAX_UNPACKED_BYTES = 2 * 1024 ** 3
|
|
60
59
|
MAX_DEPTH = 32
|
|
61
60
|
PATH_SEGMENT = re.compile(r'[A-Za-z0-9._\[\]-]+')
|
|
62
61
|
|
|
@@ -116,7 +115,7 @@ def check_directory(root: str | Path, *, manifest_text: str | None = None):
|
|
|
116
115
|
manifest = root / 'dataset.toml'
|
|
117
116
|
if manifest.is_symlink() or not manifest.is_file():
|
|
118
117
|
raise _invalid('the Dataset directory must contain dataset.toml at its root')
|
|
119
|
-
cases, members
|
|
118
|
+
cases, members = cast(dict[str, str], {}), 0
|
|
120
119
|
for path in sorted(root.rglob('*')):
|
|
121
120
|
relative = path.relative_to(root)
|
|
122
121
|
if '.git' in relative.parts:
|
|
@@ -131,9 +130,8 @@ def check_directory(root: str | Path, *, manifest_text: str | None = None):
|
|
|
131
130
|
raise _invalid(f'unsupported path {name!r}: use letters, digits, ".", "_", "-", "[" and "]" only')
|
|
132
131
|
if cases.setdefault(name.casefold(), name) != name:
|
|
133
132
|
raise _invalid(f'paths {cases[name.casefold()]!r} and {name!r} differ only in letter case')
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
raise _invalid(f'a Dataset may hold at most {MAX_MEMBERS} files and directories and {MAX_UNPACKED_BYTES} bytes')
|
|
133
|
+
if members > MAX_MEMBERS:
|
|
134
|
+
raise _invalid(f'a Dataset may hold at most {MAX_MEMBERS} files and directories')
|
|
137
135
|
if (root / 'source.toml').exists():
|
|
138
136
|
raise _invalid('external Dataset sources (source.toml) cannot be uploaded')
|
|
139
137
|
document = tomllib.loads(manifest.read_text() if manifest_text is None else manifest_text)
|
envloop_asset/publications.py
CHANGED
|
@@ -67,7 +67,10 @@ def storage_files(manifest: dict[str, Any]) -> list[dict[str, Any]]:
|
|
|
67
67
|
if not isinstance(entries, list) or not 1 <= len(entries) <= 1000:
|
|
68
68
|
raise ValueError('publication requires a bounded native file manifest')
|
|
69
69
|
paths, total = set(), 0
|
|
70
|
-
|
|
70
|
+
schema = canonical_schema(manifest.get('schema'))
|
|
71
|
+
repository = schema == 'envloop.repository-snapshot/v1'
|
|
72
|
+
dataset = repository or (isinstance(schema, str) and schema.startswith('envloop.dataset-records/')) or (
|
|
73
|
+
manifest.get('metadata') == {'format': 'envloop.harbor-task-bundle/v1'})
|
|
71
74
|
projected = []
|
|
72
75
|
for entry in entries:
|
|
73
76
|
expected = {'path', 'size', 'sha256', 'mode'} if repository else {'path', 'size', 'sha256'}
|
|
@@ -78,13 +81,14 @@ def storage_files(manifest: dict[str, Any]) -> list[dict[str, Any]]:
|
|
|
78
81
|
if (not isinstance(path, str) or len(path) > 1024 or path in paths
|
|
79
82
|
or any(not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.-]*', part) or part in ('.', '..')
|
|
80
83
|
for part in path.split('/'))
|
|
81
|
-
or type(size) is not int or not 0 <= size <=
|
|
84
|
+
or type(size) is not int or not 0 <= size <= 2**53 - 1
|
|
85
|
+
or not dataset and size > MAX_FILE
|
|
82
86
|
or not isinstance(digest, str) or not re.fullmatch(r'[a-f0-9]{64}', digest)):
|
|
83
87
|
raise ValueError('invalid file path, size or SHA-256')
|
|
84
88
|
paths.add(path)
|
|
85
89
|
total += size
|
|
86
90
|
projected.append({'path': path, 'size': size, 'sha256': digest})
|
|
87
|
-
if total > MAX_TOTAL or any('/'.join(path.split('/')[:i]) in paths
|
|
91
|
+
if (not dataset and total > MAX_TOTAL) or any('/'.join(path.split('/')[:i]) in paths
|
|
88
92
|
for path in paths for i in range(1, len(path.split('/')))):
|
|
89
93
|
raise ValueError('publication exceeds limits or contains path collisions')
|
|
90
94
|
return sorted(projected, key=lambda item: item['path'])
|
envloop_asset/resource_cli.py
CHANGED
|
@@ -149,6 +149,8 @@ def add_runner_commands(groups: "argparse._SubParsersAction[argparse.ArgumentPar
|
|
|
149
149
|
if action == 'get' else 'Runner ID, fixed ANS URI or NAME@REVISION'))
|
|
150
150
|
if action == 'delete':
|
|
151
151
|
command.add_argument('--dry-run', action='store_true')
|
|
152
|
+
command.add_argument('--force', action='store_true',
|
|
153
|
+
help='Skip dependency checks; allowed only for a private Runner retired by a project admin')
|
|
152
154
|
command.add_argument('--json', action='store_true')
|
|
153
155
|
command = actions.add_parser('set-visibility')
|
|
154
156
|
command.add_argument('ref',metavar='RUNNER_REF')
|
|
@@ -200,7 +202,7 @@ def _execute(args: argparse.Namespace, client: Any):
|
|
|
200
202
|
return client.runners.files(args.ref,limit=args.limit,cursor=args.cursor)
|
|
201
203
|
if args.action == 'download':
|
|
202
204
|
return client.runners.download(args.ref,args.output,file_id=args.file_id,content_digest=args.content_digest,resume=args.resume)
|
|
203
|
-
return client.runners.delete(args.asset_id, dry_run=args.dry_run)
|
|
205
|
+
return client.runners.delete(args.asset_id, dry_run=args.dry_run, force=args.force)
|
|
204
206
|
collection = getattr(client, {'dataset':'datasets','checkpoint':'checkpoints','recipe':'recipes','profile':'profiles'}[args.group])
|
|
205
207
|
if args.action == 'list':
|
|
206
208
|
options = {key:getattr(args,key) for key in ('name','query','visibility','limit','cursor','include_deleted')}
|
envloop_asset/transfer.py
CHANGED
|
@@ -497,10 +497,11 @@ class AssetTransfer:
|
|
|
497
497
|
return self.transport.request('PUT', self._path(asset_id) + '/visibility',
|
|
498
498
|
{'visibility': visibility, 'expected_acl_revision': expected_acl_revision})
|
|
499
499
|
|
|
500
|
-
def delete(self, asset_id: str, *, dry_run: bool = False):
|
|
501
|
-
if type(dry_run) is not bool:
|
|
502
|
-
raise ValueError('dry_run must be
|
|
503
|
-
|
|
500
|
+
def delete(self, asset_id: str, *, dry_run: bool = False, force: bool = False):
|
|
501
|
+
if type(dry_run) is not bool or type(force) is not bool:
|
|
502
|
+
raise ValueError('dry_run and force must be booleans')
|
|
503
|
+
query = '&'.join(name + '=true' for name, value in (('dry_run', dry_run), ('force', force)) if value)
|
|
504
|
+
return self.transport.request('DELETE', self._path(asset_id) + ('?' + query if query else ''))
|
|
504
505
|
|
|
505
506
|
@staticmethod
|
|
506
507
|
def _native_result(result: Any, data_type: str):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: envloop-cli
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.5.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
|
|
@@ -10,7 +10,7 @@ Project-URL: Agent instructions, https://docs.envloop.ai/skill.md
|
|
|
10
10
|
Requires-Python: >=3.12
|
|
11
11
|
Provides-Extra: asset
|
|
12
12
|
Requires-Dist: boto3==1.44.3; extra == 'asset'
|
|
13
|
-
Requires-Dist: envloop-envhub==2.
|
|
13
|
+
Requires-Dist: envloop-envhub==2.5.0; extra == 'asset'
|
|
14
14
|
Provides-Extra: chat
|
|
15
15
|
Requires-Dist: openai==3.55.1; extra == 'chat'
|
|
16
16
|
Provides-Extra: default
|
|
@@ -247,6 +247,11 @@ Omitting the option preserves spec/Profile parameters and the Runner default
|
|
|
247
247
|
setting the same key with `--params` is rejected. The option selects Harbor's
|
|
248
248
|
task environment; platform execution placement remains server configured.
|
|
249
249
|
|
|
250
|
+
Bench Jobs accept `--model-proxy` / `--no-model-proxy` in the same canonical
|
|
251
|
+
`--spec` or named `--profile` forms to set the boolean `model_proxy` parameter.
|
|
252
|
+
Omitting both keeps the spec/Profile value; setting `model_proxy` with `--params`
|
|
253
|
+
as well is rejected.
|
|
254
|
+
|
|
250
255
|
## Existing installations
|
|
251
256
|
|
|
252
257
|
This distribution provides both the CLI and the `envloop` import package. Use a
|
|
@@ -451,3 +456,26 @@ Set `"description": ""` to clear it. Pass a JSON file path or a quoted JSON obje
|
|
|
451
456
|
`training.run` and keeps the Loop ID, execution settings and recorded research.
|
|
452
457
|
Use `client.loops.update(loop_id, spec)` from Python and read the effective `spec`
|
|
453
458
|
with `client.loops.get(loop_id)`. See the [Loop guide](https://docs.envloop.ai/guides/rsi-loops#update-metadata).
|
|
459
|
+
|
|
460
|
+
### Reconcile resources and close a Loop
|
|
461
|
+
|
|
462
|
+
Start with a JSON file such as `reconcile.json` containing `{"request_id":"scan-001"}`.
|
|
463
|
+
|
|
464
|
+
```bash
|
|
465
|
+
el loop reconcile LOOP_ID --spec reconcile.json --json
|
|
466
|
+
el loop reconcile LOOP_ID --get RECONCILIATION_ID --json
|
|
467
|
+
el loop reconcile LOOP_ID --apply RECONCILIATION_ID --digest SHA256 --json
|
|
468
|
+
el loop close LOOP_ID --state completed --request-id close-001 --json
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
Review the plan and its blockers before applying its exact digest. If the apply response is lost, use
|
|
472
|
+
`--get` with the existing reconciliation ID. If planning or closing loses its response, repeat the
|
|
473
|
+
identical request with the original request ID. A close receipt can have local state
|
|
474
|
+
`completed` while report delivery is `report_pending`. Use `el loop get LOOP_ID` to check the
|
|
475
|
+
platform's visible state.
|
|
476
|
+
|
|
477
|
+
In Python, the corresponding methods are `client.loops.reconcile(loop_id, spec)`,
|
|
478
|
+
`reconciliation_get(loop_id, reconciliation_id)`,
|
|
479
|
+
`reconciliation_apply(loop_id, reconciliation_id, digest=digest)`, and
|
|
480
|
+
`close(loop_id, state=state, request_id=request_id)`.
|
|
481
|
+
See the [Loop guide](https://docs.envloop.ai/guides/rsi-loops#reconcile-resources-and-close-a-loop).
|
|
@@ -4,12 +4,12 @@ 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
6
|
envloop/cli.py,sha256=aOgpG-JnBvjviBOizqgQQhm8by8EZvSJblNKebLhTVc,16165
|
|
7
|
-
envloop/cli_errors.py,sha256=
|
|
7
|
+
envloop/cli_errors.py,sha256=NFMjfqL0uluPv6PniYDqy7yOEm8pbk6PJwLikOYJ5i4,50031
|
|
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=
|
|
12
|
+
envloop/http.py,sha256=ObJDx8Rtrtay-iaPWBYxnPhHgR6Vo-AUfHNyR_2iAd4,22372
|
|
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
|
|
@@ -24,8 +24,8 @@ envloop_asset/checkpoint_download.py,sha256=86pq8IXoJCEP6dVaLtgocp8b8rTyuEccK_ec
|
|
|
24
24
|
envloop_asset/checkpoint_upload.py,sha256=BwvLDb862B15MJGjr1lTTu8H6GIyDN5wsVcyoD30WRA,5317
|
|
25
25
|
envloop_asset/cli.py,sha256=mISKgX1xz6UjSwP_4TQeOm89ugmcKctsZUC9DpWpcIw,3776
|
|
26
26
|
envloop_asset/cli_output.py,sha256=XKw5LRuQdorldl2ifJr-R1FDRJbSD2vthGz9GhIWw_U,5637
|
|
27
|
-
envloop_asset/client.py,sha256=
|
|
28
|
-
envloop_asset/dataset_upload.py,sha256=
|
|
27
|
+
envloop_asset/client.py,sha256=_S4KGhDdEWNNvTxD53hPNwQz_MUtFTSrs8veLaFUsbk,20663
|
|
28
|
+
envloop_asset/dataset_upload.py,sha256=nB4khCrcAjV3Ad0tOQ-XBQG2uLcCYEKTvJWDRHkJw9E,19402
|
|
29
29
|
envloop_asset/direct_artifact.py,sha256=1564EPw64MbGiUfMGRFfqHvyocxwA0gx1V5lhaH-jhM,10774
|
|
30
30
|
envloop_asset/direct_checkpoint.py,sha256=sL00wpBfax75G5hYzwJimZ4hE2BeRbpOUntzWEoM9Yw,8718
|
|
31
31
|
envloop_asset/direct_publication.py,sha256=zKBoAWnR6CGzdvsKS5ZZPLWAFDwiC0VFHLp9TxYE2O4,4103
|
|
@@ -36,20 +36,20 @@ envloop_asset/http.py,sha256=v0gLHZFnsjaPnx5Jg3I-ktn-O7rCPu8UnB10zEGhMqg,7965
|
|
|
36
36
|
envloop_asset/navigation_resources.py,sha256=puEAFr6biykIZPpqlowZ-BbRkh0miEp2OdTRP_P8ZkY,14167
|
|
37
37
|
envloop_asset/profile_updates.py,sha256=M0KWqznDY6-MPPfjGNeL4FVTR86_yCRq6OyUJc-tUVY,3387
|
|
38
38
|
envloop_asset/publication_cli.py,sha256=Ey9e8IxobZyHbYHKB_a5fucYXXZFWjYY4ZpuFdG9gm0,3709
|
|
39
|
-
envloop_asset/publications.py,sha256=
|
|
39
|
+
envloop_asset/publications.py,sha256=pD6NFiK4imUedV3lmvMYVdfRnKljtSCMuUX-w_cGxKA,9463
|
|
40
40
|
envloop_asset/r2_upload.py,sha256=m-L1Z7L7fQvJNVA9pGzwSGGOTv1_COC5OVSjUIQfxMU,1605
|
|
41
41
|
envloop_asset/recipe_packages.py,sha256=HA7RT2T6Lt94cl5_4ye3wPxxQd8lCo2_HdAeuq3yQvQ,5957
|
|
42
42
|
envloop_asset/recipes.py,sha256=We2TZWdRl-ialV-uLFvUSvJng9P2HGquqGtqKYKllgs,1442
|
|
43
|
-
envloop_asset/resource_cli.py,sha256=
|
|
43
|
+
envloop_asset/resource_cli.py,sha256=z1LapF8BjcZwELnSSqfKLMNsv-n19gALYD7w7OB2N9k,20753
|
|
44
44
|
envloop_asset/runner_packages.py,sha256=ve4UIUBBxoJ6h7LOSpiP6Tox00nak2v6K95hZ0VqvVM,6639
|
|
45
45
|
envloop_asset/tags.py,sha256=wFP0Rg-avOmYkpyYqNGdJrnGreHEli-O5_eH9Liat6c,2016
|
|
46
|
-
envloop_asset/transfer.py,sha256=
|
|
46
|
+
envloop_asset/transfer.py,sha256=LWTf_rGymac3bHX_zQdXh9OtAbutFkiL_SIPFVNx6KQ,53394
|
|
47
47
|
envloop_asset/upload_strategy.py,sha256=RP-mNtM4yHQ0YmwocsTKD7MOS2asCoWnI44AtCI9LVw,605
|
|
48
48
|
envloop_chat/__init__.py,sha256=pEW8SHBlrQr2_9UFm45unSUg-GP6rY04V3O27bspOuQ,75
|
|
49
49
|
envloop_chat/cli.py,sha256=aUoflpsBWl-U4vrzZP4xsZrvc0md-zuSsCB6APeIk8Q,5783
|
|
50
50
|
envloop_chat/client.py,sha256=CUCG0jBXJplsXsDNOdu-R-v9O-dVrMMVycNMZUS5b9M,7215
|
|
51
51
|
envloop_experiment/__init__.py,sha256=nKDGmzFNAQv2mq16YijiI3Q-gDL_smNyZD-AQaqoz7Y,68
|
|
52
|
-
envloop_experiment/cli.py,sha256=
|
|
52
|
+
envloop_experiment/cli.py,sha256=WAu0kwdQG3YG7GpYxeWGmr2UGL9-bLpdNftKT1Lsl64,44670
|
|
53
53
|
envloop_experiment/cli_output.py,sha256=aM6eajuMDheWb2GA956UE0_y-6_tC0MCdC23ulROHi4,5196
|
|
54
54
|
envloop_experiment/client.py,sha256=9V3GRxOc7Fru7dgOUtZsqW-zjwnzb4PQghh5XyVCwsU,41772
|
|
55
55
|
envloop_experiment/decision.py,sha256=HJTj-jSJJ5kcxQQzFXwrA9IICWXA6zSNBFL9EbbrxqI,918
|
|
@@ -57,7 +57,7 @@ envloop_experiment/http.py,sha256=wQ81Pz_daVRGFDIZQnIgTKRyOWWBgxF8xi4kM9UE6tQ,69
|
|
|
57
57
|
envloop_experiment/inference.py,sha256=GPg1LNPk1-ce1txSJWTkJ0qhNXxhFfP0cBwNt_fyQJ4,5662
|
|
58
58
|
envloop_experiment/job_cost.py,sha256=gZB69-pdsJM4wManw44AIS9T3ZtsxxQTqrJs-cHjwJU,2214
|
|
59
59
|
envloop_experiment/job_logs.py,sha256=RLipbj89e5hQdBeXtszsxSYYw7By1hscwSTGFQzQ3Qw,1340
|
|
60
|
-
envloop_experiment/job_spec_cli.py,sha256=
|
|
60
|
+
envloop_experiment/job_spec_cli.py,sha256=0s2DO8Mb4X6FVblIjyE66NuOPm7dPaJXzYfWMTRJQCw,14901
|
|
61
61
|
envloop_experiment/named_profile.py,sha256=niaJm3WZPH98PNfqpN8RMg18AO5zWTlI88rOnJ2DgSY,9349
|
|
62
62
|
envloop_experiment/navigation_resources.py,sha256=sbatQySVNKftZZ-HKU1mwihoJWaTPYGeLO_dJLr2EHY,1755
|
|
63
63
|
envloop_experiment/resource_cli.py,sha256=BfzQrvaq_Y_EL1OQUSxYtlWhf_SdTwJyU2omxFccn-g,2002
|
|
@@ -71,11 +71,11 @@ envloop_experiment/train_progress.py,sha256=9YO6CkTc7-LCpUpY8juf6GPF58kCU2rxc4iZ
|
|
|
71
71
|
envloop_experiment/train_runner_cli.py,sha256=XJ-woz80M6ngsArlyP-dVT4CeTeT-O2PXKP5vcSQriE,3811
|
|
72
72
|
envloop_experiment/training/__init__.py,sha256=IEQWbCHe-zZ2e7JQxOrFOdYlSQxMfOceCZUf_KeszBk,221
|
|
73
73
|
envloop_rsi_loop/__init__.py,sha256=nKDGmzFNAQv2mq16YijiI3Q-gDL_smNyZD-AQaqoz7Y,68
|
|
74
|
-
envloop_rsi_loop/cli.py,sha256=
|
|
75
|
-
envloop_rsi_loop/cli_output.py,sha256=
|
|
76
|
-
envloop_rsi_loop/loop_cli.py,sha256=
|
|
77
|
-
envloop_rsi_loop/loops.py,sha256=
|
|
78
|
-
envloop_cli-2.
|
|
79
|
-
envloop_cli-2.
|
|
80
|
-
envloop_cli-2.
|
|
81
|
-
envloop_cli-2.
|
|
74
|
+
envloop_rsi_loop/cli.py,sha256=APbb6VtB6-tQxHC-7O2f1kt99rgNPl8t3d10wxkqLok,5873
|
|
75
|
+
envloop_rsi_loop/cli_output.py,sha256=ba5EPYfyIyGBEZtZ1rkWGhDFu9mFcZYixsBXi9w9HSQ,5746
|
|
76
|
+
envloop_rsi_loop/loop_cli.py,sha256=EeU8ndZhBFDkeEDEjZve3d7RIQ0aA4OPCCn-KeniPKk,6906
|
|
77
|
+
envloop_rsi_loop/loops.py,sha256=seX3NIWTsqYpPn5QYzkXYU_fvUiG0CeKpdLKHOrLkhQ,18326
|
|
78
|
+
envloop_cli-2.5.0.dist-info/METADATA,sha256=jntBtXjyJyQ46JGZ9jGYs0aMLixy1kEho1XaPJX2LB8,24695
|
|
79
|
+
envloop_cli-2.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
80
|
+
envloop_cli-2.5.0.dist-info/entry_points.txt,sha256=8aXOpgtVk4GndhChA4XNecShkb1w0xGHBHrKla78ofI,67
|
|
81
|
+
envloop_cli-2.5.0.dist-info/RECORD,,
|
envloop_experiment/cli.py
CHANGED
|
@@ -166,6 +166,12 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]"):
|
|
|
166
166
|
help='Bench/Sandbox canonical --spec or named --profile: Harbor task environment; '
|
|
167
167
|
'omitted uses the Runner default (docker). '
|
|
168
168
|
'Cannot also set harbor_env with --params')
|
|
169
|
+
model_proxy = job_submit.add_mutually_exclusive_group()
|
|
170
|
+
model_proxy.add_argument('--model-proxy', dest='model_proxy', action='store_const', const=True, default=None,
|
|
171
|
+
help='Bench canonical --spec or named --profile: set the boolean model_proxy parameter; '
|
|
172
|
+
'omitted preserves the spec/Profile value. Cannot also set model_proxy with --params')
|
|
173
|
+
model_proxy.add_argument('--no-model-proxy', dest='model_proxy', action='store_const', const=False,
|
|
174
|
+
help='Bench canonical --spec or named --profile: set model_proxy to false')
|
|
169
175
|
job_submit.add_argument("--seed", type=int)
|
|
170
176
|
job_submit.add_argument("--timeout-seconds", type=wait_seconds,
|
|
171
177
|
help="Bench/Sandbox or Train Runner execution timeout (whole seconds); Train recipe --wait timeout (default: 600)")
|
|
@@ -375,6 +381,11 @@ def validate(args: argparse.Namespace, cli: argparse.ArgumentParser):
|
|
|
375
381
|
cli.error('--harbor_env applies only to Bench/Sandbox Jobs')
|
|
376
382
|
if any(key.lower() == 'harbor_env' for key in (getattr(args, 'named_parameters', None) or {})):
|
|
377
383
|
cli.error('--harbor_env and --params cannot both set harbor_env')
|
|
384
|
+
if args.model_proxy is not None:
|
|
385
|
+
if args.type != 'bench':
|
|
386
|
+
cli.error('--model-proxy and --no-model-proxy apply only to Bench Jobs')
|
|
387
|
+
if any(key.lower() == 'model_proxy' for key in (getattr(args, 'named_parameters', None) or {})):
|
|
388
|
+
cli.error('--model-proxy/--no-model-proxy and --params cannot both set model_proxy')
|
|
378
389
|
if args.provider is not None and args.type not in {'bench', 'sandbox'}:
|
|
379
390
|
cli.error('--provider requires a Bench/Sandbox Job')
|
|
380
391
|
named_mode = args.spec is None and args.profile is not None and (
|
|
@@ -402,11 +413,15 @@ def validate(args: argparse.Namespace, cli: argparse.ArgumentParser):
|
|
|
402
413
|
resources=requested_resources(args) or None, provider=args.provider)
|
|
403
414
|
if args.harbor_env is not None:
|
|
404
415
|
args.named_request['parameters']['harbor_env'] = args.harbor_env
|
|
416
|
+
if args.model_proxy is not None:
|
|
417
|
+
args.named_request['parameters']['model_proxy'] = args.model_proxy
|
|
405
418
|
except (TypeError, ValueError) as exc:
|
|
406
419
|
cli.error(str(exc))
|
|
407
420
|
return None
|
|
408
421
|
if args.harbor_env is not None and args.spec is None:
|
|
409
422
|
cli.error('--harbor_env requires a canonical --spec or a named --profile')
|
|
423
|
+
if args.model_proxy is not None and args.spec is None:
|
|
424
|
+
cli.error('--model-proxy and --no-model-proxy require a canonical --spec or a named --profile')
|
|
410
425
|
if args.spec is None and args.params is not None and args.type not in {'bench', 'sandbox'}:
|
|
411
426
|
cli.error('--params applies to Bench/Sandbox declared Runner runtime parameters')
|
|
412
427
|
runner_mode = args.type == 'train' and args.spec is None
|
|
@@ -77,6 +77,8 @@ def spec_request(args: argparse.Namespace):
|
|
|
77
77
|
request['type'] = kind
|
|
78
78
|
if args.harbor_env is not None:
|
|
79
79
|
raise ValueError('--harbor_env requires a canonical --spec with schema envloop.job/v1 or a named --profile')
|
|
80
|
+
if getattr(args, 'model_proxy', None) is not None:
|
|
81
|
+
raise ValueError('--model-proxy and --no-model-proxy require a canonical --spec or a named --profile')
|
|
80
82
|
if getattr(args, 'provider', None) is not None:
|
|
81
83
|
request['provider'] = args.provider
|
|
82
84
|
validate_public_execution(request)
|
|
@@ -219,6 +221,8 @@ def unified_request(args: argparse.Namespace, request: dict[str, Any]) -> dict[s
|
|
|
219
221
|
args.type = kind
|
|
220
222
|
if args.harbor_env is not None and kind not in {'bench', 'sandbox'}:
|
|
221
223
|
raise ValueError('--harbor_env applies only to Bench/Sandbox Jobs')
|
|
224
|
+
if getattr(args, 'model_proxy', None) is not None and kind != 'bench':
|
|
225
|
+
raise ValueError('--model-proxy and --no-model-proxy apply only to Bench Jobs')
|
|
222
226
|
incompatible = ('dataset', 'dataset_option', 'source', 'task_id', 'config', 'split', 'revision',
|
|
223
227
|
'job_id', 'tag', 'attempts', 'profile', 'delete_delay_seconds', *TRAIN_ONLY_FIELDS)
|
|
224
228
|
if any(getattr(args, key, None) is not None for key in incompatible):
|
|
@@ -237,6 +241,8 @@ def unified_request(args: argparse.Namespace, request: dict[str, Any]) -> dict[s
|
|
|
237
241
|
params.update(getattr(args, 'named_parameters', None) or {})
|
|
238
242
|
if args.harbor_env is not None:
|
|
239
243
|
params['harbor_env'] = args.harbor_env
|
|
244
|
+
if getattr(args, 'model_proxy', None) is not None:
|
|
245
|
+
params['model_proxy'] = args.model_proxy
|
|
240
246
|
for key in ('command', 'image', 'seed'):
|
|
241
247
|
if getattr(args, key) is not None:
|
|
242
248
|
params[key] = getattr(args, key)
|
envloop_rsi_loop/cli.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import argparse
|
|
2
2
|
|
|
3
|
+
from envloop_rsi_loop.loops import CLOSE_STATES
|
|
4
|
+
|
|
3
5
|
LOOP_ID_HELP = "loop_ followed by 32 lower-case hex characters, as shown by el loop list"
|
|
4
6
|
|
|
5
7
|
|
|
@@ -25,6 +27,19 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]"):
|
|
|
25
27
|
update.add_argument("loop_id", metavar="LOOP_ID", help=LOOP_ID_HELP)
|
|
26
28
|
update.add_argument("--spec", required=True, metavar="FILE|JSON",
|
|
27
29
|
help="JSON file path or inline envloop.loop/v1 JSON object; supplied name/description override, omitted fields stay")
|
|
30
|
+
reconcile = loops.add_parser("reconcile", help="Plan, inspect or apply audited Loop reconciliation")
|
|
31
|
+
reconcile.add_argument("loop_id", metavar="LOOP_ID", help=LOOP_ID_HELP)
|
|
32
|
+
mode = reconcile.add_mutually_exclusive_group(required=True)
|
|
33
|
+
mode.add_argument("--spec", metavar="FILE", help="Plan reconciliation from a JSON file with a request_id")
|
|
34
|
+
mode.add_argument("--get", metavar="ID", help="Read a saved plan or receipt, including after a lost apply response")
|
|
35
|
+
mode.add_argument("--apply", metavar="ID", help="Apply the reviewed plan with --digest")
|
|
36
|
+
reconcile.add_argument("--digest", metavar="SHA256", help="Exact lowercase SHA-256 from the plan, required with --apply")
|
|
37
|
+
reconcile.add_argument("--json", action="store_true", help="Output the complete plan or receipt as JSON")
|
|
38
|
+
close = loops.add_parser("close", help="Explicitly close a Loop and show report delivery status")
|
|
39
|
+
close.add_argument("loop_id", metavar="LOOP_ID", help=LOOP_ID_HELP)
|
|
40
|
+
close.add_argument("--state", required=True, choices=CLOSE_STATES, help="Terminal state for local closure")
|
|
41
|
+
close.add_argument("--request-id", required=True, metavar="ID", help="Reuse this request ID with the same state to check delivery")
|
|
42
|
+
close.add_argument("--json", action="store_true", help="Output the complete closure receipt as JSON")
|
|
28
43
|
iteration = loops.add_parser("iteration", help="Read one Iteration of a Loop").add_subparsers(
|
|
29
44
|
dest="iteration_action", required=True)
|
|
30
45
|
iteration_get = iteration.add_parser("get", help="Show one Iteration's decision, summary and audits")
|
envloop_rsi_loop/cli_output.py
CHANGED
|
@@ -60,6 +60,27 @@ def _summary(fields: tuple[tuple[str, Any], ...]) -> str:
|
|
|
60
60
|
for label, value in fields)
|
|
61
61
|
|
|
62
62
|
|
|
63
|
+
def reconciliation_output(receipt: dict[str, Any]) -> str:
|
|
64
|
+
return _summary((
|
|
65
|
+
("Loop ID", receipt.get("loop_id")),
|
|
66
|
+
("Reconciliation ID", receipt.get("reconciliation_id")),
|
|
67
|
+
("Status", receipt.get("status")),
|
|
68
|
+
("Digest", receipt.get("digest")),
|
|
69
|
+
("Blockers", receipt.get("blocker_count", len(receipt["blockers"]))),
|
|
70
|
+
("Expires at", timestamp(receipt.get("expires_at"))),
|
|
71
|
+
)) + "\nUse --json to review entries and blockers."
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def close_output(receipt: dict[str, Any]) -> str:
|
|
75
|
+
return _summary((
|
|
76
|
+
("Loop ID", receipt.get("loop_id")),
|
|
77
|
+
("Request ID", receipt.get("request_id")),
|
|
78
|
+
("Local state", receipt.get("state")),
|
|
79
|
+
("Report delivery", receipt.get("delivery")),
|
|
80
|
+
("Ended at", timestamp(receipt.get("ended_at"))),
|
|
81
|
+
))
|
|
82
|
+
|
|
83
|
+
|
|
63
84
|
def _checkpoint_name(checkpoint: Any) -> Any:
|
|
64
85
|
if not isinstance(checkpoint, dict):
|
|
65
86
|
return None
|
envloop_rsi_loop/loop_cli.py
CHANGED
|
@@ -7,8 +7,17 @@ import time
|
|
|
7
7
|
from pathlib import Path
|
|
8
8
|
from typing import TYPE_CHECKING, Any
|
|
9
9
|
|
|
10
|
+
from envloop.http import RemoteError
|
|
10
11
|
from envloop.terminal import safe_text, status_text, style
|
|
11
|
-
from envloop_rsi_loop.loops import
|
|
12
|
+
from envloop_rsi_loop.loops import (
|
|
13
|
+
LoopError,
|
|
14
|
+
loop_path,
|
|
15
|
+
reconciliation_path,
|
|
16
|
+
reconciliation_spec,
|
|
17
|
+
valid_digest,
|
|
18
|
+
valid_iteration,
|
|
19
|
+
validate_request_id,
|
|
20
|
+
)
|
|
12
21
|
|
|
13
22
|
if TYPE_CHECKING:
|
|
14
23
|
from envloop_rsi_loop.loops import Loops
|
|
@@ -18,7 +27,7 @@ POLL_SECONDS = 3.0
|
|
|
18
27
|
|
|
19
28
|
|
|
20
29
|
def validate(args: argparse.Namespace) -> None:
|
|
21
|
-
"""
|
|
30
|
+
"""Validate local Loop command inputs before connecting."""
|
|
22
31
|
if getattr(args, "loop_id", None) is not None:
|
|
23
32
|
loop_path(args.loop_id)
|
|
24
33
|
if getattr(args, "iteration", None) is not None:
|
|
@@ -33,6 +42,17 @@ def validate(args: argparse.Namespace) -> None:
|
|
|
33
42
|
if not isinstance(spec, dict):
|
|
34
43
|
raise ValueError("Loop spec must be a JSON object")
|
|
35
44
|
args.loop_spec = spec
|
|
45
|
+
if args.action == "reconcile":
|
|
46
|
+
if (args.apply is None) != (args.digest is None):
|
|
47
|
+
raise LoopError("INVALID_RECONCILIATION_MODE")
|
|
48
|
+
if args.spec is not None:
|
|
49
|
+
args.loop_spec = reconciliation_spec(json.loads(Path(args.spec).read_text(encoding="utf-8")))
|
|
50
|
+
else:
|
|
51
|
+
reconciliation_path(args.loop_id, args.get if args.get is not None else args.apply)
|
|
52
|
+
if args.digest is not None:
|
|
53
|
+
valid_digest(args.digest)
|
|
54
|
+
if args.action == "close":
|
|
55
|
+
validate_request_id(args.request_id)
|
|
36
56
|
|
|
37
57
|
|
|
38
58
|
def _brief(args: argparse.Namespace) -> str:
|
|
@@ -68,8 +88,7 @@ def _follow(loops: "Loops", loop_id: str, since: int | None, *, as_json: bool =
|
|
|
68
88
|
|
|
69
89
|
def loop_jobs(client: Any, detail: dict[str, Any]) -> dict[str, Any]:
|
|
70
90
|
"""The Loop's Train Jobs for the detail view; a failed lookup is shown, not raised."""
|
|
71
|
-
from
|
|
72
|
-
from envloop_rsi_loop.loops import LoopError, train_jobs
|
|
91
|
+
from envloop_rsi_loop.loops import train_jobs
|
|
73
92
|
name = detail.get("legacy_name", detail.get("name"))
|
|
74
93
|
try:
|
|
75
94
|
return train_jobs(client.training_jobs, detail.get("loop_id") or "", name=name if isinstance(name, str) else None)
|
|
@@ -80,7 +99,14 @@ def loop_jobs(client: Any, detail: dict[str, Any]) -> dict[str, Any]:
|
|
|
80
99
|
|
|
81
100
|
def execute(args: argparse.Namespace, client: Any) -> dict[str, Any]:
|
|
82
101
|
"""Run one ``loop`` action; returns the result to print, or exits after printing its own output."""
|
|
83
|
-
|
|
102
|
+
try:
|
|
103
|
+
result = _run(args, client)
|
|
104
|
+
except RemoteError as error:
|
|
105
|
+
if args.action in {"reconcile", "close"}:
|
|
106
|
+
# The CLI uses static guidance for this error code. Remote diagnostics can include ledger data.
|
|
107
|
+
route = error.route if error.code == "RSI_RECONCILIATION_CONFLICT" else None
|
|
108
|
+
raise RemoteError(error.code, error.status_code, retry_after=error.retry_after, route=route) from None
|
|
109
|
+
raise
|
|
84
110
|
if result is None:
|
|
85
111
|
from envloop._optional import CommandExit
|
|
86
112
|
raise CommandExit(0)
|
|
@@ -94,6 +120,27 @@ def _run(args: argparse.Namespace, client: Any) -> dict[str, Any] | None:
|
|
|
94
120
|
return loops.list()
|
|
95
121
|
if action == "update":
|
|
96
122
|
return loops.update(args.loop_id, args.loop_spec)
|
|
123
|
+
if action == "reconcile":
|
|
124
|
+
from envloop_rsi_loop.cli_output import reconciliation_output
|
|
125
|
+
|
|
126
|
+
if args.spec is not None:
|
|
127
|
+
result = loops.reconcile(args.loop_id, args.loop_spec)
|
|
128
|
+
elif args.get is not None:
|
|
129
|
+
result = loops.reconciliation_get(args.loop_id, args.get)
|
|
130
|
+
else:
|
|
131
|
+
result = loops.reconciliation_apply(args.loop_id, args.apply, digest=args.digest)
|
|
132
|
+
if args.json:
|
|
133
|
+
return result
|
|
134
|
+
print(reconciliation_output(result))
|
|
135
|
+
return None
|
|
136
|
+
if action == "close":
|
|
137
|
+
from envloop_rsi_loop.cli_output import close_output
|
|
138
|
+
|
|
139
|
+
result = loops.close(args.loop_id, state=args.state, request_id=args.request_id)
|
|
140
|
+
if args.json:
|
|
141
|
+
return result
|
|
142
|
+
print(close_output(result))
|
|
143
|
+
return None
|
|
97
144
|
if action == "get":
|
|
98
145
|
detail = loops.get(args.loop_id)
|
|
99
146
|
if not args.json:
|
envloop_rsi_loop/loops.py
CHANGED
|
@@ -1,21 +1,42 @@
|
|
|
1
1
|
"""RSI Loops: the platform's ``/v1/rsi/loops`` API, plus the Train Jobs each Loop launched.
|
|
2
2
|
|
|
3
3
|
A Loop is one research process toward a goal (``loop_id`` is ``loop_<32 hex>``); each of its
|
|
4
|
-
Iterations (numbered from 1) plans, trains, evaluates and decides. The platform owns
|
|
5
|
-
|
|
4
|
+
Iterations (numbered from 1) plans, trains, evaluates and decides. The platform owns Loop state
|
|
5
|
+
and validates reconciliation evidence.
|
|
6
6
|
|
|
7
7
|
Train Jobs carry the Loop in their tags: ``rsi_loop`` / ``rsi_iteration`` for new Jobs, and the
|
|
8
8
|
historical ``rsi_run`` (the Loop's name) / ``rsi_round`` on Jobs created before the rename.
|
|
9
9
|
"""
|
|
10
10
|
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
11
13
|
import re
|
|
14
|
+
from collections.abc import Callable
|
|
12
15
|
from datetime import datetime
|
|
16
|
+
from decimal import Decimal
|
|
13
17
|
from typing import Any
|
|
14
18
|
from urllib.parse import quote, urlencode
|
|
15
19
|
|
|
20
|
+
from envloop.http import encode_json
|
|
16
21
|
from envloop_experiment.train import TrainJobs
|
|
17
22
|
|
|
18
23
|
LOOP_ID = re.compile(r"loop_[a-f0-9]{32}")
|
|
24
|
+
RECONCILIATION_ID = re.compile(r"rec_[a-f0-9]{32}")
|
|
25
|
+
SHA256 = re.compile(r"[a-f0-9]{64}")
|
|
26
|
+
CLOSE_STATES = ("completed", "failed", "cancelled")
|
|
27
|
+
RECONCILIATION_FIELDS = {"request_id", "entries", "observed_jobs", "release_attestations"}
|
|
28
|
+
RECONCILIATION_ENTRY_FIELDS = {"entry", "disposition", "job_ids", "reason", "evidence"}
|
|
29
|
+
RECONCILIATION_DISPOSITIONS = ("job_link", "not_created", "operator_attested")
|
|
30
|
+
RECONCILIATION_JOB_ID = re.compile(r"job_[a-zA-Z0-9]{20,124}")
|
|
31
|
+
UNSAFE_EVIDENCE_KEY = re.compile(
|
|
32
|
+
r"actor|role|can_attest|approved|command|cmd|argv|shell|script|exec|executable|path|ledger|"
|
|
33
|
+
r"raw_ledger|ended_at|cleanup_confirmed|__proto__|constructor|prototype", re.IGNORECASE | re.ASCII)
|
|
34
|
+
# Match the platform's ECMAScript \s and String.trim() when checking opaque IDs and reasons.
|
|
35
|
+
JS_WHITESPACE = (
|
|
36
|
+
"\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
|
|
37
|
+
"\u2028\u2029\u202f\u205f\u3000\ufeff"
|
|
38
|
+
)
|
|
39
|
+
INVALID_REQUEST_ID_CHAR = re.compile(r"[\x00-\x1f\x7f" + re.escape(JS_WHITESPACE) + "]")
|
|
19
40
|
TERMINAL_STATUSES = frozenset({"SUCCEEDED", "FAILED", "CANCELLED", "completed", "failed", "cancelled"})
|
|
20
41
|
PAGE_LIMIT = 100 # the platform's maximum page size
|
|
21
42
|
MAX_PAGES = 10 # the Console's bound: the 1000 newest Train Jobs of the project
|
|
@@ -35,6 +56,143 @@ def loop_path(loop_id: str) -> str:
|
|
|
35
56
|
return "/v1/rsi/loops/" + quote(loop_id, safe="")
|
|
36
57
|
|
|
37
58
|
|
|
59
|
+
def reconciliation_path(loop_id: str, reconciliation_id: str) -> str:
|
|
60
|
+
path = loop_path(loop_id)
|
|
61
|
+
if not isinstance(reconciliation_id, str) or not RECONCILIATION_ID.fullmatch(reconciliation_id):
|
|
62
|
+
raise LoopError("INVALID_RECONCILIATION_ID")
|
|
63
|
+
return f"{path}/reconciliations/{reconciliation_id}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def valid_digest(digest: str) -> str:
|
|
67
|
+
if not isinstance(digest, str) or not SHA256.fullmatch(digest):
|
|
68
|
+
raise LoopError("INVALID_RECONCILIATION_DIGEST")
|
|
69
|
+
return digest
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def reconciliation_spec(spec: object) -> dict[str, Any]:
|
|
73
|
+
if not isinstance(spec, dict) or spec.keys() - RECONCILIATION_FIELDS:
|
|
74
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
75
|
+
validate_request_id(spec.get("request_id"))
|
|
76
|
+
try:
|
|
77
|
+
_validate_distinct_items(spec.get("entries", []), _entry_line)
|
|
78
|
+
_validate_distinct_items(spec.get("observed_jobs", []), _reconciliation_job_id)
|
|
79
|
+
_validate_distinct_items(spec.get("release_attestations", []), _release_job_id)
|
|
80
|
+
size = len(encode_json(spec))
|
|
81
|
+
except (TypeError, ValueError, OverflowError, RecursionError):
|
|
82
|
+
raise LoopError("INVALID_RSI_RECONCILIATION") from None
|
|
83
|
+
if size > 256 * 1024:
|
|
84
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
85
|
+
return spec
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def validate_request_id(request_id: object) -> None:
|
|
89
|
+
if not isinstance(request_id, str) or not 1 <= len(request_id) <= 128 or INVALID_REQUEST_ID_CHAR.search(request_id):
|
|
90
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _validate_distinct_items(items: object, identity: Callable[[object], str | int | float]) -> None:
|
|
94
|
+
if not isinstance(items, list) or len(items) > 256:
|
|
95
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
96
|
+
if len({identity(item) for item in items}) != len(items):
|
|
97
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _reconciliation_job_id(value: object) -> str:
|
|
101
|
+
if not isinstance(value, str) or not RECONCILIATION_JOB_ID.fullmatch(value):
|
|
102
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
103
|
+
return value
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _validate_reconciliation_reason(value: object) -> None:
|
|
107
|
+
if (not isinstance(value, str) or not value.strip(JS_WHITESPACE)
|
|
108
|
+
or len(value.encode("utf-16-le", errors="surrogatepass")) // 2 > 2048):
|
|
109
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _release_job_id(value: object) -> str:
|
|
113
|
+
if not isinstance(value, dict) or not {"job_id", "reason"} <= value.keys() or value.keys() - {
|
|
114
|
+
"job_id", "reason", "supersedes", "withdraw"}:
|
|
115
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
116
|
+
if "supersedes" in value and (not isinstance(value["supersedes"], str) or not RECONCILIATION_ID.fullmatch(value["supersedes"])):
|
|
117
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
118
|
+
if "withdraw" in value and (value["withdraw"] is not True or "supersedes" not in value):
|
|
119
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
120
|
+
_validate_reconciliation_reason(value["reason"])
|
|
121
|
+
return _reconciliation_job_id(value["job_id"])
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _evidence_bytes(value: Any) -> int:
|
|
125
|
+
"""UTF-8 length of compact JSON after the public API's binary64 number parsing."""
|
|
126
|
+
if isinstance(value, dict):
|
|
127
|
+
return 2 + max(0, len(value) - 1) + sum(_evidence_bytes(k) + 1 + _evidence_bytes(v) for k, v in value.items())
|
|
128
|
+
if isinstance(value, (list, tuple)):
|
|
129
|
+
return 2 + max(0, len(value) - 1) + sum(_evidence_bytes(v) for v in value)
|
|
130
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
131
|
+
number = float(value)
|
|
132
|
+
if not math.isfinite(number):
|
|
133
|
+
raise ValueError("non-finite evidence number")
|
|
134
|
+
if not number:
|
|
135
|
+
return 1
|
|
136
|
+
decimal = Decimal(repr(abs(number)))
|
|
137
|
+
# adjusted() and as_tuple() only inspect the exact literal. normalize()
|
|
138
|
+
# would round using the application's active decimal context.
|
|
139
|
+
digits = len("".join(map(str, decimal.as_tuple().digits)).rstrip("0"))
|
|
140
|
+
power = decimal.adjusted()
|
|
141
|
+
if -6 <= power < 21:
|
|
142
|
+
fraction = max(0, digits - power - 1)
|
|
143
|
+
return int(number < 0) + max(1, power + 1) + int(fraction > 0) + fraction
|
|
144
|
+
return int(number < 0) + digits + int(digits > 1) + 2 + len(str(abs(power)))
|
|
145
|
+
return len(encode_json(value))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _safe_evidence_keys(value: object) -> bool:
|
|
149
|
+
if isinstance(value, dict):
|
|
150
|
+
names: set[bytes] = set()
|
|
151
|
+
for key, item in value.items():
|
|
152
|
+
if not isinstance(key, str) or UNSAFE_EVIDENCE_KEY.fullmatch(key):
|
|
153
|
+
return False
|
|
154
|
+
# ECMAScript property names are sequences of UTF-16 code units.
|
|
155
|
+
name = key.encode("utf-16-le", errors="surrogatepass")
|
|
156
|
+
if name in names or not _safe_evidence_keys(item):
|
|
157
|
+
return False
|
|
158
|
+
names.add(name)
|
|
159
|
+
return True
|
|
160
|
+
if isinstance(value, (list, tuple)):
|
|
161
|
+
return all(_safe_evidence_keys(item) for item in value)
|
|
162
|
+
return True
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _entry_line(value: object) -> int | float:
|
|
166
|
+
if not isinstance(value, dict) or value.keys() - RECONCILIATION_ENTRY_FIELDS:
|
|
167
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
168
|
+
reference = value.get("entry")
|
|
169
|
+
if not isinstance(reference, dict) or reference.keys() != {"line", "sha256"}:
|
|
170
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
171
|
+
line, digest = reference["line"], reference["sha256"]
|
|
172
|
+
if (isinstance(line, bool) or not isinstance(line, (int, float))
|
|
173
|
+
or not 1 <= line < 2**53 or line % 1 != 0
|
|
174
|
+
or not isinstance(digest, str) or not SHA256.fullmatch(digest)):
|
|
175
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
176
|
+
disposition = value.get("disposition")
|
|
177
|
+
if disposition not in RECONCILIATION_DISPOSITIONS:
|
|
178
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
179
|
+
if disposition == "job_link":
|
|
180
|
+
ids = value.get("job_ids")
|
|
181
|
+
_validate_distinct_items(ids, _reconciliation_job_id)
|
|
182
|
+
if not ids:
|
|
183
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
184
|
+
elif "job_ids" in value:
|
|
185
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
186
|
+
if "reason" in value:
|
|
187
|
+
_validate_reconciliation_reason(value["reason"])
|
|
188
|
+
evidence = value.get("evidence")
|
|
189
|
+
if "evidence" in value and (not isinstance(evidence, dict) or _evidence_bytes(evidence) > 4096 or not _safe_evidence_keys(evidence)):
|
|
190
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
191
|
+
if disposition == "operator_attested" and (not value.get("reason") or not evidence):
|
|
192
|
+
raise LoopError("INVALID_RSI_RECONCILIATION")
|
|
193
|
+
return line
|
|
194
|
+
|
|
195
|
+
|
|
38
196
|
def valid_iteration(iteration: int) -> int:
|
|
39
197
|
if isinstance(iteration, bool) or not isinstance(iteration, int) or iteration < 1:
|
|
40
198
|
raise LoopError("INVALID_ITERATION")
|
|
@@ -135,6 +293,27 @@ class Loops:
|
|
|
135
293
|
"""
|
|
136
294
|
return self._request("PATCH", loop_path(loop_id), spec)
|
|
137
295
|
|
|
296
|
+
def reconcile(self, loop_id: str, spec: dict[str, Any]) -> dict[str, Any]:
|
|
297
|
+
"""Plan reconciliation. Reuse the original request ID and spec after a lost response."""
|
|
298
|
+
return self._request("POST", f"{loop_path(loop_id)}/reconciliations", reconciliation_spec(spec))
|
|
299
|
+
|
|
300
|
+
def reconciliation_get(self, loop_id: str, reconciliation_id: str) -> dict[str, Any]:
|
|
301
|
+
"""Read the saved plan or applied receipt, including after a lost apply response."""
|
|
302
|
+
return self._request("GET", reconciliation_path(loop_id, reconciliation_id))
|
|
303
|
+
|
|
304
|
+
def reconciliation_apply(self, loop_id: str, reconciliation_id: str, *, digest: str) -> dict[str, Any]:
|
|
305
|
+
"""Apply the reviewed plan using the exact digest returned by the platform."""
|
|
306
|
+
path = reconciliation_path(loop_id, reconciliation_id)
|
|
307
|
+
return self._request("POST", f"{path}/apply", {"digest": valid_digest(digest)})
|
|
308
|
+
|
|
309
|
+
def close(self, loop_id: str, *, state: str, request_id: str) -> dict[str, Any]:
|
|
310
|
+
"""Request explicit local closure and return the platform's report delivery status."""
|
|
311
|
+
path = loop_path(loop_id)
|
|
312
|
+
if state not in CLOSE_STATES:
|
|
313
|
+
raise LoopError("INVALID_CLOSE_STATE")
|
|
314
|
+
validate_request_id(request_id)
|
|
315
|
+
return self._request("POST", f"{path}/close", {"request_id": request_id, "state": state})
|
|
316
|
+
|
|
138
317
|
def get_iteration(self, loop_id: str, iteration: int) -> dict[str, Any]:
|
|
139
318
|
"""One Iteration (numbered from 1): its plan, interventions, audits, decision and summary."""
|
|
140
319
|
return self._request("GET", f"{loop_path(loop_id)}/iterations/{valid_iteration(iteration)}")
|
|
File without changes
|
|
File without changes
|