Skip to content
6 changes: 5 additions & 1 deletion packages/genkit-middleware/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ response = await ai.generate(
)
```

Skills are discovered by scanning for directories containing `SKILL.md` files. Each `SKILL.md` can have optional YAML frontmatter:
Each direct subdirectory of a skill path that holds a `SKILL.md` is a skill, named after the directory (`skills/python-expert/SKILL.md` is `python-expert`). Frontmatter `description` shows up in the catalog; frontmatter `name` doesn't rename the skill:

```markdown
---
Expand All @@ -179,6 +179,8 @@ description: Expert Python programming assistance
You are an expert Python programmer...
```

When two skill paths hold the same name, the later path wins. A symlinked skill directory is followed, so `skills/plating -> ~/shared/plating` works. A `SKILL.md` that is itself a symlink, not a regular file, or over 1 MiB isn't read.

### Filesystem

Provides sandboxed file operations confined to a root directory:
Expand Down Expand Up @@ -206,6 +208,8 @@ Provides four tools:
- `write_file`: Write to a file (requires `allow_write_access=True`)
- `edit_file`: Edit file with string replacements (requires `allow_write_access=True`)

Paths resolve against `root_dir`. An absolute path works only if it already points inside the root; `/etc/hosts` is refused, not read as `{root}/etc/hosts`. Symlinks are resolved first, so a link out of the root is refused and left out of `list_files`. Tool errors come back as the tool response with the host root path removed.

### Artifacts

Exposes `read_artifact` / `write_artifact` tools and lists session artifacts in the
Expand Down
166 changes: 130 additions & 36 deletions packages/genkit-middleware/src/genkit_middleware/_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,14 @@
Provides sandboxed file operations — ``list_files``, ``read_file``,
``write_file``, ``edit_file`` — confined to a configurable root directory.

Paths resolve against the root. An absolute path is accepted only when it
already points inside the root. Symlinks are resolved before the containment
check, so a link that points outside the root is refused.

``read_file`` queues file content as user messages so the tool response stays
small. Tool errors are queued the same way so the model can self-correct on
the next turn.
small. Tool errors come back as the tool's own response, with the host root
path redacted, so the model can self-correct without a user turn landing
between the tool response and the next model turn.

Each ``generate()`` gets a fresh middleware instance with its own message
queue; ``wrap_generate`` drains queued messages into the request before the
Expand All @@ -32,8 +37,11 @@

import asyncio
import base64
import errno
import mimetypes
import os
import re
import stat
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -73,8 +81,8 @@ class _ReadFileInput(PydanticBaseModel):
"""Input for read_file tool."""

file_path: str
offset: int = 0
limit: int = 0
offset: int = Field(default=0, ge=0, description='1-based line to start from; 0 reads from the top.')
limit: int = Field(default=0, ge=0, description='Number of lines to read; 0 reads to the end.')


class _WriteFileInput(PydanticBaseModel):
Expand Down Expand Up @@ -103,6 +111,19 @@ class _EditFileInput(PydanticBaseModel):
_MAX_READ_SLICE_BYTES = 256 * 1024 # 256 KB — max bytes returned per slice


def _attr_text(value: str) -> str:
"""Escape text placed in a double-quoted attribute of the ``<read_file>`` wrapper."""
return (
value
.replace('&', '&amp;')
.replace('<', '&lt;')
.replace('>', '&gt;')
.replace('"', '&quot;')
.replace('\n', ' ')
.replace('\r', ' ')
)


class FilesystemConfig(GenkitConfig):
"""Sandbox root and write/tool naming options."""

Expand All @@ -120,8 +141,8 @@ class Filesystem(Middleware[FilesystemConfig]):
"""Filesystem middleware with sandboxed file operations.

Contributes ``list_files``, ``read_file``, and optionally ``write_file``
and ``edit_file``. Tool errors are queued as user messages so the model
can self-correct on the next turn.
and ``edit_file``. Tool errors are returned as the tool response so the
model can self-correct on the next turn.
"""

name = 'filesystem'
Expand All @@ -147,18 +168,64 @@ def _filesystem_tool_names(self) -> frozenset[str]:
names |= {self._tool_name('write_file'), self._tool_name('edit_file')}
return frozenset(names)

def _resolve_safe(self, rel: str) -> str:
"""Resolve ``rel`` to an absolute path, raising ValueError if it escapes root."""
rel = rel.strip().lstrip('/').lstrip('\\')
if not rel:
rel = '.'
candidate = os.path.realpath(os.path.join(self._root_abs, rel))
c_norm = os.path.normcase(candidate)
def _contains(self, abs_path: str) -> bool:
"""Whether a resolved absolute path is the root or under it."""
c_norm = os.path.normcase(abs_path)
root_norm = os.path.normcase(self._root_abs)
if c_norm != root_norm and not c_norm.startswith(root_norm + os.sep):
raise ValueError(f'Path {rel!r} escapes the root directory.')
return c_norm == root_norm or c_norm.startswith(root_norm.rstrip(os.sep) + os.sep)

def _resolve_safe(self, path: str) -> str:
"""Resolve a model-supplied path to a real absolute path inside the root.

A relative path resolves against the root. An absolute path is used
as-is and must already be inside the root: ``/etc/hosts`` is refused,
not rewritten to ``{root}/etc/hosts``. Raises ValueError otherwise.
"""
path = path.strip()
if '\x00' in path:
raise ValueError(f'Path {path!r} contains a NUL byte.')
candidate = os.path.realpath(os.path.join(self._root_abs, path or '.'))
if not self._contains(candidate):
if os.path.isabs(path):
raise ValueError(f'Absolute path {path!r} escapes the root directory; use a path relative to the root.')
raise ValueError(f'Path {path!r} escapes the root directory.')
return candidate

def _redact(self, text: str) -> str:
"""Rewrite host root paths in an error message relative to the root."""
seps = re.escape(os.sep + (os.altsep or ''))
roots: set[str] = {self._root_abs, os.path.abspath(self.config.root_dir)}
for root in sorted(roots, key=lambda r: len(r), reverse=True):
if root == os.path.dirname(root):
continue # A filesystem root ('/') is no secret, and replacing it mangles every path.
escaped = re.escape(root)
text = re.sub(rf'(?<![\w.-]){escaped}[{seps}]', '', text)
text = re.sub(rf'(?<![\w.-]){escaped}(?![\w.\-{seps}])', '.', text)
return text

def _describe(self, abs_path: str) -> tuple[bool, int] | None:
"""Return ``(is_directory, size_bytes)`` for a listing entry.

Uses ``lstat``, so a symlink is described by its target only when the
target is inside the root. A symlink out of the root, a special file
(FIFO, socket, device), or an entry that can't be stat'ed is left out
instead of leaking or advertising an unreadable entry.
"""
try:
st = os.lstat(abs_path)
if stat.S_ISLNK(st.st_mode):
target = os.path.realpath(abs_path)
if not self._contains(target):
return None
st = os.stat(target)
except OSError:
return None
if stat.S_ISDIR(st.st_mode):
return True, 0
if stat.S_ISREG(st.st_mode):
return False, st.st_size
return None

def _enqueue_parts(self, parts: list[Part]) -> None:
"""Append parts to the pending user message for the next model turn."""
if self._message_queue and self._message_queue[-1].role == Role.USER:
Expand All @@ -174,40 +241,44 @@ def _list_files(self, dir_path: str = '', recursive: bool = False) -> list[dict[

results: list[dict[str, Any]] = []
if recursive:
# os.walk doesn't follow links: a symlinked directory is listed, never descended.
for root, dirs, files in os.walk(abs_dir):
dirs[:] = sorted(d for d in dirs if not d.startswith('.'))
for name in sorted(files):
abs_path = os.path.join(root, name)
try:
stat = os.stat(abs_path)
rel = os.path.relpath(abs_path, abs_dir)
results.append({'path': rel, 'is_directory': False, 'size_bytes': stat.st_size})
except OSError:
info = self._describe(abs_path)
if info is None:
continue
is_dir, size = info
rel = os.path.relpath(abs_path, abs_dir)
results.append({'path': rel, 'is_directory': is_dir, 'size_bytes': size})
for name in dirs:
rel = os.path.relpath(os.path.join(root, name), abs_dir)
abs_path = os.path.join(root, name)
if self._describe(abs_path) is None:
continue
rel = os.path.relpath(abs_path, abs_dir)
results.append({'path': rel, 'is_directory': True, 'size_bytes': 0})
else:
for name in sorted(os.listdir(abs_dir)):
abs_path = os.path.join(abs_dir, name)
try:
stat = os.stat(abs_path)
is_dir = os.path.isdir(abs_path)
results.append({'path': name, 'is_directory': is_dir, 'size_bytes': 0 if is_dir else stat.st_size})
except OSError:
info = self._describe(os.path.join(abs_dir, name))
if info is None:
continue
is_dir, size = info
results.append({'path': name, 'is_directory': is_dir, 'size_bytes': size})

return results

def _read_file_impl(self, file_path: str, offset: int, limit: int) -> str:
"""Read a file and enqueue its content as a user message."""
if offset < 0 or limit < 0:
raise ValueError(f'offset and limit must be >= 0 (got offset={offset}, limit={limit}).')
abs_path = self._resolve_safe(file_path)
if not os.path.isfile(abs_path):
raise ValueError(f'File not found: {file_path!r}')

stat = os.stat(abs_path)
if stat.st_size > _MAX_FILE_SIZE_BYTES:
raise ValueError(f'File too large ({stat.st_size:,} bytes; max {_MAX_FILE_SIZE_BYTES:,}).')
stat_result = os.stat(abs_path)
if stat_result.st_size > _MAX_FILE_SIZE_BYTES:
raise ValueError(f'File too large ({stat_result.st_size:,} bytes; max {_MAX_FILE_SIZE_BYTES:,}).')

mime_type, _ = mimetypes.guess_type(abs_path)
is_image = bool(mime_type and mime_type.startswith('image/'))
Expand All @@ -233,16 +304,25 @@ def _read_file_impl(self, file_path: str, offset: int, limit: int) -> str:
if len(sliced.encode()) > _MAX_READ_SLICE_BYTES:
raise ValueError(f'Slice too large ({len(sliced):,} chars). Use offset/limit to read smaller sections.')

path_attr = _attr_text(file_path)
if offset > 0 or limit > 0:
wrapped = f'<read_file path="{file_path}" lines="{start + 1}-{end}">\n{sliced}\n</read_file>'
wrapped = f'<read_file path="{path_attr}" lines="{start + 1}-{end}">\n{sliced}\n</read_file>'
else:
wrapped = f'<read_file path="{file_path}" totalLines="{total}">\n{sliced}\n</read_file>'
wrapped = f'<read_file path="{path_attr}" totalLines="{total}">\n{sliced}\n</read_file>'

self._enqueue_parts([Part.from_text(wrapped)])
return f'File {file_path} read successfully. Content queued as user message.'

def _write_file_impl(self, file_path: str, content: str) -> str:
abs_path = self._resolve_safe(file_path)
try:
st = os.lstat(abs_path)
except FileNotFoundError:
st = None
if st is not None and not stat.S_ISREG(st.st_mode):
if stat.S_ISDIR(st.st_mode):
raise IsADirectoryError(errno.EISDIR, 'Is a directory', abs_path)
raise ValueError(f'Cannot write to non-regular file: {file_path!r}')
os.makedirs(os.path.dirname(abs_path) or '.', exist_ok=True)
with open(abs_path, 'w', encoding='utf-8') as fh:
fh.write(content)
Expand All @@ -253,6 +333,10 @@ def _edit_file_impl(self, file_path: str, edits: list[dict[str, Any]]) -> str:
if not os.path.isfile(abs_path):
raise ValueError(f'File not found: {file_path!r}')

stat_result = os.stat(abs_path)
if stat_result.st_size > _MAX_FILE_SIZE_BYTES:
raise ValueError(f'File too large ({stat_result.st_size:,} bytes; max {_MAX_FILE_SIZE_BYTES:,}).')

with open(abs_path, encoding='utf-8', errors='replace') as fh:
content = fh.read()

Expand All @@ -270,6 +354,13 @@ def _edit_file_impl(self, file_path: str, edits: list[dict[str, Any]]) -> str:
if not replace_all and count > 1:
raise ValueError(f'old_string matches {count} times but replace_all=False.')
content = content.replace(old, new) if replace_all else content.replace(old, new, 1)
if len(content) > _MAX_FILE_SIZE_BYTES:
encoded_len = len(content.encode('utf-8'))
raise ValueError(f'Edited file too large ({encoded_len:,} bytes; max {_MAX_FILE_SIZE_BYTES:,}).')

encoded_len = len(content.encode('utf-8'))
if encoded_len > _MAX_FILE_SIZE_BYTES:
raise ValueError(f'Edited file too large ({encoded_len:,} bytes; max {_MAX_FILE_SIZE_BYTES:,}).')

with open(abs_path, 'w', encoding='utf-8') as fh:
fh.write(content)
Expand Down Expand Up @@ -363,13 +454,16 @@ async def wrap_tool(
ctx: MiddlewareContext,
next_fn: Callable[[ToolHookParams, MiddlewareContext], Awaitable[MultipartToolResponse]],
) -> MultipartToolResponse:
"""Catch filesystem tool errors and enqueue them as user messages."""
"""Return filesystem tool errors as the tool response, host paths redacted.

The error stays in the tool turn, as in JS. Queueing it as a user
message put a user turn between the tool response and the next model
turn, and carried the absolute host root into the conversation.
"""
if params.tool.name not in self._filesystem_tool_names():
return await next_fn(params, ctx)

try:
return await next_fn(params, ctx)
except Exception as exc:
error_msg = f'Tool "{params.tool.name}" failed: {exc}'
self._enqueue_parts([Part.from_text(error_msg)])
return MultipartToolResponse(output='Tool call failed; see user message below for details.')
return MultipartToolResponse(output=f'Tool "{params.tool.name}" failed: {self._redact(str(exc))}')
Loading
Loading