zettcode-tools 0.5.1__tar.gz → 0.5.3__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.
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/.gitignore +1 -1
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/PKG-INFO +2 -2
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/pyproject.toml +1 -1
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/files.py +20 -14
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/shell.py +43 -0
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/workspace.py +34 -4
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/__init__.py +0 -0
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/boundary.py +0 -0
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/images.py +0 -0
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/output.py +0 -0
- {zettcode_tools-0.5.1 → zettcode_tools-0.5.3}/src/zettcode/tools/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: zettcode-tools
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.3
|
|
4
4
|
Summary: The coding tools of ZettCode: read, search, write, edit and the shell, as a part of the agent that lives apart from it
|
|
5
5
|
Project-URL: Repository, https://github.com/Chang-LeHung/zettcode
|
|
6
6
|
Author: Chang-LeHung
|
|
@@ -16,4 +16,4 @@ Classifier: Programming Language :: Python :: 3.15
|
|
|
16
16
|
Classifier: Typing :: Typed
|
|
17
17
|
Requires-Python: >=3.10
|
|
18
18
|
Requires-Dist: pydantic<3,>=2
|
|
19
|
-
Requires-Dist: zett-agent<0.
|
|
19
|
+
Requires-Dist: zett-agent<0.4,>=0.3.2
|
|
@@ -18,7 +18,7 @@ classifiers = [
|
|
|
18
18
|
]
|
|
19
19
|
dependencies = [
|
|
20
20
|
# The tool contract, the message types and the @tool builder.
|
|
21
|
-
"zett-agent>=0.2
|
|
21
|
+
"zett-agent>=0.3.2,<0.4",
|
|
22
22
|
# A tool's parameters are described with the schema library the framework uses.
|
|
23
23
|
"pydantic>=2,<3",
|
|
24
24
|
]
|
|
@@ -38,7 +38,9 @@ from .workspace import (
|
|
|
38
38
|
FilePath = Annotated[str, Field(min_length=1)]
|
|
39
39
|
Expression = Annotated[str, Field(min_length=1)]
|
|
40
40
|
Offset = Annotated[int, Field(ge=1)]
|
|
41
|
-
|
|
41
|
+
#: The most lines one read may return, and the number it returns when the call names no limit.
|
|
42
|
+
MAX_READ_LINES = 2_000
|
|
43
|
+
Limit = Annotated[int, Field(ge=1, le=MAX_READ_LINES)]
|
|
42
44
|
MaxResults = Annotated[int, Field(ge=1, le=5_000)]
|
|
43
45
|
OldString = Annotated[str, Field(min_length=1)]
|
|
44
46
|
|
|
@@ -53,17 +55,19 @@ def _image_type_of(path: Path) -> str | None:
|
|
|
53
55
|
|
|
54
56
|
|
|
55
57
|
@tool
|
|
56
|
-
def read(file_path: FilePath, offset: Offset = 1, limit: Limit =
|
|
58
|
+
def read(file_path: FilePath, offset: Offset = 1, limit: Limit = MAX_READ_LINES) -> ReadResult:
|
|
57
59
|
"""Read a local file: UTF-8 text as a line range, or a PNG, JPEG, GIF, or WebP image as an image.
|
|
58
60
|
|
|
59
61
|
Args:
|
|
60
62
|
file_path: Absolute path or a path relative to the current working directory.
|
|
61
63
|
offset: One-based line number to start reading from; ignored for images.
|
|
62
|
-
limit: Maximum number of lines to return;
|
|
64
|
+
limit: Maximum number of lines to return, 2,000 by default and never more; the result is also held to
|
|
65
|
+
50 KB; ignored for images.
|
|
63
66
|
|
|
64
67
|
Returns:
|
|
65
|
-
The requested line range,
|
|
66
|
-
continue when more lines remain.
|
|
68
|
+
The requested line range, each line prefixed with its 1-based number and a tab (``<line>\\t<content>``), or the
|
|
69
|
+
image and a one-line description of it; a trailing hint says how to continue when more lines remain. The
|
|
70
|
+
prefix is for reference: it is not part of the file.
|
|
67
71
|
|
|
68
72
|
Snippet:
|
|
69
73
|
read(file_path="docs/diagram.png")
|
|
@@ -74,6 +78,7 @@ def read(file_path: FilePath, offset: Offset = 1, limit: Limit = 200) -> ReadRes
|
|
|
74
78
|
- A trailing hint says how to go on: the next offset when more lines remain, or the shell when one line is
|
|
75
79
|
longer than the output limit.
|
|
76
80
|
- An image comes back as an image with a one-line description; the range arguments do not apply to it.
|
|
81
|
+
- The line numbers are for reference; do not copy them into an edit or a write.
|
|
77
82
|
- PDF and SVG files are not supported.
|
|
78
83
|
"""
|
|
79
84
|
located = Located.of(file_path)
|
|
@@ -91,23 +96,27 @@ def read(file_path: FilePath, offset: Offset = 1, limit: Limit = 200) -> ReadRes
|
|
|
91
96
|
|
|
92
97
|
|
|
93
98
|
@tool
|
|
94
|
-
def read_file(file_path: FilePath, offset: Offset = 1, limit: Limit =
|
|
99
|
+
def read_file(file_path: FilePath, offset: Offset = 1, limit: Limit = MAX_READ_LINES) -> str:
|
|
95
100
|
"""Read a line range from a UTF-8 text file.
|
|
96
101
|
|
|
97
102
|
Args:
|
|
98
103
|
file_path: Absolute path or a path relative to the current working directory.
|
|
99
104
|
offset: One-based line number to start reading from.
|
|
100
|
-
limit: Maximum number of lines to return
|
|
105
|
+
limit: Maximum number of lines to return, 2,000 by default and never more; the result is also held to
|
|
106
|
+
50 KB.
|
|
101
107
|
|
|
102
108
|
Returns:
|
|
103
|
-
The requested line range
|
|
109
|
+
The requested line range, each line prefixed with its 1-based number and a tab (``<line>\\t<content>``); a
|
|
110
|
+
trailing hint says how to continue when more lines remain. The prefix is for reference: it is not part of the
|
|
111
|
+
file.
|
|
104
112
|
|
|
105
113
|
Snippet:
|
|
106
|
-
read_file(file_path="src/app.py", offset=
|
|
114
|
+
read_file(file_path="src/app.py", offset=500)
|
|
107
115
|
|
|
108
116
|
Guidelines:
|
|
109
117
|
- Use line ranges for large files.
|
|
110
118
|
- Inspect the current content before editing a file.
|
|
119
|
+
- The line numbers are for reference; do not copy them into an edit or a write.
|
|
111
120
|
"""
|
|
112
121
|
located = Located.of(file_path)
|
|
113
122
|
located.require_file()
|
|
@@ -217,13 +226,12 @@ def grep(
|
|
|
217
226
|
|
|
218
227
|
|
|
219
228
|
@tool
|
|
220
|
-
def write_file(file_path: FilePath, content: str
|
|
229
|
+
def write_file(file_path: FilePath, content: str) -> str:
|
|
221
230
|
"""Atomically write a UTF-8 text file.
|
|
222
231
|
|
|
223
232
|
Args:
|
|
224
233
|
file_path: Absolute path or a path relative to the current working directory.
|
|
225
234
|
content: Complete UTF-8 text to write.
|
|
226
|
-
overwrite: Whether an existing file may be replaced.
|
|
227
235
|
|
|
228
236
|
Returns:
|
|
229
237
|
One line saying whether the file was created or replaced, and its path.
|
|
@@ -239,8 +247,6 @@ def write_file(file_path: FilePath, content: str, overwrite: bool = True) -> str
|
|
|
239
247
|
exists = located.path.exists()
|
|
240
248
|
if exists and not located.path.is_file():
|
|
241
249
|
raise ValueError(f"Path is not a file: {file_path}")
|
|
242
|
-
if exists and not overwrite:
|
|
243
|
-
raise ValueError(f"File already exists: {file_path}")
|
|
244
250
|
write_text(located.path, content)
|
|
245
251
|
return f"{'Wrote' if exists else 'Created'} {located.shown}"
|
|
246
252
|
|
|
@@ -266,7 +272,7 @@ def edit(file_path: FilePath, old_string: OldString, new_string: str, replace_al
|
|
|
266
272
|
- Always use this tool when you need to modify an existing file, instead of sed, awk, perl -i, python -c, tee, or shell redirection. Reserve those for bulk or mechanical rewrites this tool cannot express, such as renaming a symbol across many files.
|
|
267
273
|
- One change a call: call edit again for the next change, and nothing is written when the old text does not match.
|
|
268
274
|
- Avoid sed, cat, and similar shell commands for reading or changing files unless it is necessary; inspect files with the read tool and change them with this tool.
|
|
269
|
-
- Read the target lines first and copy old_string exactly: same indentation, quotes, and line breaks.
|
|
275
|
+
- Read the target lines first and copy old_string exactly: same indentation, quotes, and line breaks; a read's line number and tab are not part of the file.
|
|
270
276
|
- Make old_string unique by including a neighbouring line or two; set replace_all only when every occurrence must change.
|
|
271
277
|
- When an edit fails, read the file again and retry with corrected old_string rather than switching to a shell command.
|
|
272
278
|
"""
|
|
@@ -15,6 +15,9 @@ import asyncio
|
|
|
15
15
|
import os
|
|
16
16
|
import signal
|
|
17
17
|
import tempfile
|
|
18
|
+
from collections.abc import Iterator, Mapping
|
|
19
|
+
from contextlib import contextmanager
|
|
20
|
+
from contextvars import ContextVar
|
|
18
21
|
from pathlib import Path
|
|
19
22
|
from typing import Annotated
|
|
20
23
|
|
|
@@ -33,6 +36,43 @@ OUTPUT_ROOT = ".zett-tool-output"
|
|
|
33
36
|
DEFAULT_TIMEOUT_SECONDS = 60
|
|
34
37
|
MAX_TIMEOUT_SECONDS = 600
|
|
35
38
|
|
|
39
|
+
_ENVIRONMENT: ContextVar[Mapping[str, str | None] | None] = ContextVar("zettcode_shell_environment", default=None)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@contextmanager
|
|
43
|
+
def shell_environment(values: Mapping[str, str | None]) -> Iterator[None]:
|
|
44
|
+
"""Overlay environment variables for this task's subprocesses only; ``None`` removes a variable.
|
|
45
|
+
|
|
46
|
+
Nested scopes compose, parallel tool calls stay isolated, and cancellation restores the prior scope.
|
|
47
|
+
The process environment is never changed. Tool backends that start their own subprocess may use
|
|
48
|
+
:func:`subprocess_environment` to carry the same handoff.
|
|
49
|
+
"""
|
|
50
|
+
token = _ENVIRONMENT.set({**(_ENVIRONMENT.get() or {}), **values})
|
|
51
|
+
try:
|
|
52
|
+
yield
|
|
53
|
+
finally:
|
|
54
|
+
_ENVIRONMENT.reset(token)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def shell_environment_values() -> dict[str, str | None]:
|
|
58
|
+
"""Return only the task overlay, without inheriting process credentials or stale handoffs."""
|
|
59
|
+
return dict(_ENVIRONMENT.get() or {})
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def subprocess_environment() -> dict[str, str] | None:
|
|
63
|
+
"""Return a fresh process environment with the current task's overlay, or ``None`` to inherit normally."""
|
|
64
|
+
values = _ENVIRONMENT.get()
|
|
65
|
+
if not values:
|
|
66
|
+
return None
|
|
67
|
+
env = dict(os.environ)
|
|
68
|
+
for key, value in values.items():
|
|
69
|
+
if value is None:
|
|
70
|
+
env.pop(key, None)
|
|
71
|
+
else:
|
|
72
|
+
env[key] = value
|
|
73
|
+
return env
|
|
74
|
+
|
|
75
|
+
|
|
36
76
|
Command = Annotated[str, Field(min_length=1)]
|
|
37
77
|
WorkDir = Annotated[str, Field(min_length=1)]
|
|
38
78
|
TimeoutSeconds = Annotated[int, Field(ge=1, le=MAX_TIMEOUT_SECONDS)]
|
|
@@ -95,6 +135,7 @@ async def run_command(command: str, timeout_seconds: int, directory: Path | None
|
|
|
95
135
|
stdout=stdout_target,
|
|
96
136
|
stderr=stderr_target,
|
|
97
137
|
start_new_session=os.name == "posix",
|
|
138
|
+
env=subprocess_environment(),
|
|
98
139
|
)
|
|
99
140
|
try:
|
|
100
141
|
await asyncio.wait_for(process.wait(), timeout_seconds)
|
|
@@ -181,5 +222,7 @@ __all__ = [
|
|
|
181
222
|
"OUTPUT_ROOT",
|
|
182
223
|
"CommandFailed",
|
|
183
224
|
"run_command",
|
|
225
|
+
"shell_environment",
|
|
226
|
+
"subprocess_environment",
|
|
184
227
|
"shell_tool",
|
|
185
228
|
]
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import os
|
|
6
|
+
import re
|
|
6
7
|
import tempfile
|
|
7
8
|
from dataclasses import dataclass
|
|
8
9
|
from pathlib import Path
|
|
@@ -140,6 +141,9 @@ def write_text(path: Path, content: str) -> None:
|
|
|
140
141
|
def read_lines(located: Located, offset: int, limit: int) -> str:
|
|
141
142
|
"""Return ``limit`` lines of a UTF-8 file from line ``offset``, with a note on how to continue when more remains.
|
|
142
143
|
|
|
144
|
+
Each line is prefixed with its 1-based number and a tab (``<number>\\t<content>``); the prefix is for reference
|
|
145
|
+
and is not part of the file.
|
|
146
|
+
|
|
143
147
|
The result is held to :data:`MAX_OUTPUT_BYTES`. A line longer than that is cut, and the note says so: the
|
|
144
148
|
reader has no column to resume from, because one 2 MB line is not what the tool is for — the shell reads it.
|
|
145
149
|
A cut inside an ordinary line is not that: the budget was used up before it, and the note then names the line
|
|
@@ -154,7 +158,7 @@ def read_lines(located: Located, offset: int, limit: int) -> str:
|
|
|
154
158
|
ValueError: When the file is not UTF-8 text.
|
|
155
159
|
"""
|
|
156
160
|
selected: list[str] = []
|
|
157
|
-
number, used, line_start = 1, 0, 0
|
|
161
|
+
number, used, line_start, emitted = 1, 0, 0, 0
|
|
158
162
|
next_offset: int | None = None
|
|
159
163
|
cut_at: int | None = None
|
|
160
164
|
oversized = False
|
|
@@ -165,15 +169,26 @@ def read_lines(located: Located, offset: int, limit: int) -> str:
|
|
|
165
169
|
next_offset = number
|
|
166
170
|
break
|
|
167
171
|
if number >= offset:
|
|
168
|
-
|
|
172
|
+
# The prefix belongs to the first fragment of a line; a long line is read in pieces, and
|
|
173
|
+
# repeating the number for each would put it in the middle of the content.
|
|
174
|
+
prefix = "" if number == emitted else f"{number}\t"
|
|
175
|
+
numbered = prefix + fragment
|
|
176
|
+
part = utf8_prefix(numbered, MAX_OUTPUT_BYTES - used)
|
|
177
|
+
if len(part) <= len(prefix):
|
|
178
|
+
# The budget ran out inside the line number, or exactly at it. A bare number would read
|
|
179
|
+
# as content, so emit none of the line and send the reader back to it.
|
|
180
|
+
cut_at = number
|
|
181
|
+
oversized = _line_longer_than_budget(source, used - line_start, numbered, MAX_OUTPUT_BYTES)
|
|
182
|
+
break
|
|
169
183
|
selected.append(part)
|
|
170
184
|
used += len(part.encode("utf-8"))
|
|
171
|
-
|
|
185
|
+
emitted = number
|
|
186
|
+
if len(part) < len(numbered):
|
|
172
187
|
# Whether this line could fill a call of its own decides what the note says, and only
|
|
173
188
|
# what is left of the line knows that. Reading on is bounded by one budget.
|
|
174
189
|
cut_at = number
|
|
175
190
|
oversized = _line_longer_than_budget(
|
|
176
|
-
source, used - line_start,
|
|
191
|
+
source, used - line_start, numbered[len(part) :], MAX_OUTPUT_BYTES
|
|
177
192
|
)
|
|
178
193
|
break
|
|
179
194
|
if fragment.endswith("\n"):
|
|
@@ -245,6 +260,11 @@ def apply_edit(content: str, old_string: str, new_string: str, replace_all: bool
|
|
|
245
260
|
|
|
246
261
|
def _miss_hint(content: str, old_string: str) -> str:
|
|
247
262
|
"""Say why an exact match failed, so the model fixes ``old_string`` instead of leaving the tool."""
|
|
263
|
+
if _numbered_copy_matches(content, old_string):
|
|
264
|
+
return (
|
|
265
|
+
"A read prefixes each line with its number and a tab, and those are not in the file; "
|
|
266
|
+
"copy the lines again without them. Nothing was written."
|
|
267
|
+
)
|
|
248
268
|
if " ".join(content.split()).count(" ".join(old_string.split())) > 0:
|
|
249
269
|
return (
|
|
250
270
|
"A match exists that differs only in whitespace or indentation; "
|
|
@@ -253,6 +273,16 @@ def _miss_hint(content: str, old_string: str) -> str:
|
|
|
253
273
|
return "Read the file again and copy old_string from its current content. Nothing was written."
|
|
254
274
|
|
|
255
275
|
|
|
276
|
+
#: A line a read returned: its 1-based number, a tab, then the file's own text.
|
|
277
|
+
_NUMBERED_LINE = re.compile(r"^[ \t]*\d+\t", re.MULTILINE)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _numbered_copy_matches(content: str, old_string: str) -> bool:
|
|
281
|
+
"""Return whether ``old_string`` matches once a read's line numbers and tabs are removed."""
|
|
282
|
+
stripped = _NUMBERED_LINE.sub("", old_string)
|
|
283
|
+
return stripped != old_string and stripped in content
|
|
284
|
+
|
|
285
|
+
|
|
256
286
|
def _excerpt(value: str, *, limit: int = 60) -> str:
|
|
257
287
|
"""Shorten one matched snippet for an error message."""
|
|
258
288
|
collapsed = " ".join(value.split())
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|