envloop-envhub 1.23.0__tar.gz → 2.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/PKG-INFO +11 -3
  2. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/README.pypi.md +10 -2
  3. envloop_envhub-2.3.1/envhub/ans/client/download.py +138 -0
  4. envloop_envhub-2.3.1/envhub/ans/client/materialize.py +213 -0
  5. envloop_envhub-2.3.1/envhub/ans/client/recipe_package.py +162 -0
  6. envloop_envhub-2.3.1/envhub/ans/proto/params.py +526 -0
  7. envloop_envhub-2.3.1/envhub/ans/proto/recipe.py +562 -0
  8. envloop_envhub-2.3.1/envhub/ans/proto/tags.py +17 -0
  9. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/proto/uri.py +12 -0
  10. envloop_envhub-2.3.1/envhub/checkpoints/__init__.py +1 -0
  11. envloop_envhub-2.3.1/envhub/checkpoints/source.py +53 -0
  12. envloop_envhub-2.3.1/envhub/jobs/__init__.py +21 -0
  13. envloop_envhub-2.3.1/envhub/jobs/types.py +68 -0
  14. envloop_envhub-2.3.1/envhub/proxyhub/__init__.py +1 -0
  15. envloop_envhub-2.3.1/envhub/proxyhub/bundle.py +20 -0
  16. envloop_envhub-2.3.1/envhub/proxyhub/guest.py +627 -0
  17. envloop_envhub-2.3.1/envhub/proxyhub/policy.py +141 -0
  18. envloop_envhub-2.3.1/envhub/proxyhub/services.py +66 -0
  19. envloop_envhub-2.3.1/envhub/supervisor/__init__.py +51 -0
  20. envloop_envhub-2.3.1/envhub/supervisor/__main__.py +51 -0
  21. envloop_envhub-2.3.1/envhub/supervisor/asset_io.py +263 -0
  22. envloop_envhub-2.3.1/envhub/supervisor/bootstrap.py +65 -0
  23. envloop_envhub-2.3.1/envhub/supervisor/contract.py +262 -0
  24. envloop_envhub-2.3.1/envhub/supervisor/controller.py +199 -0
  25. envloop_envhub-2.3.1/envhub/supervisor/declarations.py +59 -0
  26. envloop_envhub-2.3.1/envhub/supervisor/guest.py +169 -0
  27. envloop_envhub-2.3.1/envhub/supervisor/outputs.py +104 -0
  28. envloop_envhub-2.3.1/envhub/supervisor/process.py +97 -0
  29. envloop_envhub-2.3.1/envhub/supervisor/redaction.py +66 -0
  30. envloop_envhub-2.3.1/envhub/supervisor/sdk.py +161 -0
  31. envloop_envhub-2.3.1/envhub/supervisor/tools.py +119 -0
  32. envloop_envhub-2.3.1/pyproject.toml +111 -0
  33. envloop_envhub-1.23.0/envhub/ans/client/download.py +0 -83
  34. envloop_envhub-1.23.0/envhub/ans/client/materialize.py +0 -64
  35. envloop_envhub-1.23.0/pyproject.toml +0 -56
  36. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/NOTICE +0 -0
  37. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/__init__.py +0 -0
  38. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/__init__.py +0 -0
  39. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/client/__init__.py +0 -0
  40. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/proto/__init__.py +0 -0
  41. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/proto/ans.proto +0 -0
  42. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/proto/errors.py +0 -0
  43. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/proto/manifests.py +0 -0
  44. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/envhub/ans/proto/schemas.py +0 -0
  45. {envloop_envhub-1.23.0 → envloop_envhub-2.3.1}/hatch_build.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: envloop-envhub
3
- Version: 1.23.0
3
+ Version: 2.3.1
4
4
  Summary: Dependency-free ANS protocol and verified downloads
5
5
  License-File: NOTICE
6
6
  Requires-Python: >=3.12
@@ -10,7 +10,7 @@ Description-Content-Type: text/markdown
10
10
  # EnvLoop ANS core
11
11
 
12
12
  `envloop-envhub==1.23.0` provides dependency-free ANS references, URI parsing,
13
- content manifest validation and verified atomic downloads for Python 3.12+.
13
+ content manifest validation, verified atomic downloads and the worker supervisor for Python 3.12+.
14
14
 
15
15
  ```python
16
16
  from envhub.ans.proto import DatasetRef, parse_uri
@@ -22,7 +22,13 @@ HTTPS uses Python's system CA trust and verifies certificates and hostnames;
22
22
  the Python installation must have a working trusted CA store. Download plans
23
23
  come from the caller's authorized API; this library does not issue credentials.
24
24
 
25
- Only the ANS client/protocol implementation is distributed. Registry services,
25
+ The reviewed ANS client/protocol and `envhub.supervisor` implementation are distributed.
26
+ `supervisor --help` (or `python -m envhub.supervisor`) provides data phase and Linux
27
+ process supervision entrypoints. Install a separately pinned public `el` CLI for
28
+ transfers; this package does not issue credentials or include a Docker/Kubernetes
29
+ controller. Platform adapters provide phase-scoped credentials and lifecycle policy.
30
+
31
+ Registry services,
26
32
  databases, storage drivers, publishing tools, datasets and Runner/Recipe assets
27
33
  are excluded. Internal EnvHub applications require a separately provided private
28
34
  companion; installing this core does not provide those applications.
@@ -32,3 +38,5 @@ Source: https://github.com/EnvLoop/EnvHub
32
38
 
33
39
  The source baseline declares no implementation license. This packaging change
34
40
  adds no license grant; excluded content licenses do not apply. See NOTICE.
41
+
42
+ Portable `envhub.proxyhub` supplies the LiteLLM adapter, bounded request policy, private trajectory capture and service launch specifications. Optional service dependencies are prepared separately; importing the default package does not import LiteLLM or an HTTP server.
@@ -1,7 +1,7 @@
1
1
  # EnvLoop ANS core
2
2
 
3
3
  `envloop-envhub==1.23.0` provides dependency-free ANS references, URI parsing,
4
- content manifest validation and verified atomic downloads for Python 3.12+.
4
+ content manifest validation, verified atomic downloads and the worker supervisor for Python 3.12+.
5
5
 
6
6
  ```python
7
7
  from envhub.ans.proto import DatasetRef, parse_uri
@@ -13,7 +13,13 @@ HTTPS uses Python's system CA trust and verifies certificates and hostnames;
13
13
  the Python installation must have a working trusted CA store. Download plans
14
14
  come from the caller's authorized API; this library does not issue credentials.
15
15
 
16
- Only the ANS client/protocol implementation is distributed. Registry services,
16
+ The reviewed ANS client/protocol and `envhub.supervisor` implementation are distributed.
17
+ `supervisor --help` (or `python -m envhub.supervisor`) provides data phase and Linux
18
+ process supervision entrypoints. Install a separately pinned public `el` CLI for
19
+ transfers; this package does not issue credentials or include a Docker/Kubernetes
20
+ controller. Platform adapters provide phase-scoped credentials and lifecycle policy.
21
+
22
+ Registry services,
17
23
  databases, storage drivers, publishing tools, datasets and Runner/Recipe assets
18
24
  are excluded. Internal EnvHub applications require a separately provided private
19
25
  companion; installing this core does not provide those applications.
@@ -23,3 +29,5 @@ Source: https://github.com/EnvLoop/EnvHub
23
29
 
24
30
  The source baseline declares no implementation license. This packaging change
25
31
  adds no license grant; excluded content licenses do not apply. See NOTICE.
32
+
33
+ Portable `envhub.proxyhub` supplies the LiteLLM adapter, bounded request policy, private trajectory capture and service launch specifications. Optional service dependencies are prepared separately; importing the default package does not import LiteLLM or an HTTP server.
@@ -0,0 +1,138 @@
1
+ """Materialize one ANS directory from temporary provider URLs."""
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ from collections.abc import Callable, Iterable, Iterator
7
+ from pathlib import Path
8
+ from typing import Any, override
9
+ from urllib.parse import urlsplit
10
+
11
+ from envhub.ans.client.materialize import (
12
+ MAX_TASK_ARCHIVE,
13
+ materialize_manifest,
14
+ materialize_task_archive,
15
+ materialize_task_files,
16
+ validate_task_files,
17
+ )
18
+ from envhub.ans.proto import manifests as artifacts
19
+ from envhub.ans.proto.errors import InvalidRecord
20
+ from envhub.ans.proto.uri import DatasetRef, parse_uri
21
+
22
+
23
+ def validate_download_plan(plan: Any, *, uri: str, split: str | None = None,
24
+ config: str | None = None, content_digest: str | None = None,
25
+ task_id: str | None = None, task_digest: str | None = None) -> tuple[dict[str, Any], dict[str, str], dict[str, int]]:
26
+ """Validate identity, pins and URLs before issuing any provider request."""
27
+ try:
28
+ reference = parse_uri(uri)
29
+ task = task_id is not None or task_digest is not None
30
+ if task and (not isinstance(reference, DatasetRef) or not isinstance(task_id, str)
31
+ or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*', task_id)
32
+ or '..' in task_id
33
+ or not isinstance(task_digest, str) or not re.fullmatch(r'sha256:[a-f0-9]{64}', task_digest)
34
+ or not isinstance(split, str) or not split
35
+ or not isinstance(plan, dict) or plan.get('task_id') != task_id or plan.get('task_digest') != task_digest):
36
+ raise InvalidRecord('download plan does not match the requested Task')
37
+ if (not isinstance(plan, dict) or set(plan) != {'uri', 'content_digest', 'split', 'expires_in', 'files'} | ({'config'} if config is not None else set()) | ({'task_id', 'task_digest'} if task else set())
38
+ or reference.uri != uri or plan['uri'] != uri or plan['split'] != split
39
+ or config is not None and (not isinstance(reference, DatasetRef)
40
+ or not isinstance(config, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,127}', config)
41
+ or plan.get('config') != config)
42
+ or not re.fullmatch('[a-f0-9]{64}', plan['content_digest'])
43
+ or content_digest is not None and plan['content_digest'] != content_digest
44
+ or type(plan['expires_in']) is not int or not 1 <= plan['expires_in'] <= 300):
45
+ raise InvalidRecord('download plan does not match the requested ANS identity')
46
+ entries: list[dict[str, Any]] = []
47
+ urls: dict[str, str] = {}
48
+ modes: dict[str, int] = {}
49
+ for entry in plan['files']:
50
+ if (set(entry) != {'path', 'size', 'sha256', 'mode', 'url'}
51
+ or type(entry['mode']) is not int or entry['mode'] not in (0o100644, 0o100755)):
52
+ raise InvalidRecord('invalid download file metadata')
53
+ url = urlsplit(entry['url'])
54
+ if (url.scheme != 'https' or not url.hostname or url.username is not None
55
+ or url.password is not None or url.fragment):
56
+ raise InvalidRecord('download requires a credential-free HTTPS origin')
57
+ entries.append({key: entry[key] for key in ('path', 'size', 'sha256')})
58
+ urls[entry['path']], modes[entry['path']] = entry['url'], entry['mode']
59
+ archive = task and len(entries) == 1 and entries[0]['path'] == 'task.tgz'
60
+ if archive and (not 0 < entries[0]['size'] <= MAX_TASK_ARCHIVE or modes['task.tgz'] != 0o100644):
61
+ raise InvalidRecord('Task download requires one bounded native archive')
62
+ if task and not archive:
63
+ validate_task_files(entries)
64
+ manifest = artifacts.validate_manifest({'schema': artifacts.SCHEMA, 'kind': 'directory', 'files': entries})
65
+ except (KeyError, TypeError, ValueError) as error:
66
+ raise InvalidRecord('invalid ANS download plan') from error
67
+
68
+ return manifest, urls, modes
69
+
70
+
71
+ def download_directory(plan: Any, destination: Path, *, uri: str, split: str | None = None,
72
+ config: str | None = None, content_digest: str | None = None,
73
+ task_id: str | None = None, task_digest: str | None = None,
74
+ read_url: Callable[[str], Iterable[bytes]] | None = None,
75
+ max_workers: int = 4) -> Path:
76
+ """Verify a complete directory and publish it atomically, without API credentials.
77
+
78
+ The first file is verified before up to four concurrent transfers, allowing
79
+ readers to renew an initially expired plan before other files are read. A
80
+ custom reader must be thread safe or select max_workers=1. Task delivery
81
+ remains sequential. Temporary URLs never enter the saved directory.
82
+ """
83
+ manifest, urls, modes = validate_download_plan(plan, uri=uri, split=split, config=config, content_digest=content_digest,
84
+ task_id=task_id, task_digest=task_digest)
85
+ # The trusted Supervisor sets a private per-CLI remaining budget. It is
86
+ # validated against the exact selected plan before object access; renewal
87
+ # remains the public CLI's responsibility and cannot expand this budget.
88
+ budget = None
89
+ if raw := os.environ.get('ENVLOOP_DATA_DOWNLOAD_BUDGET'):
90
+ try:
91
+ budget = json.loads(raw)
92
+ if (not isinstance(budget, dict) or set(budget) != {'max_bytes', 'max_files'}
93
+ or any(type(v) is not int or v < 0 for v in budget.values())):
94
+ raise ValueError()
95
+ except (TypeError, ValueError):
96
+ raise InvalidRecord('invalid worker download budget') from None
97
+ if (len(manifest['files']) > budget['max_files']
98
+ or sum(item['size'] for item in manifest['files']) > budget['max_bytes']):
99
+ raise InvalidRecord('worker input quota exceeded')
100
+
101
+ def materialize(read: Callable[[str], Iterable[bytes]]) -> Path:
102
+ if task_digest is not None:
103
+ if len(manifest['files']) == 1 and manifest['files'][0]['path'] == 'task.tgz':
104
+ return materialize_task_archive(manifest, destination, read, task_digest=task_digest,
105
+ **({'max_bytes': budget['max_bytes'], 'max_files': budget['max_files']} if budget is not None else {}))
106
+ return materialize_task_files(manifest, destination, read, modes=modes, task_digest=task_digest)
107
+ return materialize_manifest(manifest, destination, read, modes=modes, max_workers=max_workers)
108
+
109
+ if read_url is not None:
110
+ def read_custom(path: str) -> Iterable[bytes]:
111
+ return read_url(urls[path])
112
+ return materialize(read_custom)
113
+ import ssl
114
+ from urllib.error import URLError
115
+ from urllib.request import (
116
+ HTTPRedirectHandler,
117
+ HTTPSHandler,
118
+ ProxyHandler,
119
+ build_opener,
120
+ )
121
+
122
+ class NoRedirect(HTTPRedirectHandler):
123
+ @override
124
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
125
+ return None
126
+
127
+ context = ssl.create_default_context()
128
+ def read(path: str) -> Iterator[bytes]:
129
+ client = build_opener(ProxyHandler({}), NoRedirect(), HTTPSHandler(context=context))
130
+ try:
131
+ with client.open(urls[path], timeout=60) as response:
132
+ if response.status != 200:
133
+ raise InvalidRecord('repository download failed')
134
+ while chunk := response.read(1024 * 1024):
135
+ yield chunk
136
+ except URLError:
137
+ raise InvalidRecord('repository download failed') from None
138
+ return materialize(read)
@@ -0,0 +1,213 @@
1
+ """Verify bytes and atomically materialize ANS manifests."""
2
+ import gzip
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ import stat
9
+ import tarfile
10
+ import tempfile
11
+ from collections.abc import Callable, Iterable
12
+ from concurrent.futures import ThreadPoolExecutor, as_completed
13
+ from pathlib import Path, PurePosixPath
14
+ from typing import Any
15
+
16
+ from envhub.ans.proto.errors import InvalidManifest
17
+ from envhub.ans.proto.manifests import validate_manifest
18
+
19
+
20
+ def materialize_manifest(
21
+ manifest: dict[str, Any],
22
+ destination: Path,
23
+ read: Callable[[str], bytes | Iterable[bytes]],
24
+ *,
25
+ modes: dict[str, int] | None = None,
26
+ max_workers: int = 1,
27
+ ) -> Path:
28
+ """Verify streamed bytes privately, then rename the complete tree into place.
29
+
30
+ ``read(relative_path)`` returns bytes or an iterable of byte chunks. Existing
31
+ destinations and symlink ancestors are rejected; callers own the parent tree.
32
+ No destination becomes visible on download, size or digest failure.
33
+ The first file is verified before concurrent fan-out. Concurrent readers
34
+ must be thread safe; at most four remaining files are read at once.
35
+ """
36
+ value = validate_manifest(manifest)
37
+ if type(max_workers) is not int or not 1 <= max_workers <= 4:
38
+ raise ValueError('Artifact download concurrency must be between one and four')
39
+ if modes is not None and (not isinstance(modes, dict)
40
+ or set(modes) != {item['path'] for item in value['files']}
41
+ or any(type(mode) is not int or mode not in (0o100644, 0o100755) for mode in modes.values())):
42
+ raise InvalidManifest('Invalid artifact executable modes')
43
+ target = Path(destination)
44
+ if any(parent.is_symlink() for parent in (target, *target.parents)):
45
+ raise InvalidManifest('Artifact destination cannot contain symlinks')
46
+ if target.exists():
47
+ raise FileExistsError('Artifact destination already exists')
48
+ staging = Path(tempfile.mkdtemp(prefix='.artifact-', dir=target.parent))
49
+ def write_file(item: dict[str, Any]) -> None:
50
+ path = staging / item['path']
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+ content = read(item['path'])
53
+ chunks = (content,) if isinstance(content, bytes) else content
54
+ digest, size = hashlib.sha256(), 0
55
+ with path.open('xb') as output:
56
+ for chunk in chunks:
57
+ if not isinstance(chunk, bytes):
58
+ raise InvalidManifest('Artifact reader must return byte chunks')
59
+ size += len(chunk)
60
+ if size > item['size']:
61
+ raise InvalidManifest('Artifact file size mismatch')
62
+ digest.update(chunk)
63
+ output.write(chunk)
64
+ if size != item['size'] or digest.hexdigest() != item['sha256']:
65
+ raise InvalidManifest('Artifact file size or SHA-256 mismatch')
66
+ if modes is not None:
67
+ path.chmod(modes[item['path']] & 0o777)
68
+ try:
69
+ if max_workers == 1 or len(value['files']) == 1:
70
+ for item in value['files']:
71
+ write_file(item)
72
+ else:
73
+ write_file(value['files'][0])
74
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
75
+ pending = [executor.submit(write_file, item) for item in value['files'][1:]]
76
+ try:
77
+ for future in as_completed(pending):
78
+ future.result()
79
+ finally:
80
+ for future in pending:
81
+ future.cancel()
82
+ if target.exists() or target.is_symlink():
83
+ raise FileExistsError('Artifact destination already exists')
84
+ os.rename(staging, target)
85
+ return target
86
+ finally:
87
+ if staging.exists():
88
+ shutil.rmtree(staging)
89
+
90
+
91
+ # Native Task archives are independently pinned from their extracted tree.
92
+ MAX_TASK_ARCHIVE = 16 * 1024 * 1024
93
+ MAX_TASK_EXPANDED = 64 * 1024 * 1024
94
+ MAX_TASK_FILES = 256
95
+
96
+
97
+ def task_inventory_fingerprint(files: list[dict[str, Any]]) -> str:
98
+ """Canonical native Task tree hash from an already verified file inventory."""
99
+ records = []
100
+ seen = set()
101
+ for item in sorted(files, key=lambda item: item['path']):
102
+ path, size, digest, mode = (item[key] for key in ('path', 'size', 'sha256', 'mode'))
103
+ if '.git' in path.split('/'):
104
+ continue
105
+ if (path in seen or type(size) is not int or size < 0 or mode not in (0o100644, 0o100755)
106
+ or not isinstance(digest, str) or not re.fullmatch(r'[a-f0-9]{64}', digest)):
107
+ raise InvalidManifest('Invalid Task file inventory')
108
+ seen.add(path)
109
+ records.append([path, bool(mode & 0o111), size, digest])
110
+ return hashlib.sha256(json.dumps(records, ensure_ascii=False, separators=(',', ':')).encode()).hexdigest()
111
+
112
+
113
+ def task_fingerprint(directory: Path) -> str:
114
+ """Canonical native Task content hash, shared by authoring and delivery."""
115
+ files = []
116
+ for path in sorted(directory.rglob('*'), key=lambda p: p.relative_to(directory).as_posix()):
117
+ if '.git' in path.relative_to(directory).parts:
118
+ continue
119
+ mode = path.lstat().st_mode
120
+ if not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)):
121
+ raise InvalidManifest('Unsafe task file')
122
+ if stat.S_ISREG(mode):
123
+ files.append({'path': path.relative_to(directory).as_posix(), 'size': path.stat().st_size,
124
+ 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
125
+ 'mode': 0o100755 if mode & 0o111 else 0o100644})
126
+ return task_inventory_fingerprint(files)
127
+
128
+
129
+ def validate_task_files(files: list[dict[str, Any]]) -> None:
130
+ """Bound one complete native Task directory without discarding any declared file."""
131
+ if (not 1 <= len(files) <= MAX_TASK_FILES or sum(item['size'] for item in files) > MAX_TASK_EXPANDED
132
+ or 'task.toml' not in {item['path'] for item in files}
133
+ or any('.git' in item['path'].split('/') for item in files)):
134
+ raise InvalidManifest('Invalid or oversized Task file inventory')
135
+
136
+
137
+ def materialize_task_files(manifest: dict[str, Any], destination: Path,
138
+ read: Callable[[str], bytes | Iterable[bytes]], *, modes: dict[str, int], task_digest: str) -> Path:
139
+ """Verify every Task byte/mode and tree pin before exposing the complete directory."""
140
+ value = validate_manifest(manifest)
141
+ validate_task_files(value['files'])
142
+ target = Path(destination)
143
+ if target.exists() or any(path.is_symlink() for path in (target, *target.parents)):
144
+ raise InvalidManifest('Task destination must be fresh and cannot contain symlinks')
145
+ target.parent.mkdir(parents=True, exist_ok=True)
146
+ with tempfile.TemporaryDirectory(prefix='.task-', dir=target.parent) as temporary:
147
+ staging = materialize_manifest(value, Path(temporary)/'task', read, modes=modes)
148
+ if 'sha256:' + task_fingerprint(staging) != task_digest:
149
+ raise InvalidManifest('Task tree fingerprint mismatch')
150
+ if target.exists() or target.is_symlink():
151
+ raise FileExistsError('Task destination already exists')
152
+ os.rename(staging, target)
153
+ return target
154
+
155
+
156
+ def materialize_task_archive(manifest: dict[str, Any], destination: Path,
157
+ read: Callable[[str], bytes | Iterable[bytes]], *, task_digest: str,
158
+ max_bytes: int = MAX_TASK_EXPANDED, max_files: int = MAX_TASK_FILES) -> Path:
159
+ """Verify a native Task archive and its tree fingerprint, then publish atomically."""
160
+ value = validate_manifest(manifest)
161
+ if (len(value['files']) != 1 or value['files'][0]['path'] != 'task.tgz'
162
+ or not 0 < value['files'][0]['size'] <= MAX_TASK_ARCHIVE):
163
+ raise InvalidManifest('Task download requires one bounded native archive')
164
+ target = Path(destination)
165
+ if target.exists() or any(path.is_symlink() for path in (target, *target.parents)):
166
+ raise InvalidManifest('Task destination must be fresh and cannot contain symlinks')
167
+ target.parent.mkdir(parents=True, exist_ok=True)
168
+ with tempfile.TemporaryDirectory(prefix='.task-', dir=target.parent) as temporary:
169
+ root = Path(temporary)
170
+ archive_dir = materialize_manifest(value, root/'archive', read)
171
+ expanded = root/'task.tar'
172
+ size = 0
173
+ try:
174
+ with gzip.open(archive_dir/'task.tgz', 'rb') as source, expanded.open('xb') as output:
175
+ while chunk := source.read(min(65536, MAX_TASK_EXPANDED - size + 1)):
176
+ size += len(chunk)
177
+ if size > MAX_TASK_EXPANDED:
178
+ raise InvalidManifest('Task archive expanded size exceeds limit')
179
+ output.write(chunk)
180
+ staging = root/'task'
181
+ staging.mkdir()
182
+ seen, total = set(), 0
183
+ with tarfile.open(expanded, 'r:') as archive:
184
+ for count, member in enumerate(archive, 1):
185
+ parts = PurePosixPath(member.name).parts
186
+ if (count > min(MAX_TASK_FILES, max_files) or not parts or len(member.name) > 1024
187
+ or member.name.startswith('/') or '\\' in member.name
188
+ or any(ord(character) < 32 for character in member.name)
189
+ or any(part in ('', '.', '..', '.git') for part in member.name.split('/'))
190
+ or member.name in seen or not member.isfile() or member.size < 0):
191
+ raise InvalidManifest('Invalid Task archive member')
192
+ seen.add(member.name)
193
+ total += member.size
194
+ if total > min(MAX_TASK_EXPANDED, max_bytes):
195
+ raise InvalidManifest('Task file size exceeds limit')
196
+ path = staging.joinpath(*parts)
197
+ path.parent.mkdir(parents=True, exist_ok=True)
198
+ source = archive.extractfile(member)
199
+ if source is None:
200
+ raise InvalidManifest('Task archive member is unavailable')
201
+ with source, path.open('xb') as output:
202
+ shutil.copyfileobj(source, output, length=65536)
203
+ path.chmod(0o755 if member.mode & 0o111 else 0o644)
204
+ if not (staging/'task.toml').is_file():
205
+ raise InvalidManifest('Task archive is missing task.toml')
206
+ if 'sha256:' + task_fingerprint(staging) != task_digest:
207
+ raise InvalidManifest('Task tree fingerprint mismatch')
208
+ if target.exists() or target.is_symlink():
209
+ raise FileExistsError('Task destination already exists')
210
+ os.rename(staging, target)
211
+ except (OSError, EOFError, ValueError, tarfile.TarError) as error:
212
+ raise InvalidManifest('Invalid Task archive') from error
213
+ return target
@@ -0,0 +1,162 @@
1
+ """Build a Recipe package (recipe.tgz contents and content index) from a committed `recipe.toml`.
2
+
3
+ recipe.toml is the Recipe's entry configuration file: it declares the Job types, params, Runner
4
+ contract, dependencies and source paths. `entrypoint.sh` is the entry executable the Runner's
5
+ `main.sh` runs. Both sit next to each other in the repository and at the root of recipe.tgz.
6
+
7
+ The caller supplies the committed tree listing and a blob reader; this module performs no Git,
8
+ network, import or working-tree access. The package holds `recipe.toml` and `entrypoint.sh` (their
9
+ exact committed bytes, at the root paths) and the code files selected by `[source].paths`, at their
10
+ repository-relative paths. Its identity is the SHA-256 of the `envloop.content-index/v1` content
11
+ index (`envhub.ans.proto.recipe`), so a dry run returns the final Recipe URI. The platform remains
12
+ the validating authority and stores the package as a `.tgz` archive.
13
+ """
14
+
15
+ from collections.abc import Callable, Mapping
16
+ from typing import Any
17
+
18
+ from envhub.ans.proto.params import (
19
+ STANDARD_PARAMS,
20
+ ParamConflictError,
21
+ merge_declarations,
22
+ )
23
+ from envhub.ans.proto.recipe import (
24
+ DECLARATION,
25
+ ENTRYPOINT,
26
+ MAX_FILE,
27
+ MAX_FILES,
28
+ MAX_TOTAL,
29
+ RecipeError,
30
+ build_index,
31
+ canonical,
32
+ index_digest,
33
+ parse_recipe,
34
+ parse_recipe_toml,
35
+ recipe_reference,
36
+ recipe_spec_dict,
37
+ safe_path,
38
+ selected,
39
+ )
40
+
41
+ # Retired declaration formats: they built a parameters-carrying manifest. Their published content stays readable.
42
+ RETIRED_SCHEMAS = frozenset({'envloop.recipe-publication/v3'})
43
+ REGULAR = ('100644', '100755')
44
+
45
+ __all__ = ['DECLARATION', 'RETIRED_SCHEMAS', 'RecipePackageError', 'build_recipe_package', 'canonical',
46
+ 'declaration_path']
47
+
48
+
49
+ class RecipePackageError(ValueError):
50
+ """A stable code without reflecting repository content."""
51
+
52
+ def __init__(self, code: str = 'RECIPE_PACKAGE_INVALID') -> None:
53
+ super().__init__(code)
54
+ self.code = code
55
+
56
+
57
+ def _require(condition: object, code: str = 'RECIPE_PACKAGE_INVALID') -> None:
58
+ if not condition:
59
+ raise RecipePackageError(code)
60
+
61
+
62
+ def declaration_path(directory: str, name: str = DECLARATION) -> str:
63
+ """Repository-relative path of `recipe.toml` (or `entrypoint.sh`) in a directory ('' is the root)."""
64
+ if directory in ('', '.'):
65
+ return name
66
+ try:
67
+ return safe_path(directory.strip('/')) + '/' + name
68
+ except RecipeError as error:
69
+ raise RecipePackageError(error.code) from None
70
+
71
+
72
+ def _check_runner(runner_params: Any, declared: dict[str, dict[str, Any]]) -> None:
73
+ _require(isinstance(runner_params, Mapping) and all(isinstance(v, Mapping) for v in runner_params.values()))
74
+ ordinary = {name: dict(item) for name, item in runner_params.items() if name not in STANDARD_PARAMS}
75
+ try:
76
+ merge_declarations(ordinary, declared)
77
+ except ParamConflictError:
78
+ raise RecipePackageError('RECIPE_PARAM_CONFLICT') from None
79
+
80
+
81
+ def _retired(raw: bytes) -> bool:
82
+ import tomllib
83
+
84
+ try:
85
+ return tomllib.loads(raw.decode('utf-8')).get('schema_version') in RETIRED_SCHEMAS
86
+ except (UnicodeError, tomllib.TOMLDecodeError):
87
+ return False
88
+
89
+
90
+ def build_recipe_package(tree: Mapping[str, str], read: Callable[[str], bytes], *, commit: str,
91
+ directory: str = '',
92
+ runner_params: Mapping[str, Mapping[str, Any]] | None = None) -> dict[str, Any]:
93
+ """Return `{uri, manifest_sha256, manifest, files, inputs, recipe}` for one frozen commit.
94
+
95
+ `tree` maps every repository-relative path at `commit` to its Git mode (`100644`, `100755`,
96
+ `120000`, `160000`); `read(path)` returns that path's blob bytes at the same commit. `directory`
97
+ holds `recipe.toml` and `entrypoint.sh`. `manifest` is the content index and `manifest_sha256` its digest, the Recipe
98
+ revision in `uri`; `files` are the recipe.tgz contents; `recipe` is the parsed declaration
99
+ (`recipe_spec_dict`); `inputs` lists the repository paths consumed so a caller can refuse
100
+ uncommitted edits. Without `[source].repository` the source is a local Git repository and the
101
+ index `source` is `{"commit"}` only.
102
+
103
+ A `[source].paths` selection that would place another file at the package root path
104
+ `recipe.toml` or `entrypoint.sh` fails with `RECIPE_DECLARATION_CONFLICT`; the committed paths of
105
+ the two protocol files are not packaged a second time. `runner_params`, when the caller knows the declared Runner's
106
+ `params` declarations, is checked with `merge_declarations` (`RECIPE_PARAM_CONFLICT`) without
107
+ changing the package.
108
+ """
109
+ _require(isinstance(tree, Mapping) and all(isinstance(k, str) and isinstance(v, str) for k, v in tree.items()))
110
+ source = declaration_path(directory)
111
+ entry = declaration_path(directory, ENTRYPOINT)
112
+ _require(tree.get(source) in REGULAR, 'RECIPE_DECLARATION_NOT_FOUND')
113
+ _require(tree.get(entry) in REGULAR, 'RECIPE_ENTRYPOINT_NOT_FOUND')
114
+ raw = read(source)
115
+ _require(isinstance(raw, bytes), 'RECIPE_DECLARATION_NOT_FOUND')
116
+ _require(not _retired(raw), 'RECIPE_PACKAGE_SCHEMA_RETIRED')
117
+ try:
118
+ spec = parse_recipe_toml(raw)
119
+ except RecipeError as error:
120
+ raise RecipePackageError(error.code) from None
121
+ if runner_params is not None:
122
+ _check_runner(runner_params, spec.params)
123
+ matches: set[str] = set()
124
+ for prefix in spec.source['paths']:
125
+ found = {name for name in tree if name == prefix or name.startswith(prefix + '/')}
126
+ _require(bool(found), 'RECIPE_PATH_NOT_FOUND')
127
+ matches |= found
128
+ # Exclusions are exact selected files only; no globbing or implicit filtering.
129
+ _require(set(spec.source['exclude']) <= matches, 'RECIPE_PATH_NOT_FOUND')
130
+ chosen = sorted(name for name in matches if selected(name, spec))
131
+ _require(not (DECLARATION in chosen and source != DECLARATION)
132
+ and not (ENTRYPOINT in chosen and entry != ENTRYPOINT), 'RECIPE_DECLARATION_CONFLICT')
133
+ chosen = [name for name in chosen if name not in (source, entry)]
134
+ _require(len(chosen) < MAX_FILES - 1, 'RECIPE_PACKAGE_TOO_LARGE')
135
+ script = read(entry)
136
+ _require(isinstance(script, bytes) and len(script) <= MAX_FILE, 'RECIPE_ENTRYPOINT_NOT_FOUND')
137
+ files: dict[str, bytes] = {DECLARATION: raw, ENTRYPOINT: script}
138
+ total = len(raw) + len(script)
139
+ for name in chosen:
140
+ _require(tree[name] in REGULAR, 'RECIPE_FILE_UNSUPPORTED')
141
+ content = read(name)
142
+ _require(isinstance(content, bytes) and len(content) <= MAX_FILE, 'RECIPE_PACKAGE_TOO_LARGE')
143
+ total += len(content)
144
+ _require(total <= MAX_TOTAL, 'RECIPE_PACKAGE_TOO_LARGE')
145
+ files[name] = content
146
+ _require(not spec.agent or spec.agent['definition'] in files, 'RECIPE_AGENT_DEFINITION_NOT_FOUND')
147
+ try:
148
+ parse_recipe(files)
149
+ index = build_index(files, repository=spec.source.get('repository'), commit=commit,
150
+ dependencies=spec.dependencies)
151
+ reference = recipe_reference(spec, index)
152
+ digest = index_digest(index)
153
+ except RecipeError as error:
154
+ raise RecipePackageError(error.code) from None
155
+ return {
156
+ 'uri': reference.uri,
157
+ 'manifest_sha256': digest,
158
+ 'manifest': index,
159
+ 'files': files,
160
+ 'inputs': sorted({source, entry, *spec.source['paths']}),
161
+ 'recipe': recipe_spec_dict(spec),
162
+ }