feat: запись, правка и поиск файлов, json_query

- write_file: атомарная запись (temp + rename), лимит 1 МБ,
  create_dirs по требованию, только внутри песочницы
- replace_in_file: требует ровно одного совпадения search,
  all:true для осознанной массовой замены
- search_files: regex по содержимому, 'путь:строка: текст',
  пропускает .git/vendor/node_modules/var, бинарные и большие файлы
- find_files: маска по относительному пути или имени
- json_query: путь вида data.items[0].id
- FileSandbox: resolveForWrite и writeAtomic, запрет '..' на запись,
  подсказка в сообщении «путь не найден»
- 88 тестов
This commit is contained in:
rsgrinko committed 2026-11-12 19:12:08 +03:00
1 parent cf627b8ce5
commit 72883fbc53
8 files changed
+1117 -38

No files matched your search

+128 -26
View File
@@ -7,9 +7,8 @@ namespace AiSdk\Tools;
/**
* Ограничитель файловых инструментов: любой путь обязан лежать внутри корня.
*
* Никакой «магии»: относительный путь склеивается с корнем, приводится к
* реальному виду (realpath) и проверяется по префиксу. Всё, что выходит
* наружу — «..», абсолютные пути, симлинки за пределы каталога — отвергается.
* Чтение проверяется через realpath, запись — через realpath каталога:
* иначе «..» и симлинки уводили бы за пределы корня.
*/
final class FileSandbox
{
@@ -32,44 +31,112 @@ final class FileSandbox
}
/**
* Привести относительный путь к абсолютному внутри корня.
* Абсолютный путь к существующему файлу или каталогу.
*
* @throws \RuntimeException если путь вне корня или (для чтения) не найден
* @throws \RuntimeException если путь вне корня или не найден
*/
public function resolve(string $path, bool $mustExist = true): string
public function resolve(string $path): string
{
$path = trim($path);
$relative = $this->normalize($path);
if ($path === '' || $path === '.') {
if ($relative === '') {
return $this->root;
}
if (str_contains($path, "\0")) {
throw new \RuntimeException('Некорректный путь.');
}
if (str_starts_with($path, '/') || preg_match('/^[A-Za-z]:[\\\\\/]/', $path) === 1) {
throw new \RuntimeException('Абсолютные пути запрещены: указывайте путь относительно корня.');
}
$candidate = $this->root . DIRECTORY_SEPARATOR . $path;
$real = realpath($candidate);
$real = realpath($this->root . DIRECTORY_SEPARATOR . $relative);
if ($real === false) {
if ($mustExist) {
throw new \RuntimeException('Путь не найден: ' . $path);
}
return $candidate;
throw new \RuntimeException(
'Путь не найден: ' . $path . '. Нужен путь к файлу относительно корня, например src/app.php.'
);
}
if ($real !== $this->root && !$this->startsWithRoot($real)) {
throw new \RuntimeException('Путь выходит за пределы разрешённого каталога.');
}
$this->assertInside($real);
return $real;
}
/**
* Абсолютный путь для записи. Каталог должен существовать (если не передан
* createDirs), сам файл — нет.
*
* @throws \RuntimeException
*/
public function resolveForWrite(string $path, bool $createDirs = false): string
{
$relative = $this->normalize($path);
if ($relative === '') {
throw new \RuntimeException('Не указан путь к файлу.');
}
$directory = dirname($relative);
$name = basename($relative);
if ($name === '' || $name === '.' || $name === '..') {
throw new \RuntimeException('Некорректное имя файла.');
}
$directoryPath = $directory === '.' || $directory === ''
? $this->root
: $this->root . DIRECTORY_SEPARATOR . $directory;
if (!is_dir($directoryPath)) {
if (!$createDirs) {
throw new \RuntimeException('Каталог не существует: ' . $directory);
}
if (!@mkdir($directoryPath, 0777, true) && !is_dir($directoryPath)) {
throw new \RuntimeException('Не удалось создать каталог: ' . $directory);
}
}
$realDirectory = realpath($directoryPath);
if ($realDirectory === false) {
throw new \RuntimeException('Каталог недоступен: ' . $directory);
}
$this->assertInside($realDirectory);
return $realDirectory . DIRECTORY_SEPARATOR . $name;
}
/**
* Атомарная запись: сначала во временный файл рядом, потом rename.
* Так при сбое не остаётся полузаписанный файл.
*/
public function writeAtomic(string $absolute, string $content): void
{
$directory = dirname($absolute);
$temporary = @tempnam($directory, '.aisdk_');
if ($temporary === false) {
throw new \RuntimeException('Не удалось создать временный файл в ' . $directory);
}
$written = @file_put_contents($temporary, $content);
if ($written === false) {
@unlink($temporary);
throw new \RuntimeException('Не удалось записать файл.');
}
@chmod($temporary, 0644);
// На Windows rename не перезаписывает существующий файл.
if (is_file($absolute) && DIRECTORY_SEPARATOR === '\\') {
@unlink($absolute);
}
if (!@rename($temporary, $absolute)) {
@unlink($temporary);
throw new \RuntimeException('Не удалось переименовать временный файл.');
}
}
/**
* Путь для показа пользователю (относительно корня).
*/
@@ -88,6 +155,41 @@ final class FileSandbox
return $absolute;
}
/**
* Относительный путь без «..», абсолютных путей и нулевых байтов.
*/
private function normalize(string $path): string
{
$path = trim(str_replace('\\', '/', $path));
if ($path === '' || $path === '.') {
return '';
}
if (str_contains($path, "\0")) {
throw new \RuntimeException('Некорректный путь.');
}
if (str_starts_with($path, '/') || preg_match('/^[A-Za-z]:[\\\\\/]/', $path) === 1) {
throw new \RuntimeException('Абсолютные пути запрещены: указывайте путь относительно корня.');
}
$path = preg_replace('#/+#', '/', $path) ?? $path;
if (preg_match('#(^|/)\.\.(/|$)#', $path) === 1) {
throw new \RuntimeException('Путь не должен содержать "..".');
}
return trim($path, '/');
}
private function assertInside(string $real): void
{
if ($real !== $this->root && !$this->startsWithRoot($real)) {
throw new \RuntimeException('Путь выходит за пределы разрешённого каталога.');
}
}
private function startsWithRoot(string $path): bool
{
$prefix = $this->root . DIRECTORY_SEPARATOR;
+153
View File
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Поиск файлов по маске имени внутри песочницы.
*/
final class FindFilesTool implements Tool
{
private const IGNORED = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var'];
public function __construct(
private readonly FileSandbox $sandbox,
private readonly int $defaultLimit = 100,
) {
}
public function name(): string
{
return 'find_files';
}
public function description(): string
{
return 'Найти файлы по маске имени: "*.php", "**/*.md", "Config*". '
. 'Можно ограничить подкаталог. Возвращает пути и размеры.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'pattern' => [
'type' => 'string',
'description' => 'Маска, например *.php или src/**/*.php.',
],
'path' => [
'type' => 'string',
'description' => 'Подкаталог для поиска. По умолчанию весь корень.',
],
'limit' => [
'type' => 'integer',
'description' => 'Сколько путей вернуть, по умолчанию ' . $this->defaultLimit . ', максимум 500.',
],
],
'required' => ['pattern'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$pattern = trim((string) ($args['pattern'] ?? ''));
if ($pattern === '') {
return 'Пустая маска.';
}
$limit = (int) ($args['limit'] ?? $this->defaultLimit);
$limit = max(1, min($limit, 500));
try {
$start = $this->sandbox->resolve((string) ($args['path'] ?? ''));
} catch (\RuntimeException $e) {
return $e->getMessage();
}
if (!is_dir($start)) {
return 'Это не каталог: ' . (string) ($args['path'] ?? '');
}
$found = [];
$truncated = false;
try {
$this->eachEntry($start, function (string $path) use (&$found, $pattern, $limit): void {
$relative = $this->sandbox->relative($path);
if (!fnmatch($pattern, $relative) && !fnmatch($pattern, basename($path))) {
return;
}
$size = @filesize($path);
$found[] = $relative . ' (' . $this->human($size === false ? 0 : $size) . ')';
if (count($found) >= $limit) {
throw new \RuntimeException('__limit__');
}
});
} catch (\RuntimeException $e) {
if ($e->getMessage() !== '__limit__') {
return 'Ошибка поиска: ' . $e->getMessage();
}
$truncated = true;
}
if ($found === []) {
return 'Файлы не найдены по маске "' . $pattern . '".';
}
return 'Найдено ' . count($found) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n"
. implode("\n", $found);
}
/**
* @param callable(string): void $onFile
*/
private function eachEntry(string $directory, callable $onFile): void
{
$entries = @scandir($directory);
if ($entries === false) {
return;
}
foreach ($entries as $name) {
if ($name === '.' || $name === '..' || in_array($name, self::IGNORED, true)) {
continue;
}
$path = $directory . DIRECTORY_SEPARATOR . $name;
if (is_dir($path)) {
$this->eachEntry($path, $onFile);
continue;
}
if (is_file($path)) {
$onFile($path);
}
}
}
private function human(int $bytes): string
{
if ($bytes >= 1048576) {
return round($bytes / 1048576, 1) . ' МБ';
}
if ($bytes >= 1024) {
return round($bytes / 1024, 1) . ' КБ';
}
return $bytes . ' Б';
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Достать значение из JSON по простому пути: data.items[0].id
*/
final class JsonQueryTool implements Tool
{
private const MAX_OUTPUT = 2000;
public function name(): string
{
return 'json_query';
}
public function description(): string
{
return 'Достать значение из JSON-строки по пути вида data.items[0].id '
. '(точки для ключей, [n] для массивов). Удобно, когда ответ API большой и обрезан.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'json' => ['type' => 'string', 'description' => 'JSON-текст целиком.'],
'path' => ['type' => 'string', 'description' => 'Путь, например data.items[0].id.'],
],
'required' => ['json', 'path'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$json = (string) ($args['json'] ?? '');
$path = trim((string) ($args['path'] ?? ''));
if (trim($json) === '') {
return 'Пустой JSON.';
}
if ($path === '') {
return 'Пустой path.';
}
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return 'Некорректный JSON: ' . json_last_error_msg();
}
try {
$tokens = $this->tokenize($path);
} catch (\InvalidArgumentException $e) {
return $e->getMessage();
}
$current = $data;
$passed = [];
foreach ($tokens as $token) {
if (!is_array($current)) {
return 'Путь ' . $path . ' не найден: на шаге "' . implode('.', $passed)
. '" значение не является объектом или массивом.';
}
if (array_key_exists($token, $current)) {
$current = $current[$token];
$passed[] = $token;
continue;
}
if (ctype_digit($token) && array_key_exists((int) $token, $current)) {
$current = $current[(int) $token];
$passed[] = $token;
continue;
}
return 'Путь ' . $path . ' не найден: нет ключа "' . $token . '".';
}
if (is_scalar($current) || $current === null) {
return $path . ' = ' . var_export($current, true);
}
$encoded = json_encode($current, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($encoded === false) {
return 'Значение не удалось сериализовать.';
}
$cut = mb_strlen($encoded) > self::MAX_OUTPUT;
return $path . ' = ' . mb_substr($encoded, 0, self::MAX_OUTPUT) . ($cut ? '…' : '');
}
/**
* data.items[0].id -> ['data','items','0','id']
*
* @return list<string>
*/
private function tokenize(string $path): array
{
$path = trim($path);
$path = preg_replace('/^\$?\.?/', '', $path) ?? $path;
$tokens = [];
$buffer = '';
$length = strlen($path);
for ($i = 0; $i < $length; $i++) {
$char = $path[$i];
if ($char === '.') {
if ($buffer !== '') {
$tokens[] = $buffer;
$buffer = '';
}
continue;
}
if ($char === '[') {
if ($buffer !== '') {
$tokens[] = $buffer;
$buffer = '';
}
$end = strpos($path, ']', $i);
if ($end === false) {
throw new \InvalidArgumentException('Не закрыта квадратная скобка в path.');
}
$tokens[] = substr($path, $i + 1, $end - $i - 1);
$i = $end;
continue;
}
$buffer .= $char;
}
if ($buffer !== '') {
$tokens[] = $buffer;
}
if ($tokens === []) {
throw new \InvalidArgumentException('Пустой path.');
}
return $tokens;
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Точечная замена в файле: старый фрагмент -> новый.
*
* По умолчанию требует ровно одного совпадения: так модель не испортит файл,
* заменив не тот кусок. Если совпадений несколько и это осознанно — all: true.
*/
final class ReplaceInFileTool implements Tool
{
public function __construct(private readonly FileSandbox $sandbox)
{
}
public function name(): string
{
return 'replace_in_file';
}
public function description(): string
{
return 'Заменить фрагмент текста в файле. Нужно ровно одно совпадение search, '
. 'иначе замена не выполняется (если совпадений несколько — all: true). '
. 'Пиши search вместе с отступами и соседними строками, чтобы попасть в нужное место.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'path' => ['type' => 'string', 'description' => 'Путь файла относительно корня.'],
'search' => ['type' => 'string', 'description' => 'Что заменить: точный фрагмент.'],
'replace' => ['type' => 'string', 'description' => 'На что заменить.'],
'all' => [
'type' => 'boolean',
'description' => 'Заменить все совпадения. По умолчанию false.',
],
],
'required' => ['path', 'search', 'replace'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$path = trim((string) ($args['path'] ?? ''));
$search = (string) ($args['search'] ?? '');
$replace = (string) ($args['replace'] ?? '');
$all = (bool) ($args['all'] ?? false);
if ($path === '') {
return 'Не указан путь файла.';
}
if ($search === '') {
return 'Пустой search: нечего заменять.';
}
try {
$file = $this->sandbox->resolve($path);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
if (!is_file($file)) {
return 'Это не файл: ' . $path;
}
$content = @file_get_contents($file);
if ($content === false) {
return 'Не удалось прочитать файл.';
}
$count = substr_count($content, $search);
if ($count === 0) {
return 'Фрагмент не найден в ' . $path . '. Проверь отступы и текст.';
}
if ($count > 1 && !$all) {
return 'Найдено совпадений: ' . $count . '. Уточни search или передай all: true.';
}
$updated = $all
? str_replace($search, $replace, $content)
: $this->replaceOnce($content, $search, $replace);
try {
$this->sandbox->writeAtomic($file, $updated);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
return 'Заменено вхождений: ' . ($all ? $count : 1)
. ', файл ' . $this->sandbox->relative($file)
. ': ' . strlen($updated) . ' Б.';
}
/**
* Заменить только первое вхождение, не трогая остальные.
*/
private function replaceOnce(string $content, string $search, string $replace): string
{
$position = strpos($content, $search);
if ($position === false) {
return $content;
}
return substr_replace($content, $replace, $position, strlen($search));
}
}
+221
View File
@@ -0,0 +1,221 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Поиск по содержимому файлов внутри песочницы (аналог grep).
*
* Только чтение. Служебные каталоги пропускаются, большие и бинарные файлы
* не сканируются.
*/
final class SearchFilesTool implements Tool
{
private const IGNORED = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var'];
private const MAX_FILE = 1048576;
private const MAX_LINE = 200;
public function __construct(
private readonly FileSandbox $sandbox,
private readonly int $defaultLimit = 50,
) {
}
public function name(): string
{
return 'search_files';
}
public function description(): string
{
return 'Найти строки по регулярному выражению в файлах проекта. '
. 'Возвращает "путь:строка: текст". Можно ограничить подкаталог и маску файлов.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'pattern' => [
'type' => 'string',
'description' => 'Регулярное выражение, например "class Kernel" или "TODO|FIXME".',
],
'path' => [
'type' => 'string',
'description' => 'Подкаталог для поиска. По умолчанию весь корень.',
],
'glob' => [
'type' => 'string',
'description' => 'Маска файлов, например *.php. По умолчанию все.',
],
'limit' => [
'type' => 'integer',
'description' => 'Сколько совпадений вернуть, по умолчанию ' . $this->defaultLimit . ', максимум 200.',
],
'ignore_case' => [
'type' => 'boolean',
'description' => 'Игнорировать регистр. По умолчанию false.',
],
],
'required' => ['pattern'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$pattern = trim((string) ($args['pattern'] ?? ''));
if ($pattern === '') {
return 'Пустой pattern.';
}
$limit = (int) ($args['limit'] ?? $this->defaultLimit);
$limit = max(1, min($limit, 200));
$glob = trim((string) ($args['glob'] ?? ''));
$glob = $glob !== '' ? $glob : '*';
$ignoreCase = (bool) ($args['ignore_case'] ?? false);
$regex = $this->compile($pattern, $ignoreCase);
if ($regex === null) {
return 'Некорректное регулярное выражение: ' . $pattern;
}
try {
$start = $this->sandbox->resolve((string) ($args['path'] ?? ''));
} catch (\RuntimeException $e) {
return $e->getMessage();
}
if (!is_dir($start)) {
return 'Это не каталог: ' . (string) ($args['path'] ?? '');
}
$results = [];
$truncated = false;
try {
$this->eachFile($start, function (string $file) use (&$results, $regex, $glob, $limit): void {
$relative = $this->sandbox->relative($file);
if (!fnmatch($glob, $relative) && !fnmatch($glob, basename($file))) {
return;
}
foreach ($this->matchLines($file, $regex) as $line) {
$results[] = $relative . ':' . $line;
if (count($results) >= $limit) {
throw new \RuntimeException('__limit__');
}
}
});
} catch (\RuntimeException $e) {
if ($e->getMessage() !== '__limit__') {
return 'Ошибка поиска: ' . $e->getMessage();
}
$truncated = true;
}
if ($results === []) {
return 'Ничего не найдено по "' . $pattern . '".';
}
return 'Найдено ' . count($results) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n"
. implode("\n", $results);
}
private function compile(string $pattern, bool $ignoreCase): ?string
{
$delimiter = '~';
$escaped = str_replace($delimiter, '\\' . $delimiter, $pattern);
$regex = $delimiter . $escaped . $delimiter . 'u' . ($ignoreCase ? 'i' : '');
return @preg_match($regex, '') === false ? null : $regex;
}
/**
* @return list<string> строки вида "12: текст"
*/
private function matchLines(string $file, string $regex): array
{
$size = @filesize($file);
if ($size === false || $size > self::MAX_FILE) {
return [];
}
$handle = @fopen($file, 'rb');
if ($handle === false) {
return [];
}
$head = (string) fread($handle, 4096);
fclose($handle);
if ($head !== '' && !mb_check_encoding($head, 'UTF-8')) {
return [];
}
$lines = @file($file, FILE_IGNORE_NEW_LINES);
if ($lines === false) {
return [];
}
$matches = [];
foreach ($lines as $index => $line) {
if (@preg_match($regex, $line) !== 1) {
continue;
}
$text = trim($line);
if (mb_strlen($text) > self::MAX_LINE) {
$text = mb_substr($text, 0, self::MAX_LINE) . '…';
}
$matches[] = ($index + 1) . ': ' . $text;
}
return $matches;
}
/**
* @param callable(string): void $onFile
*/
private function eachFile(string $directory, callable $onFile): void
{
$entries = @scandir($directory);
if ($entries === false) {
return;
}
foreach ($entries as $name) {
if ($name === '.' || $name === '..' || in_array($name, self::IGNORED, true)) {
continue;
}
$path = $directory . DIRECTORY_SEPARATOR . $name;
if (is_dir($path)) {
$this->eachFile($path, $onFile);
continue;
}
if (is_file($path)) {
$onFile($path);
}
}
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Создание и перезапись файла внутри песочницы.
*
* Пишет целиком и атомарно. Для точечной правки лучше replace_in_file.
*/
final class WriteFileTool implements Tool
{
private const MAX_BYTES = 1048576;
public function __construct(private readonly FileSandbox $sandbox)
{
}
public function name(): string
{
return 'write_file';
}
public function description(): string
{
return 'Создать или перезаписать файл целиком (до 1 МБ). '
. 'Путь относительно корня проекта. '
. 'Для изменения одной строки используй replace_in_file, а не перезапись.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'path' => [
'type' => 'string',
'description' => 'Путь файла относительно корня, например src/Config.php.',
],
'content' => [
'type' => 'string',
'description' => 'Полное содержимое файла.',
],
'create_dirs' => [
'type' => 'boolean',
'description' => 'Создать недостающие каталоги. По умолчанию false.',
],
],
'required' => ['path', 'content'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$path = trim((string) ($args['path'] ?? ''));
$content = (string) ($args['content'] ?? '');
$createDirs = (bool) ($args['create_dirs'] ?? false);
if ($path === '') {
return 'Не указан путь файла.';
}
if (strlen($content) > self::MAX_BYTES) {
return 'Содержимое больше 1 МБ — запиши файл частями или сократи.';
}
try {
$target = $this->sandbox->resolveForWrite($path, $createDirs);
if (is_dir($target)) {
return 'Это каталог, а не файл: ' . $path;
}
$existed = is_file($target);
$this->sandbox->writeAtomic($target, $content);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
return ($existed ? 'Перезаписан' : 'Создан')
. ' файл ' . $this->sandbox->relative($target)
. ': ' . strlen($content) . ' Б.';
}
}