diff --git a/README.md b/README.md index 4f6ee6b..010ab3b 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,9 @@ echo $agent->ask('Который час в Москве и сколько буд - **`Tool` + `ToolRegistry`** — инструмент = 4 метода; реестр сам отдаёт схемы модели и вызывает нужный инструмент. - **`ChatClient`** — интерфейс, чтобы подменить модель заглушкой в тестах. -- **13 готовых инструментов**: время, калькулятор, погода, файлы, CSV, HTTP, - единицы, даты, UUID, хеши, явное завершение и команды оболочки — - см. [таблицу](#инструменты). +- **18 готовых инструментов**: время, калькулятор, погода, файлы (чтение, + запись, поиск), CSV, HTTP, единицы, даты, UUID, хеши, JSON, явное завершение + и команды оболочки — см. [таблицу](#инструменты). Без Composer, без фреймворка, без БД. Только PHP и расширение `curl`. @@ -70,8 +70,13 @@ tools/ FinishTool.php явное завершение работы с результатом FileSandbox.php ограничитель путей (общий для файловых инструментов) ReadFileTool.php чтение файла внутри корня + WriteFileTool.php запись файла (атомарно) + ReplaceInFileTool.php точечная замена фрагмента + SearchFilesTool.php поиск по содержимому + FindFilesTool.php поиск файлов по маске ListDirTool.php список каталога внутри корня CsvQueryTool.php выборка из CSV с фильтром + JsonQueryTool.php значение по пути из JSON HttpRequestTool.php HTTP любого метода с авторизацией ShellTool.php команды оболочки (опасно) ConvertUnitsTool.php температура, длина, масса, скорость @@ -164,8 +169,13 @@ $agent = Agent::fromEnv($tools, 'Отвечай кратко.'); | `calculator` | арифметика без `eval()` | — | | `get_weather` | погода (open-meteo, без ключа) | — | | `read_file` | чтение файла внутри корня | `new ReadFileTool($sandbox)` | +| `write_file` | создать/перезаписать файл | `new WriteFileTool($sandbox)` | +| `replace_in_file` | точечная замена фрагмента | `new ReplaceInFileTool($sandbox)` | +| `search_files` | поиск по содержимому (grep) | `new SearchFilesTool($sandbox)` | +| `find_files` | поиск файлов по маске | `new FindFilesTool($sandbox)` | | `list_dir` | содержимое каталога | `new ListDirTool($sandbox)` | | `csv_query` | выборка из CSV с фильтром | `new CsvQueryTool($sandbox)` | +| `json_query` | значение по пути из JSON | — | | `http_request` | любой метод, тело, Basic/Bearer | — | | `convert_units` | температура, длина, масса, скорость | — | | `date_calc` | разница дат, «+30 days» | — | @@ -181,14 +191,37 @@ $sandbox = new FileSandbox(__DIR__ . '/data'); $tools = (new ToolRegistry())->add( new ReadFileTool($sandbox), + new WriteFileTool($sandbox), + new ReplaceInFileTool($sandbox), + new SearchFilesTool($sandbox), + new FindFilesTool($sandbox), new ListDirTool($sandbox), new CsvQueryTool($sandbox), ); ``` - всё вне корня отвергается: `..`, абсолютные пути, симлинки наружу; -- бинарные файлы не читаются, сообщается размер; -- большие файлы — через `offset` и `limit` в строках. +- запись атомарная: временный файл рядом и `rename`, полузаписанных файлов нет; +- `replace_in_file` требует **ровно одного** совпадения `search` — чтобы модель + не заменила не тот кусок; для осознанной массовой замены есть `all: true`; +- поиск пропускает `.git`, `vendor`, `node_modules`, `var` и не читает бинарные + файлы и файлы больше 1 МБ; +- большие файлы читаются через `offset` и `limit` в строках. + +Запись — единственная деструктивная операция среди файловых инструментов. +Перед регистрацией `write_file`/`replace_in_file` стоит подумать о +`toolApproval`: хук может спросить человека или запретить запись вне нужных +каталогов. + +`json_query` достаёт значение по простому пути — удобно после `http_request`, +когда ответ большой: + +```php +(new JsonQueryTool())->handle([ + 'json' => '{"data":{"items":[{"id":42}]}}', + 'path' => 'data.items[0].id', +]); // data.items[0].id = 42 +``` `http_request` — любой метод с параметрами и авторизацией: @@ -417,11 +450,11 @@ curl http://10.10.10.77:8080/v1/models php tests/run.php ``` -72 проверки: калькулятор, время, реестр, обрезка результатов, весь цикл агента, -настройки (tool_choice, подтверждение вызовов, история), finish, файловая -песочница, CSV, единицы, даты, uuid/хеши, сборка HTTP-запроса (методы, тело, -заголовки, Basic/Bearer), защита от SSRF и run_command (код выхода, таймаут, -allowlist, обрезка) +88 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, +настройки (tool_choice, подтверждение вызовов, история), finish, файлы +(чтение, запись, замена, поиск, побег из песочницы), CSV, единицы, даты, +uuid/хеши, сборка HTTP-запроса (методы, тело, заголовки, Basic/Bearer), +защита от SSRF, run_command (код выхода, таймаут, allowlist, обрезка) (успех, ошибка инструмента, лимит раундов, история). Сеть не нужна — модель подменяется `FakeClient` из `tests/run.php`. diff --git a/tests/run.php b/tests/run.php index 37b7799..afa0b33 100644 --- a/tests/run.php +++ b/tests/run.php @@ -26,13 +26,18 @@ use AiSdk\Tools\ConvertUnitsTool; use AiSdk\Tools\CsvQueryTool; use AiSdk\Tools\DateCalcTool; use AiSdk\Tools\FileSandbox; +use AiSdk\Tools\FindFilesTool; +use AiSdk\Tools\JsonQueryTool; use AiSdk\Tools\FinishTool; use AiSdk\Tools\HashTool; use AiSdk\Tools\HttpRequestTool; use AiSdk\Tools\ListDirTool; use AiSdk\Tools\ReadFileTool; +use AiSdk\Tools\ReplaceInFileTool; +use AiSdk\Tools\SearchFilesTool; use AiSdk\Tools\ShellTool; use AiSdk\Tools\TimeTool; +use AiSdk\Tools\WriteFileTool; use AiSdk\Tools\UuidTool; mb_internal_encoding('UTF-8'); @@ -742,7 +747,7 @@ test('read_file: побег через .. запрещён', function (): void { $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '../outside.txt']); - assertContains('выходит за пределы', $result); + assertContains('не должен содержать', $result); }); test('read_file: абсолютный путь запрещён', function (): void { @@ -778,7 +783,7 @@ test('list_dir: выход за корень запрещён', function (): voi $result = (new ListDirTool(new FileSandbox($dir)))->handle(['path' => '..']); - assertContains('выходит за пределы', $result); + assertContains('не должен содержать', $result); }); // --------------------------------------------------------------------------- @@ -1028,6 +1033,198 @@ test('http_request: allowPrivate снимает блокировку внутр ); }); +// --------------------------------------------------------------------------- +// Запись и правка файлов +// --------------------------------------------------------------------------- + +test('write_file: создаёт файл', function (): void { + $dir = testDir(); + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'note.txt', + 'content' => 'привет', + ]); + + assertContains('Создан', $result); + assertSame('привет', file_get_contents($dir . '/note.txt')); +}); + +test('write_file: перезаписывает файл', function (): void { + $dir = testDir(); + file_put_contents($dir . '/note.txt', 'старое'); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'note.txt', + 'content' => 'новое', + ]); + + assertContains('Перезаписан', $result); + assertSame('новое', file_get_contents($dir . '/note.txt')); +}); + +test('write_file: создаёт каталоги с create_dirs', function (): void { + $dir = testDir(); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'a/b/c.txt', + 'content' => 'x', + 'create_dirs' => true, + ]); + + assertContains('Создан', $result); + assertTrue(is_file($dir . '/a/b/c.txt'), 'файл не создан'); +}); + +test('write_file: без create_dirs каталог обязателен', function (): void { + $dir = testDir(); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'nope/x.txt', + 'content' => 'x', + ]); + + assertContains('Каталог не существует', $result); +}); + +test('write_file: запись вне песочницы запрещена', function (): void { + $dir = testDir(); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => '../evil.txt', + 'content' => 'x', + ]); + + assertContains('не должен содержать', $result); +}); + +test('replace_in_file: заменяет единственное совпадение', function (): void { + $dir = testDir(); + file_put_contents($dir . '/code.txt', "class A\nclass B\n"); + + $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'code.txt', + 'search' => 'class A', + 'replace' => 'final class A', + ]); + + assertContains('Заменено вхождений: 1', $result); + + $content = (string) file_get_contents($dir . '/code.txt'); + + assertContains('final class A', $content); + assertContains('class B', $content); +}); + +test('replace_in_file: несколько совпадений требуют all', function (): void { + $dir = testDir(); + file_put_contents($dir . '/code.txt', "x\nx\n"); + + $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'code.txt', + 'search' => 'x', + 'replace' => 'y', + ]); + + assertContains('Найдено совпадений: 2', $result); +}); + +test('replace_in_file: не найдено — понятная ошибка', function (): void { + $dir = testDir(); + file_put_contents($dir . '/code.txt', 'abc'); + + $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'code.txt', + 'search' => 'zzz', + 'replace' => 'y', + ]); + + assertContains('не найден', $result); +}); + +// --------------------------------------------------------------------------- +// Поиск по файлам +// --------------------------------------------------------------------------- + +test('search_files: находит строки с номерами', function (): void { + $dir = testDir(); + file_put_contents($dir . '/a.php', "handle(['pattern' => 'class \w+']); + + assertContains('a.php:2:', $result); + assertContains('b.txt:1:', $result); +}); + +test('search_files: glob ограничивает файлы', function (): void { + $dir = testDir(); + file_put_contents($dir . '/a.php', "class Foo\n"); + file_put_contents($dir . '/b.txt', "class Bar\n"); + + $result = (new SearchFilesTool(new FileSandbox($dir)))->handle([ + 'pattern' => 'class', + 'glob' => '*.php', + ]); + + assertContains('a.php', $result); + assertTrue(!str_contains($result, 'b.txt'), 'лишний файл в выдаче'); +}); + +test('search_files: служебные каталоги пропускаются', function (): void { + $dir = testDir(); + mkdir($dir . '/vendor', 0777, true); + file_put_contents($dir . '/vendor/lib.php', "class Vendor\n"); + file_put_contents($dir . '/app.php', "class App\n"); + + $result = (new SearchFilesTool(new FileSandbox($dir)))->handle(['pattern' => 'class']); + + assertContains('app.php', $result); + assertTrue(!str_contains($result, 'vendor'), 'vendor не должен сканироваться'); +}); + +test('search_files: некорректная регулярка', function (): void { + $dir = testDir(); + + $result = (new SearchFilesTool(new FileSandbox($dir)))->handle(['pattern' => '([']); + + assertContains('Некорректное регулярное выражение', $result); +}); + +test('find_files: поиск по маске', function (): void { + $dir = testDir(); + file_put_contents($dir . '/a.php', 'x'); + file_put_contents($dir . '/b.txt', 'x'); + + $result = (new FindFilesTool(new FileSandbox($dir)))->handle(['pattern' => '*.php']); + + assertContains('a.php', $result); + assertTrue(!str_contains($result, 'b.txt'), 'лишний файл в выдаче'); +}); + +// --------------------------------------------------------------------------- +// JSON +// --------------------------------------------------------------------------- + +test('json_query: вложенный путь', function (): void { + $result = (new JsonQueryTool())->handle([ + 'json' => '{"data":{"items":[{"id":42,"name":"x"}]}}', + 'path' => 'data.items[0].id', + ]); + + assertContains('42', $result); +}); + +test('json_query: нет ключа — сообщение', function (): void { + $result = (new JsonQueryTool())->handle(['json' => '{"a":1}', 'path' => 'b']); + + assertContains('не найден', $result); +}); + +test('json_query: битый JSON', function (): void { + $result = (new JsonQueryTool())->handle(['json' => '{oops', 'path' => 'a']); + + assertContains('Некорректный JSON', $result); +}); + // --------------------------------------------------------------------------- // run_command: оболочка // --------------------------------------------------------------------------- @@ -1084,3 +1281,5 @@ echo PHP_EOL . 'пройдено: ' . $passed . ', провалено: ' . $fail exit($failed === 0 ? 0 : 1); + + diff --git a/tools/FileSandbox.php b/tools/FileSandbox.php index 091146c..f1a5253 100644 --- a/tools/FileSandbox.php +++ b/tools/FileSandbox.php @@ -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; diff --git a/tools/FindFilesTool.php b/tools/FindFilesTool.php new file mode 100644 index 0000000..ac431a7 --- /dev/null +++ b/tools/FindFilesTool.php @@ -0,0 +1,153 @@ + '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 . ' Б'; + } +} diff --git a/tools/JsonQueryTool.php b/tools/JsonQueryTool.php new file mode 100644 index 0000000..2983e2b --- /dev/null +++ b/tools/JsonQueryTool.php @@ -0,0 +1,163 @@ + '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 + */ + 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; + } +} diff --git a/tools/ReplaceInFileTool.php b/tools/ReplaceInFileTool.php new file mode 100644 index 0000000..0bcdac9 --- /dev/null +++ b/tools/ReplaceInFileTool.php @@ -0,0 +1,120 @@ + новый. + * + * По умолчанию требует ровно одного совпадения: так модель не испортит файл, + * заменив не тот кусок. Если совпадений несколько и это осознанно — 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)); + } +} diff --git a/tools/SearchFilesTool.php b/tools/SearchFilesTool.php new file mode 100644 index 0000000..232df47 --- /dev/null +++ b/tools/SearchFilesTool.php @@ -0,0 +1,221 @@ + '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 строки вида "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); + } + } + } +} diff --git a/tools/WriteFileTool.php b/tools/WriteFileTool.php new file mode 100644 index 0000000..173663a --- /dev/null +++ b/tools/WriteFileTool.php @@ -0,0 +1,88 @@ + '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) . ' Б.'; + } +}