agents-function-tools 0.2.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.
- agents_function_tools-0.2.0.dist-info/METADATA +90 -0
- agents_function_tools-0.2.0.dist-info/RECORD +14 -0
- agents_function_tools-0.2.0.dist-info/WHEEL +5 -0
- agents_function_tools-0.2.0.dist-info/licenses/LICENSE +202 -0
- agents_function_tools-0.2.0.dist-info/top_level.txt +1 -0
- function_tools/__init__.py +21 -0
- function_tools/archive.py +220 -0
- function_tools/command.py +172 -0
- function_tools/errors.py +11 -0
- function_tools/host.py +43 -0
- function_tools/http.py +136 -0
- function_tools/openai_tools.py +398 -0
- function_tools/responses.py +39 -0
- function_tools/workspace.py +433 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agents-function-tools
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Portable, policy-friendly system function tools for AI applications.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: openai-agents<1,>=0.1
|
|
14
|
+
Requires-Dist: pydantic<3,>=2
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# Agents Function Tools
|
|
18
|
+
|
|
19
|
+
`agents-function-tools` is a portable Python library of policy-friendly system function tools. It contains no business model, Agent routing, domain workflow, database adapter, or code-review logic. Its Python import name is `function_tools`.
|
|
20
|
+
|
|
21
|
+
## Included tools
|
|
22
|
+
|
|
23
|
+
| Category | Tools | Effect class |
|
|
24
|
+
|---|---|---|
|
|
25
|
+
| Workspace read | List, read UTF-8, inspect metadata, glob-style find, hash files, disk usage | `safe_read` |
|
|
26
|
+
| Workspace write | Write text, create directories, copy a regular file, move a path, delete a path | `workspace_write` |
|
|
27
|
+
| ZIP | List archive entries; create and extract bounded ZIP archives | `safe_read` / `workspace_write` |
|
|
28
|
+
| Network | Fetch bounded HTTPS text from configured hosts | `safe_read` |
|
|
29
|
+
| Host | Non-sensitive system info, UTC time, explicitly allowlisted environment variables | `safe_read` |
|
|
30
|
+
| Commands | Describe configured aliases; run one allowlisted executable with `shell=False` | `safe_read` / `workspace_execution` |
|
|
31
|
+
|
|
32
|
+
Every tool returns the same JSON envelope with `ok`, `tool`, `effect`, `data`, and `error` fields. Paths are always relative to a configured workspace root.
|
|
33
|
+
|
|
34
|
+
## Safety boundary
|
|
35
|
+
|
|
36
|
+
- Path traversal and access outside the workspace root are rejected.
|
|
37
|
+
- The workspace root cannot be deleted.
|
|
38
|
+
- Recursive deletion must be explicit.
|
|
39
|
+
- File reads, writes, hashes, and archive expansion have byte limits.
|
|
40
|
+
- Every workspace mutation and local command requires the SDK approval gate in addition to the orchestration approval policy. File copy accepts regular, non-symlink source files only.
|
|
41
|
+
- ZIP creation rejects symlinks; ZIP extraction rejects path traversal and symlink entries before writing files.
|
|
42
|
+
- HTTPS fetching requires an exact host allowlist, rejects redirects, URL credentials, and non-default ports, accepts only text-like content types, and blocks resolved private or loopback addresses. No host is enabled by default. Deployment still needs an egress proxy or firewall: application-layer DNS checks do not replace network isolation.
|
|
43
|
+
- Host diagnostics intentionally exclude user identities, process lists, network configuration, installed software, and environment variables except for names explicitly configured by the host.
|
|
44
|
+
- Command execution accepts an argument array, never a shell string. Programs must be mapped by the host application, execution has a timeout, and output is truncated.
|
|
45
|
+
- The local command runner is not an OS security sandbox. Production deployment must run the service or runner inside the company-approved container/sandbox with no production secrets and restricted network access.
|
|
46
|
+
- Approval remains the orchestration layer's responsibility. Only expose `workspace_write` or `workspace_execution` tools to an Agent after the matching approval has been validated.
|
|
47
|
+
|
|
48
|
+
This is a controlled operating-system capability adapter, not a general shell, process-management, credential, service-control, or unrestricted-network interface. Give each business Agent only the smallest subset of these tools it needs.
|
|
49
|
+
|
|
50
|
+
## Example
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import sys
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
|
|
56
|
+
from function_tools.openai_tools import ToolConfig, create_function_tools
|
|
57
|
+
|
|
58
|
+
bundle = create_function_tools(
|
|
59
|
+
ToolConfig(
|
|
60
|
+
workspace_root=Path("./workspace"),
|
|
61
|
+
command_programs={"python": sys.executable},
|
|
62
|
+
http_allowed_hosts=frozenset({"api.example.internal"}),
|
|
63
|
+
environment_variables=frozenset({"APP_ENV"}),
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# Safe tools can be attached to an Agent immediately.
|
|
68
|
+
safe_tools = list(bundle.safe_read)
|
|
69
|
+
|
|
70
|
+
# Select side-effect tools only after the policy and approval checks pass.
|
|
71
|
+
write_tools = list(bundle.workspace_write)
|
|
72
|
+
execution_tools = list(bundle.workspace_execution)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The SDK derives each FunctionTool's input schema from the Python signature and docstring. For production, keep the groups separate when attaching them to an Agent; do not use `bundle.all` by default.
|
|
76
|
+
|
|
77
|
+
## License
|
|
78
|
+
|
|
79
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
80
|
+
|
|
81
|
+
## Development
|
|
82
|
+
|
|
83
|
+
Use Python 3.10 or newer:
|
|
84
|
+
|
|
85
|
+
```powershell
|
|
86
|
+
uv sync --python 3.10
|
|
87
|
+
uv run --python 3.10 pytest
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Tests do not call the OpenAI API and do not require `OPENAI_API_KEY`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
agents_function_tools-0.2.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
2
|
+
function_tools/__init__.py,sha256=uQodWR3-RVViMwqWzUa3ME7tN1PmF-AcaPnprmN_-eg,521
|
|
3
|
+
function_tools/archive.py,sha256=9OH_fDf_WrTPUvj5K1q3JYWW24_9H-WZD5wmZSWT-ZE,10097
|
|
4
|
+
function_tools/command.py,sha256=XxGPP1HxVTNxUs16biKiD1XZYdShp8yEsJd1T7eYpZw,6663
|
|
5
|
+
function_tools/errors.py,sha256=_1DTe0pbmJh-8Jw36wKuRqI64H52qGOZehrMea5v_cs,355
|
|
6
|
+
function_tools/host.py,sha256=peTjIaR2HrEbY9dI7kngVVCNg49FzGFJIHDkGJk_0WY,1554
|
|
7
|
+
function_tools/http.py,sha256=StD3xQWsIjI9a4NF26PNRt_VV_HTIQF6ZsBe2_-duPI,5307
|
|
8
|
+
function_tools/openai_tools.py,sha256=xUX4laI1otyQZxDO0RkNRvy_YPJkhNr2oyi99nzFhn8,13473
|
|
9
|
+
function_tools/responses.py,sha256=62cr6XH0-Vy0KGrbm1IdlofVUijhs6fhnkdSwToqjgQ,960
|
|
10
|
+
function_tools/workspace.py,sha256=ggLN7KrBgTjZf06XqefM9SSI10sh3KhSHotoVgOiWRE,17236
|
|
11
|
+
agents_function_tools-0.2.0.dist-info/METADATA,sha256=2OwO1DB7p2PzoUeI-oo_AHfw_QKgKxfMiptqe8m8Wdw,4772
|
|
12
|
+
agents_function_tools-0.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
13
|
+
agents_function_tools-0.2.0.dist-info/top_level.txt,sha256=cah-OFcLksgsGtibTUzRSuQdzjdUO-geKFpC1LqojnE,15
|
|
14
|
+
agents_function_tools-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function_tools
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Portable, policy-friendly system function tools for AI applications."""
|
|
2
|
+
|
|
3
|
+
from .archive import ZipArchive
|
|
4
|
+
from .command import CommandPolicy, LocalCommandRunner
|
|
5
|
+
from .errors import FoundationToolError
|
|
6
|
+
from .host import HostInspector
|
|
7
|
+
from .http import HttpPolicy, HttpTextClient
|
|
8
|
+
from .workspace import Workspace
|
|
9
|
+
|
|
10
|
+
__version__ = "0.2.0"
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"CommandPolicy",
|
|
14
|
+
"FoundationToolError",
|
|
15
|
+
"HostInspector",
|
|
16
|
+
"HttpPolicy",
|
|
17
|
+
"HttpTextClient",
|
|
18
|
+
"LocalCommandRunner",
|
|
19
|
+
"Workspace",
|
|
20
|
+
"ZipArchive",
|
|
21
|
+
]
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
import zipfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .errors import FoundationToolError
|
|
10
|
+
from .workspace import Workspace
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ZipArchive:
|
|
14
|
+
"""ZIP operations confined to a workspace and bounded by its write limit."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, workspace: Workspace) -> None:
|
|
17
|
+
self.workspace = workspace
|
|
18
|
+
|
|
19
|
+
def list_entries(self, path: str, *, max_entries: int = 200) -> dict[str, Any]:
|
|
20
|
+
if not 1 <= max_entries <= 10_000:
|
|
21
|
+
raise FoundationToolError("INVALID_LIMIT", "max_entries must be between 1 and 10000.")
|
|
22
|
+
archive_path = self._archive_path(path)
|
|
23
|
+
try:
|
|
24
|
+
with zipfile.ZipFile(archive_path) as archive:
|
|
25
|
+
infos = archive.infolist()
|
|
26
|
+
except zipfile.BadZipFile as error:
|
|
27
|
+
raise FoundationToolError(
|
|
28
|
+
"INVALID_ARCHIVE", "Path is not a valid ZIP archive."
|
|
29
|
+
) from error
|
|
30
|
+
except OSError as error:
|
|
31
|
+
raise FoundationToolError("ARCHIVE_READ_FAILED", str(error), retryable=True) from error
|
|
32
|
+
entries = [self._entry(info) for info in infos[:max_entries]]
|
|
33
|
+
return {
|
|
34
|
+
"path": self.workspace.relative_path(archive_path),
|
|
35
|
+
"entries": entries,
|
|
36
|
+
"truncated": len(infos) > max_entries,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
def create(
|
|
40
|
+
self, paths: list[str], destination: str, *, overwrite: bool = False
|
|
41
|
+
) -> dict[str, Any]:
|
|
42
|
+
if not paths:
|
|
43
|
+
raise FoundationToolError(
|
|
44
|
+
"INVALID_ARCHIVE_INPUT", "paths must contain at least one file or directory."
|
|
45
|
+
)
|
|
46
|
+
destination_path = self.workspace._resolve(destination, allow_root=False)
|
|
47
|
+
if destination_path.exists() and not overwrite:
|
|
48
|
+
raise FoundationToolError(
|
|
49
|
+
"ALREADY_EXISTS", "Destination exists; set overwrite=true to replace it."
|
|
50
|
+
)
|
|
51
|
+
if destination_path.exists() and destination_path.is_dir():
|
|
52
|
+
raise FoundationToolError("IS_DIRECTORY", "Destination cannot be a directory.")
|
|
53
|
+
if not destination_path.parent.is_dir():
|
|
54
|
+
raise FoundationToolError("PARENT_NOT_FOUND", "Parent directory does not exist.")
|
|
55
|
+
files = self._collect_files(paths)
|
|
56
|
+
total_bytes = sum(file.stat().st_size for file in files)
|
|
57
|
+
if total_bytes > self.workspace.max_write_bytes:
|
|
58
|
+
raise FoundationToolError(
|
|
59
|
+
"CONTENT_TOO_LARGE", "Archive input exceeds the workspace write limit."
|
|
60
|
+
)
|
|
61
|
+
temporary_name: str | None = None
|
|
62
|
+
try:
|
|
63
|
+
with tempfile.NamedTemporaryFile(
|
|
64
|
+
dir=destination_path.parent, suffix=".zip", delete=False
|
|
65
|
+
) as temporary:
|
|
66
|
+
temporary_name = temporary.name
|
|
67
|
+
with zipfile.ZipFile(temporary_name, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
|
68
|
+
for file in files:
|
|
69
|
+
archive.write(file, arcname=self.workspace.relative_path(file))
|
|
70
|
+
archive_size = Path(temporary_name).stat().st_size
|
|
71
|
+
if archive_size > self.workspace.max_write_bytes:
|
|
72
|
+
raise FoundationToolError(
|
|
73
|
+
"CONTENT_TOO_LARGE", "Generated archive exceeds the workspace write limit."
|
|
74
|
+
)
|
|
75
|
+
os.replace(temporary_name, destination_path)
|
|
76
|
+
except FoundationToolError:
|
|
77
|
+
if temporary_name:
|
|
78
|
+
Path(temporary_name).unlink(missing_ok=True)
|
|
79
|
+
raise
|
|
80
|
+
except (OSError, zipfile.BadZipFile) as error:
|
|
81
|
+
if temporary_name:
|
|
82
|
+
Path(temporary_name).unlink(missing_ok=True)
|
|
83
|
+
raise FoundationToolError(
|
|
84
|
+
"ARCHIVE_CREATE_FAILED", str(error), retryable=True
|
|
85
|
+
) from error
|
|
86
|
+
return {
|
|
87
|
+
"path": self.workspace.relative_path(destination_path),
|
|
88
|
+
"source_files": len(files),
|
|
89
|
+
"bytes": archive_size,
|
|
90
|
+
"overwritten": overwrite,
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
def extract(self, path: str, destination: str, *, overwrite: bool = False) -> dict[str, Any]:
|
|
94
|
+
archive_path = self._archive_path(path)
|
|
95
|
+
destination_path = self.workspace._resolve(destination, allow_root=False)
|
|
96
|
+
if destination_path.exists() and not destination_path.is_dir():
|
|
97
|
+
raise FoundationToolError(
|
|
98
|
+
"NOT_A_DIRECTORY", "Extraction destination must be a directory."
|
|
99
|
+
)
|
|
100
|
+
if destination_path.exists() and any(destination_path.iterdir()) and not overwrite:
|
|
101
|
+
raise FoundationToolError(
|
|
102
|
+
"DIRECTORY_NOT_EMPTY", "Destination is not empty; set overwrite=true to extract."
|
|
103
|
+
)
|
|
104
|
+
try:
|
|
105
|
+
with zipfile.ZipFile(archive_path) as archive:
|
|
106
|
+
infos = archive.infolist()
|
|
107
|
+
total_bytes = sum(info.file_size for info in infos)
|
|
108
|
+
if total_bytes > self.workspace.max_write_bytes:
|
|
109
|
+
raise FoundationToolError(
|
|
110
|
+
"CONTENT_TOO_LARGE", "Archive contents exceed the workspace write limit."
|
|
111
|
+
)
|
|
112
|
+
outputs = self._validate_extraction_outputs(infos, destination, overwrite)
|
|
113
|
+
destination_path.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
for info, output in zip(infos, outputs, strict=True):
|
|
115
|
+
if info.is_dir():
|
|
116
|
+
output.mkdir(parents=True, exist_ok=True)
|
|
117
|
+
continue
|
|
118
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
119
|
+
with archive.open(info) as source, output.open("wb") as target:
|
|
120
|
+
target.write(source.read())
|
|
121
|
+
except FoundationToolError:
|
|
122
|
+
raise
|
|
123
|
+
except zipfile.BadZipFile as error:
|
|
124
|
+
raise FoundationToolError(
|
|
125
|
+
"INVALID_ARCHIVE", "Path is not a valid ZIP archive."
|
|
126
|
+
) from error
|
|
127
|
+
except OSError as error:
|
|
128
|
+
raise FoundationToolError(
|
|
129
|
+
"ARCHIVE_EXTRACT_FAILED", str(error), retryable=True
|
|
130
|
+
) from error
|
|
131
|
+
return {
|
|
132
|
+
"path": self.workspace.relative_path(archive_path),
|
|
133
|
+
"destination": self.workspace.relative_path(destination_path),
|
|
134
|
+
"entries": len(infos),
|
|
135
|
+
"bytes": total_bytes,
|
|
136
|
+
"overwritten": overwrite,
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
def _archive_path(self, path: str) -> Path:
|
|
140
|
+
archive_path = self.workspace._resolve(path)
|
|
141
|
+
if not archive_path.is_file():
|
|
142
|
+
raise FoundationToolError("NOT_A_FILE", "Path is not a regular file.")
|
|
143
|
+
if archive_path.stat().st_size > self.workspace.max_read_bytes:
|
|
144
|
+
raise FoundationToolError("FILE_TOO_LARGE", "Archive exceeds the workspace read limit.")
|
|
145
|
+
return archive_path
|
|
146
|
+
|
|
147
|
+
def _collect_files(self, paths: list[str]) -> list[Path]:
|
|
148
|
+
files: list[Path] = []
|
|
149
|
+
for value in paths:
|
|
150
|
+
candidate = self.workspace._resolve(value)
|
|
151
|
+
if candidate.is_symlink():
|
|
152
|
+
raise FoundationToolError(
|
|
153
|
+
"SYMLINK_NOT_SUPPORTED", "Archives cannot include symlinks."
|
|
154
|
+
)
|
|
155
|
+
if candidate.is_file():
|
|
156
|
+
files.append(candidate)
|
|
157
|
+
elif candidate.is_dir():
|
|
158
|
+
for nested in self.workspace._walk_entries(candidate):
|
|
159
|
+
if nested.is_symlink():
|
|
160
|
+
raise FoundationToolError(
|
|
161
|
+
"SYMLINK_NOT_SUPPORTED", "Archives cannot include symlinks."
|
|
162
|
+
)
|
|
163
|
+
if nested.is_file():
|
|
164
|
+
files.append(nested)
|
|
165
|
+
else:
|
|
166
|
+
raise FoundationToolError("NOT_FOUND", "Archive input path does not exist.")
|
|
167
|
+
return sorted(set(files), key=lambda item: item.as_posix().lower())
|
|
168
|
+
|
|
169
|
+
def _validate_member(self, info: zipfile.ZipInfo) -> None:
|
|
170
|
+
member = Path(info.filename.replace("\\", "/"))
|
|
171
|
+
if not info.filename or member.is_absolute() or ".." in member.parts:
|
|
172
|
+
raise FoundationToolError(
|
|
173
|
+
"UNSAFE_ARCHIVE_ENTRY", "Archive contains an unsafe entry path."
|
|
174
|
+
)
|
|
175
|
+
mode = info.external_attr >> 16
|
|
176
|
+
if mode and (mode & 0o170000) == 0o120000:
|
|
177
|
+
raise FoundationToolError(
|
|
178
|
+
"UNSAFE_ARCHIVE_ENTRY", "Archive symlink entries are not allowed."
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def _validate_extraction_outputs(
|
|
182
|
+
self, infos: list[zipfile.ZipInfo], destination: str, overwrite: bool
|
|
183
|
+
) -> list[Path]:
|
|
184
|
+
outputs: list[Path] = []
|
|
185
|
+
output_kinds: dict[Path, bool] = {}
|
|
186
|
+
for info in infos:
|
|
187
|
+
self._validate_member(info)
|
|
188
|
+
output = self.workspace._resolve(
|
|
189
|
+
str(Path(destination) / info.filename.replace("\\", "/")), allow_root=False
|
|
190
|
+
)
|
|
191
|
+
if output in output_kinds:
|
|
192
|
+
raise FoundationToolError(
|
|
193
|
+
"DUPLICATE_ARCHIVE_ENTRY", "Archive contains duplicate output paths."
|
|
194
|
+
)
|
|
195
|
+
if output.exists() and not overwrite:
|
|
196
|
+
raise FoundationToolError(
|
|
197
|
+
"ALREADY_EXISTS", f"Archive output already exists: {info.filename}"
|
|
198
|
+
)
|
|
199
|
+
if output.exists() and output.is_dir() != info.is_dir():
|
|
200
|
+
raise FoundationToolError(
|
|
201
|
+
"ARCHIVE_PATH_CONFLICT", "Archive entry conflicts with an existing path type."
|
|
202
|
+
)
|
|
203
|
+
output_kinds[output] = info.is_dir()
|
|
204
|
+
outputs.append(output)
|
|
205
|
+
|
|
206
|
+
file_outputs = {path for path, is_directory in output_kinds.items() if not is_directory}
|
|
207
|
+
for output in output_kinds:
|
|
208
|
+
if any(parent in file_outputs for parent in output.parents):
|
|
209
|
+
raise FoundationToolError(
|
|
210
|
+
"ARCHIVE_PATH_CONFLICT", "Archive file cannot also be a parent directory."
|
|
211
|
+
)
|
|
212
|
+
return outputs
|
|
213
|
+
|
|
214
|
+
def _entry(self, info: zipfile.ZipInfo) -> dict[str, Any]:
|
|
215
|
+
return {
|
|
216
|
+
"path": info.filename,
|
|
217
|
+
"kind": "directory" if info.is_dir() else "file",
|
|
218
|
+
"compressed_bytes": info.compress_size,
|
|
219
|
+
"bytes": info.file_size,
|
|
220
|
+
}
|