artifact-tool-v3 3.0.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.
@@ -0,0 +1,7 @@
1
+ """Host-side helpers for artifacts written into an agent sandbox."""
2
+
3
+ from artifact_tool_v3.manager import ArtifactManager
4
+ from artifact_tool_v3.models import Artifact
5
+
6
+ __all__ = ["Artifact", "ArtifactManager"]
7
+ __version__ = "3.0.0"
@@ -0,0 +1,165 @@
1
+ """Scan, filter, and export files an agent wrote into a sandbox workspace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import mimetypes
7
+ import os
8
+ import shutil
9
+ import zipfile
10
+ from datetime import datetime, timezone
11
+ from fnmatch import fnmatch
12
+ from pathlib import Path
13
+ from typing import Literal
14
+
15
+ from artifact_tool_v3.models import Artifact
16
+ from artifact_tool_v3.paths import workspace_path
17
+
18
+ ExportFormat = Literal["dir", "zip"]
19
+
20
+
21
+ class ArtifactManager:
22
+ """Host handle for one sandbox workspace keyed by sandbox_id."""
23
+
24
+ def __init__(
25
+ self,
26
+ sandbox_id: str,
27
+ *,
28
+ root: str | os.PathLike[str] | None = None,
29
+ ) -> None:
30
+ self.sandbox_id = sandbox_id
31
+ self._workspace = workspace_path(sandbox_id, root)
32
+
33
+ @property
34
+ def workspace_path(self) -> Path:
35
+ """Absolute path the agent should write artifacts into."""
36
+ return self._workspace
37
+
38
+ def ensure_workspace(self) -> Path:
39
+ """Create the workspace directory if needed and return its path."""
40
+ self._workspace.mkdir(parents=True, exist_ok=True)
41
+ return self._workspace
42
+
43
+ def discover(self) -> list[Artifact]:
44
+ """Walk the workspace and return metadata for every file and directory.
45
+
46
+ Missing workspaces are treated as empty so the host can call discover
47
+ before the agent has created anything.
48
+ """
49
+ if not self._workspace.exists():
50
+ return []
51
+
52
+ artifacts: list[Artifact] = []
53
+ for path in sorted(self._workspace.rglob("*")):
54
+ artifacts.append(_artifact_from_path(path, self._workspace))
55
+ return artifacts
56
+
57
+ def list(
58
+ self,
59
+ *,
60
+ name: str | None = None,
61
+ suffix: str | None = None,
62
+ type: str | None = None,
63
+ glob: str | None = None,
64
+ ) -> list[Artifact]:
65
+ """Discover artifacts and keep those matching the given filters.
66
+
67
+ `glob` is matched against the posix relative path (for example `**/*.png`).
68
+ """
69
+ results = self.discover()
70
+ if name is not None:
71
+ results = [item for item in results if item.name == name]
72
+ if suffix is not None:
73
+ expected = suffix if suffix.startswith(".") else f".{suffix}"
74
+ results = [
75
+ item
76
+ for item in results
77
+ if Path(item.name).suffix.lower() == expected.lower()
78
+ ]
79
+ if type is not None:
80
+ results = [item for item in results if item.type == type]
81
+ if glob is not None:
82
+ results = [item for item in results if fnmatch(item.relative_path, glob)]
83
+ return results
84
+
85
+ def summary(self) -> dict[str, int]:
86
+ """Return file/dir counts and total file bytes for this workspace."""
87
+ artifacts = self.discover()
88
+ files = [item for item in artifacts if not item.is_dir]
89
+ dirs = [item for item in artifacts if item.is_dir]
90
+ return {
91
+ "files": len(files),
92
+ "directories": len(dirs),
93
+ "total_bytes": sum(item.size for item in files),
94
+ }
95
+
96
+ def write_manifest(self, destination: str | os.PathLike[str] | None = None) -> Path:
97
+ """Write a JSON listing of every discovered artifact and return its path."""
98
+ dest = Path(destination) if destination is not None else self.ensure_workspace() / "manifest.json"
99
+ dest.parent.mkdir(parents=True, exist_ok=True)
100
+ payload = {
101
+ "sandbox_id": self.sandbox_id,
102
+ "workspace": str(self._workspace),
103
+ "artifacts": [item.to_dict() for item in self.discover()],
104
+ }
105
+ dest.write_text(json.dumps(payload, indent=2) + "\n")
106
+ return dest.resolve()
107
+
108
+ def cleanup(self) -> None:
109
+ """Delete the sandbox workspace directory if it exists."""
110
+ if self._workspace.exists():
111
+ shutil.rmtree(self._workspace)
112
+
113
+ def export(
114
+ self,
115
+ destination: str | os.PathLike[str],
116
+ *,
117
+ format: ExportFormat = "dir",
118
+ ) -> Path:
119
+ """Copy the workspace to a directory or zip archive of relative paths."""
120
+ dest = Path(destination)
121
+ if format == "dir":
122
+ return self._export_dir(dest)
123
+ if format == "zip":
124
+ return self._export_zip(dest)
125
+ raise ValueError(f"unsupported export format: {format!r}")
126
+
127
+ def _export_dir(self, destination: Path) -> Path:
128
+ """Copy the workspace tree into destination, creating parents as needed."""
129
+ if not self._workspace.exists():
130
+ destination.mkdir(parents=True, exist_ok=True)
131
+ return destination.resolve()
132
+
133
+ if destination.exists():
134
+ shutil.copytree(self._workspace, destination, dirs_exist_ok=True)
135
+ else:
136
+ shutil.copytree(self._workspace, destination)
137
+ return destination.resolve()
138
+
139
+ def _export_zip(self, destination: Path) -> Path:
140
+ """Write a zip whose member names are paths relative to the workspace."""
141
+ destination.parent.mkdir(parents=True, exist_ok=True)
142
+ with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED) as archive:
143
+ if self._workspace.exists():
144
+ for path in sorted(self._workspace.rglob("*")):
145
+ archive.write(path, arcname=path.relative_to(self._workspace).as_posix())
146
+ return destination.resolve()
147
+
148
+
149
+ def _artifact_from_path(path: Path, workspace: Path) -> Artifact:
150
+ """Build Artifact metadata from a filesystem stat of path."""
151
+ stat = path.stat()
152
+ is_dir = path.is_dir()
153
+ mime_type, _ = mimetypes.guess_type(path.name)
154
+ if is_dir:
155
+ mime_type = "inode/directory"
156
+
157
+ return Artifact(
158
+ name=path.name,
159
+ relative_path=path.relative_to(workspace).as_posix(),
160
+ path=path.resolve(),
161
+ type=mime_type,
162
+ size=0 if is_dir else stat.st_size,
163
+ created_at=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc),
164
+ is_dir=is_dir,
165
+ )
@@ -0,0 +1,32 @@
1
+ """In-memory description of one file or directory in a sandbox workspace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Artifact:
12
+ """Metadata for one path discovered under a sandbox workspace."""
13
+
14
+ name: str
15
+ relative_path: str
16
+ path: Path
17
+ type: str | None
18
+ size: int
19
+ created_at: datetime
20
+ is_dir: bool
21
+
22
+ def to_dict(self) -> dict[str, object]:
23
+ """JSON-friendly record used by manifests and summaries."""
24
+ return {
25
+ "name": self.name,
26
+ "relative_path": self.relative_path,
27
+ "path": str(self.path),
28
+ "type": self.type,
29
+ "size": self.size,
30
+ "created_at": self.created_at.isoformat(),
31
+ "is_dir": self.is_dir,
32
+ }
@@ -0,0 +1,50 @@
1
+ """Resolve the on-disk root and per-sandbox workspace path."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ # Used when the caller does not pass root= and the env var is unset.
9
+ DEFAULT_ROOT_DIRNAME = ".artifact_tool_v3"
10
+ ROOT_ENV_VAR = "ARTIFACT_TOOL_V3_ROOT"
11
+
12
+
13
+ class InvalidSandboxIdError(ValueError):
14
+ """Raised when sandbox_id would escape or collide with the store root."""
15
+
16
+
17
+ def resolve_root(root: str | os.PathLike[str] | None = None) -> Path:
18
+ """Pick the store root: explicit path, env var, then ~/.artifact_tool_v3."""
19
+ if root is not None:
20
+ return Path(root).expanduser().resolve()
21
+
22
+ env_root = os.environ.get(ROOT_ENV_VAR)
23
+ if env_root:
24
+ return Path(env_root).expanduser().resolve()
25
+
26
+ return (Path.home() / DEFAULT_ROOT_DIRNAME).resolve()
27
+
28
+
29
+ def validate_sandbox_id(sandbox_id: str) -> str:
30
+ """Reject ids that contain path separators or parent-directory references."""
31
+ if not sandbox_id or not sandbox_id.strip():
32
+ raise InvalidSandboxIdError("sandbox_id must be a non-empty string")
33
+
34
+ if sandbox_id != sandbox_id.strip():
35
+ raise InvalidSandboxIdError("sandbox_id must not have leading or trailing whitespace")
36
+
37
+ # Block both POSIX and Windows separators so an id cannot walk the tree.
38
+ if "/" in sandbox_id or "\\" in sandbox_id or os.sep in sandbox_id:
39
+ raise InvalidSandboxIdError("sandbox_id must not contain path separators")
40
+
41
+ if sandbox_id in {".", ".."} or ".." in sandbox_id:
42
+ raise InvalidSandboxIdError("sandbox_id must not contain '..' or be '.'")
43
+
44
+ return sandbox_id
45
+
46
+
47
+ def workspace_path(sandbox_id: str, root: str | os.PathLike[str] | None = None) -> Path:
48
+ """Return `{root}/{sandbox_id}` after validating the id."""
49
+ safe_id = validate_sandbox_id(sandbox_id)
50
+ return resolve_root(root) / safe_id
File without changes
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.5
2
+ Name: artifact_tool_v3
3
+ Version: 3.0.0
4
+ Summary: Host-side library for managing files generated in an agent sandbox.
5
+ Author: artifact_tool_v3
6
+ License-Expression: MIT
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Typing :: Typed
10
+ Requires-Python: >=3.10
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8; extra == 'dev'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # artifact_tool_v3
16
+
17
+ Host-side library for managing artifacts an agent writes into a sandbox workspace.
18
+
19
+ Same core as `artifact_tool_v2`, plus glob filters, a JSON manifest, a size summary, and workspace cleanup.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install artifact_tool_v3
25
+ ```
26
+
27
+ ## Workspace location
28
+
29
+ Each sandbox lives at `{root}/{sandbox_id}/`.
30
+
31
+ Root is resolved in this order:
32
+
33
+ 1. The `root=` argument to `ArtifactManager`
34
+ 2. The `ARTIFACT_TOOL_V3_ROOT` environment variable
35
+ 3. `~/.artifact_tool_v3`
36
+
37
+ ## Usage
38
+
39
+ ```python
40
+ from artifact_tool_v3 import ArtifactManager
41
+
42
+ mgr = ArtifactManager("run-123")
43
+ workspace = mgr.ensure_workspace()
44
+
45
+ artifacts = mgr.discover()
46
+ pngs = mgr.list(glob="**/*.png")
47
+ print(mgr.summary())
48
+ mgr.write_manifest(workspace / "manifest.json")
49
+ mgr.export("/tmp/out.zip", format="zip")
50
+ mgr.cleanup()
51
+ ```
@@ -0,0 +1,8 @@
1
+ artifact_tool_v3/__init__.py,sha256=l2ZkAM_0xc8rLq9-iWGouRvhSLLi5srmaZ65WPRXcPM,233
2
+ artifact_tool_v3/manager.py,sha256=FxL-q836VQmSzAptyAXHcrZ8i9sxezNnBoAGUCF_2UM,5973
3
+ artifact_tool_v3/models.py,sha256=wOmoYcj7iq3vzDaSp7MN1jk0-ntE30xTUKH3B5e5J58,853
4
+ artifact_tool_v3/paths.py,sha256=QTueOoGLyNLX9EjEkOdMgGwe2GO6xtLPlVis3ZIhFH8,1841
5
+ artifact_tool_v3/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ artifact_tool_v3-3.0.0.dist-info/METADATA,sha256=ryt0xHcVwC3107NyRUjRDjGyX2OChINmK9E93CZKH50,1255
7
+ artifact_tool_v3-3.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ artifact_tool_v3-3.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any