From 1dea787255aefec59435fefbb2af9b3d4c89cc10 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Thu, 12 Nov 2026 18:45:20 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2?= =?UTF-8?q?=D1=8B=D0=B5,=20=D1=81=D0=B5=D1=82=D0=B5=D0=B2=D1=8B=D0=B5=20?= =?UTF-8?q?=D0=B8=20=D0=BF=D1=80=D0=B8=D0=BA=D0=BB=D0=B0=D0=B4=D0=BD=D1=8B?= =?UTF-8?q?=D0=B5=20=D0=B8=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FileSandbox + read_file/list_dir: доступ только внутри заданного корня, отказ на .., абсолютные пути и симлинки наружу; бинарные файлы не читаются - csv_query: фильтр =/~ по колонке, выбор колонок, лимит строк - http_get: защита от SSRF (только публичные IP), проверка редиректов, лимит размера через write-callback - convert_units: температура, длина, масса, скорость + русские алиасы - date_calc: разница дат и прибавление интервала ('!' в формате, чтобы дата без времени была полуночью) - uuid и hash_text - Http: request() с лимитом размера и заголовком Location, get() поверх него - пример 07-tools.php, 55 тестов --- .gitignore | 1 + README.md | 62 +++++++- examples/07-tools.php | 44 ++++++ src/Http.php | 71 ++++++++-- tests/run.php | 284 +++++++++++++++++++++++++++++++++++++ tools/ConvertUnitsTool.php | 149 +++++++++++++++++++ tools/CsvQueryTool.php | 268 ++++++++++++++++++++++++++++++++++ tools/DateCalcTool.php | 142 +++++++++++++++++++ tools/FileSandbox.php | 100 +++++++++++++ tools/HashTool.php | 58 ++++++++ tools/HttpGetTool.php | 209 +++++++++++++++++++++++++++ tools/ListDirTool.php | 114 +++++++++++++++ tools/ReadFileTool.php | 144 +++++++++++++++++++ tools/UuidTool.php | 53 +++++++ 14 files changed, 1685 insertions(+), 14 deletions(-) create mode 100644 examples/07-tools.php create mode 100644 tools/ConvertUnitsTool.php create mode 100644 tools/CsvQueryTool.php create mode 100644 tools/DateCalcTool.php create mode 100644 tools/FileSandbox.php create mode 100644 tools/HashTool.php create mode 100644 tools/HttpGetTool.php create mode 100644 tools/ListDirTool.php create mode 100644 tools/ReadFileTool.php create mode 100644 tools/UuidTool.php diff --git a/.gitignore b/.gitignore index 4243cdf..0eba5c1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ .idea/ .vscode/ .DS_Store +tests/tmp/ diff --git a/README.md b/README.md index 9d04e0f..4d5bf6d 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,8 @@ echo $agent->ask('Который час в Москве и сколько буд - **`Tool` + `ToolRegistry`** — инструмент = 4 метода; реестр сам отдаёт схемы модели и вызывает нужный инструмент. - **`ChatClient`** — интерфейс, чтобы подменить модель заглушкой в тестах. -- **3 готовых инструмента**: `get_time`, `calculator`, `get_weather`. +- **11 готовых инструментов**: время, калькулятор, погода, файлы, CSV, HTTP, + единицы, даты, UUID, хеши и явное завершение — см. [таблицу](#инструменты). Без Composer, без фреймворка, без БД. Только PHP и расширение `curl`. @@ -65,6 +66,15 @@ tools/ CalculatorTool.php арифметика без eval() WeatherTool.php погода через open-meteo.com (без ключа) FinishTool.php явное завершение работы с результатом + FileSandbox.php ограничитель путей (общий для файловых инструментов) + ReadFileTool.php чтение файла внутри корня + ListDirTool.php список каталога внутри корня + CsvQueryTool.php выборка из CSV с фильтром + HttpGetTool.php GET с защитой от SSRF + ConvertUnitsTool.php температура, длина, масса, скорость + DateCalcTool.php разница дат и прибавление интервала + UuidTool.php UUID v4 + HashTool.php sha256/sha1/md5 examples/ 01-chat.php простой вопрос 02-tools.php агент с тремя инструментами @@ -72,6 +82,7 @@ examples/ 04-cli.php интерактивный чат в терминале 05-settings.php tool_choice, подтверждение вызовов, история 06-finish.php завершение через finish + 07-tools.php единицы, даты, uuid, хеш tests/run.php тесты без сети ``` @@ -141,6 +152,50 @@ $agent = new Agent( $agent = Agent::fromEnv($tools, 'Отвечай кратко.'); ``` +## Инструменты + +| Инструмент | Что делает | Как подключить | +|---|---|---| +| `get_time` | дата и время в часовом поясе | — | +| `calculator` | арифметика без `eval()` | — | +| `get_weather` | погода (open-meteo, без ключа) | — | +| `read_file` | чтение файла внутри корня | `new ReadFileTool($sandbox)` | +| `list_dir` | содержимое каталога | `new ListDirTool($sandbox)` | +| `csv_query` | выборка из CSV с фильтром | `new CsvQueryTool($sandbox)` | +| `http_get` | GET по публичному URL | — | +| `convert_units` | температура, длина, масса, скорость | — | +| `date_calc` | разница дат, «+30 days» | — | +| `uuid` | UUID v4 | — | +| `hash_text` | sha256 / sha1 / md5 | — | +| `finish` | завершение с результатом | `finishTool: 'finish'` | + +Файловые инструменты работают только внутри явно заданного корня: + +```php +$sandbox = new FileSandbox(__DIR__ . '/data'); + +$tools = (new ToolRegistry())->add( + new ReadFileTool($sandbox), + new ListDirTool($sandbox), + new CsvQueryTool($sandbox), +); +``` + +- всё вне корня отвергается: `..`, абсолютные пути, симлинки наружу; +- бинарные файлы не читаются, сообщается размер; +- большие файлы — через `offset` и `limit` в строках. + +`http_get` закрыт от SSRF: только `http`/`https`, только публичные адреса +(`localhost`, `10.x`, `172.16–31.x`, `192.168.x`, `169.254.x`, CGNAT запрещены), +редиректы проверяются заново на каждом шаге, размер ответа ограничен. + +`convert_units` отвечает каноническими кодами (`5 км` → `5 km`), понимает +и русские названия единиц. + +Чего здесь нет осознанно: `run_command` и `sql_query`. Если они нужны — +пишите свой инструмент с белым списком команд или read-only пользователем БД; +в ядре такие права «по умолчанию» не выдаются. + ## Свой инструмент Четыре метода. Всё. @@ -277,8 +332,9 @@ curl http://10.10.10.77:8080/v1/models php tests/run.php ``` -31 проверка: калькулятор, время, реестр, обрезка результатов, весь цикл агента, -настройки (tool_choice, подтверждение вызовов, история) и finish +55 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, +настройки (tool_choice, подтверждение вызовов, история), finish, файловая +песочница, CSV, единицы, даты, uuid/хеши и защита http_get от SSRF (успех, ошибка инструмента, лимит раундов, история). Сеть не нужна — модель подменяется `FakeClient` из `tests/run.php`. diff --git a/examples/07-tools.php b/examples/07-tools.php new file mode 100644 index 0000000..0df39b8 --- /dev/null +++ b/examples/07-tools.php @@ -0,0 +1,44 @@ +add( + new ConvertUnitsTool(), + new DateCalcTool(), + new UuidTool(), + new HashTool(), +); + +$agent = new Agent(AiClient::fromEnv(), $tools, 'Отвечай кратко, одной строкой на вопрос.', 4); + +$answer = $agent->ask( + 'Переведи 100 км в мили, посчитай сколько дней между 2026-01-01 и 2026-03-15 ' + . 'и сгенерируй один uuid.' +); + +echo $answer . PHP_EOL; + +foreach ($agent->trace() as $step) { + echo ' ' . $step['name'] . '(' . json_encode($step['arguments'], JSON_UNESCAPED_UNICODE) . ')' + . ' → ' . mb_substr($step['output'], 0, 100) . PHP_EOL; +} diff --git a/src/Http.php b/src/Http.php index 6ace22a..750d522 100644 --- a/src/Http.php +++ b/src/Http.php @@ -5,10 +5,11 @@ declare(strict_types=1); namespace AiSdk; /** - * Минимальный HTTP-клиент для инструментов: один GET, таймаут, проверка TLS. + * Минимальный HTTP-клиент без зависимостей. * - * POST не нужен — для инструментов хватает чтения. Если понадобится, - * добавьте рядом метод post() по образцу. + * get() — простой GET с редиректами (используется инструментами вроде погоды). + * request() — низкоуровневый вариант: без авто-редиректов, с лимитом размера + * и заголовком Location. На нём строится http_get с защитой от SSRF. */ final class Http { @@ -17,25 +18,66 @@ final class Http */ public static function get(string $url, float $timeout = 10.0): array { + $response = self::request($url, $timeout, true); + + return [$response['status'], $response['body']]; + } + + /** + * @param bool $follow следовать редиректам автоматически + * @param int $maxBytes предел тела ответа; больше — обрезаем и обрываем загрузку + * @return array{status: int, body: string, location: string|null, truncated: bool} + */ + public static function request( + string $url, + float $timeout = 10.0, + bool $follow = false, + int $maxBytes = 262144, + ): array { $ch = curl_init($url); if ($ch === false) { throw new AiException('не удалось создать cURL-дескриптор'); } - // Тот же флаг, что и у AiClient: AI_VERIFY_SSL / AI_CAINFO. + $body = ''; + $truncated = false; + $location = null; + $limit = max(1024, $maxBytes); + $verify = Env::bool('AI_VERIFY_SSL', true); $options = [ - CURLOPT_RETURNTRANSFER => true, + CURLOPT_RETURNTRANSFER => false, CURLOPT_TIMEOUT_MS => (int) round($timeout * 1000), CURLOPT_CONNECTTIMEOUT_MS => 5000, - CURLOPT_FOLLOWLOCATION => true, + CURLOPT_FOLLOWLOCATION => $follow, CURLOPT_MAXREDIRS => 3, CURLOPT_SSL_VERIFYPEER => $verify, CURLOPT_SSL_VERIFYHOST => $verify ? 2 : 0, CURLOPT_USERAGENT => 'ai-sdk/1.0 (+https://example.local)', - CURLOPT_HTTPHEADER => ['Accept: application/json'], + CURLOPT_HTTPHEADER => ['Accept: */*'], + CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$body, &$truncated, $limit): int { + $room = $limit - strlen($body); + + if (strlen($chunk) > $room) { + $body .= substr($chunk, 0, $room); + $truncated = true; + + return 0; // прерываем загрузку + } + + $body .= $chunk; + + return strlen($chunk); + }, + CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$location): int { + if (stripos($line, 'location:') === 0) { + $location = trim(substr($line, 9)); + } + + return strlen($line); + }, ]; $caInfo = Env::get('AI_CAINFO', '') ?? ''; @@ -46,15 +88,22 @@ final class Http curl_setopt_array($ch, $options); - $body = curl_exec($ch); + curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $errno = curl_errno($ch); $error = curl_error($ch); curl_close($ch); - if ($body === false) { - throw new AiException('HTTP-ошибка: ' . ($error !== '' ? $error : 'неизвестно')); + // 23 = CURLE_WRITE_ERROR: это мы сами оборвали слишком большой ответ. + if ($errno !== 0 && !($truncated && $errno === 23)) { + throw new AiException('HTTP-ошибка: ' . ($error !== '' ? $error : 'код ' . $errno)); } - return [$status, (string) $body]; + return [ + 'status' => $status, + 'body' => $body, + 'location' => $location, + 'truncated' => $truncated, + ]; } } diff --git a/tests/run.php b/tests/run.php index 1d9aadb..1553249 100644 --- a/tests/run.php +++ b/tests/run.php @@ -20,8 +20,17 @@ use AiSdk\ChatResult; use AiSdk\Tool; use AiSdk\ToolRegistry; use AiSdk\Tools\CalculatorTool; +use AiSdk\Tools\ConvertUnitsTool; +use AiSdk\Tools\CsvQueryTool; +use AiSdk\Tools\DateCalcTool; +use AiSdk\Tools\FileSandbox; use AiSdk\Tools\FinishTool; +use AiSdk\Tools\HashTool; +use AiSdk\Tools\HttpGetTool; +use AiSdk\Tools\ListDirTool; +use AiSdk\Tools\ReadFileTool; use AiSdk\Tools\TimeTool; +use AiSdk\Tools\UuidTool; mb_internal_encoding('UTF-8'); @@ -127,6 +136,51 @@ function textResult(string $text): ChatResult return new ChatResult($text, [], ['role' => 'assistant', 'content' => $text]); } +/** + * Временный каталог для файловых инструментов. + */ +function testDir(): string +{ + $base = __DIR__ . '/tmp'; + + if (!is_dir($base) && !mkdir($base, 0777, true) && !is_dir($base)) { + throw new RuntimeException('не удалось создать tests/tmp'); + } + + $dir = $base . '/sandbox-' . bin2hex(random_bytes(3)); + + if (!mkdir($dir, 0777, true)) { + throw new RuntimeException('не удалось создать ' . $dir); + } + + return $dir; +} + +function removeDir(string $dir): void +{ + if (!is_dir($dir)) { + return; + } + + $items = scandir($dir) ?: []; + + foreach ($items as $item) { + if ($item === '.' || $item === '..') { + continue; + } + + $path = $dir . '/' . $item; + + if (is_dir($path)) { + removeDir($path); + } else { + @unlink($path); + } + } + + @rmdir($dir); +} + /** * Ответ модели с несколькими вызовами сразу. * @@ -644,6 +698,236 @@ test('finish: можно отключить перехват через finishTo }); // --------------------------------------------------------------------------- +// Файлы +// --------------------------------------------------------------------------- + +test('read_file: читает файл внутри корня', function (): void { + $dir = testDir(); + file_put_contents($dir . '/note.txt', "первая\nвторая\nтретья"); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => 'note.txt']); + + assertContains('строки 1–3 из 3', $result); + assertContains('вторая', $result); +}); + +test('read_file: offset и limit в строках', function (): void { + $dir = testDir(); + file_put_contents($dir . '/note.txt', "1\n2\n3\n4\n5"); + + $result = (new ReadFileTool(new FileSandbox($dir))) + ->handle(['path' => 'note.txt', 'offset' => 1, 'limit' => 2]); + + assertContains('строки 2–3 из 5', $result); + assertContains("2\n3", $result); +}); + +test('read_file: побег через .. запрещён', function (): void { + $dir = testDir(); + file_put_contents(dirname($dir) . '/outside.txt', 'секрет'); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '../outside.txt']); + + assertContains('выходит за пределы', $result); +}); + +test('read_file: абсолютный путь запрещён', function (): void { + $dir = testDir(); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '/etc/passwd']); + + assertContains('Абсолютные пути запрещены', $result); +}); + +test('read_file: бинарный файл не читается', function (): void { + $dir = testDir(); + file_put_contents($dir . '/bin.dat', "\x00\x01\x02\xFF"); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => 'bin.dat']); + + assertContains('бинарный', $result); +}); + +test('list_dir: показывает каталоги и файлы', function (): void { + $dir = testDir(); + mkdir($dir . '/sub'); + file_put_contents($dir . '/a.txt', 'hello'); + + $result = (new ListDirTool(new FileSandbox($dir)))->handle([]); + + assertContains('sub/', $result); + assertContains('a.txt', $result); +}); + +test('list_dir: выход за корень запрещён', function (): void { + $dir = testDir(); + + $result = (new ListDirTool(new FileSandbox($dir)))->handle(['path' => '..']); + + assertContains('выходит за пределы', $result); +}); + +// --------------------------------------------------------------------------- +// CSV +// --------------------------------------------------------------------------- + +test('csv_query: фильтр по колонке', function (): void { + $dir = testDir(); + file_put_contents( + $dir . '/people.csv', + "name,city,age\nИван,Тула,30\nМария,Москва,25\nПётр,Тула,41\n" + ); + + $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ + 'path' => 'people.csv', + 'where' => 'city=Тула', + ]); + + assertContains('Иван', $result); + assertContains('Пётр', $result); + assertTrue(!str_contains($result, 'Мария'), 'строка из другого города попала в выборку'); + assertContains('2 из 3 строк', $result); +}); + +test('csv_query: вхождение подстроки и лимит', function (): void { + $dir = testDir(); + file_put_contents($dir . '/people.csv', "name,city\nИван,Тула\nИгорь,Тула\nПётр,Тула\n"); + + $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ + 'path' => 'people.csv', + 'where' => 'name~и', + 'columns' => 'name', + 'limit' => 2, + ]); + + assertContains('2 из 3 строк', $result); + assertTrue(!str_contains($result, 'city'), 'лишняя колонка в выборке'); +}); + +test('csv_query: неизвестная колонка — понятная ошибка', function (): void { + $dir = testDir(); + file_put_contents($dir . '/people.csv', "name,city\nИван,Тула\n"); + + $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ + 'path' => 'people.csv', + 'where' => 'город=Тула', + ]); + + assertContains('Нет колонки', $result); + assertContains('name, city', $result); +}); + +// --------------------------------------------------------------------------- +// Единицы и даты +// --------------------------------------------------------------------------- + +test('convert_units: километры в мили', function (): void { + assertSame('100 km = 62.137119 mi', (new ConvertUnitsTool())->handle([ + 'value' => 100, + 'from' => 'km', + 'to' => 'mi', + ])); +}); + +test('convert_units: температура', function (): void { + $tool = new ConvertUnitsTool(); + + assertSame('0 c = 32 f', $tool->handle(['value' => 0, 'from' => 'c', 'to' => 'f'])); + assertSame('100 c = 373.15 k', $tool->handle(['value' => 100, 'from' => 'c', 'to' => 'k'])); +}); + +test('convert_units: русские названия единиц', function (): void { + // Ответ приходит в канонических кодах, независимо от ввода. + assertSame('5 km = 5000 m', (new ConvertUnitsTool())->handle([ + 'value' => 5, + 'from' => 'км', + 'to' => 'м', + ])); +}); + +test('convert_units: неизвестная единица', function (): void { + $result = (new ConvertUnitsTool())->handle(['value' => 1, 'from' => 'parsec', 'to' => 'm']); + + assertContains('Не знаю единицы', $result); +}); + +test('date_calc: разница между датами', function (): void { + $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'to' => '2026-02-01']); + + assertContains('31 день', $result); +}); + +test('date_calc: дата без времени — это полночь, а не «сейчас»', function (): void { + $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'modifier' => '+1 day']); + + assertContains('2026-01-01 00:00:00', $result); + assertContains('2026-01-02 00:00:00', $result); +}); + +test('date_calc: прибавить интервал', function (): void { + $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'modifier' => '+30 days']); + + assertContains('2026-01-31', $result); +}); + +test('date_calc: без параметров — подсказка', function (): void { + assertContains('Нужен либо to', (new DateCalcTool())->handle([])); +}); + +test('date_calc: плохой часовой пояс', function (): void { + assertContains('Неизвестный часовой пояс', (new DateCalcTool())->handle([ + 'from' => 'now', + 'timezone' => 'Mars/Olympus', + ])); +}); + +// --------------------------------------------------------------------------- +// UUID и хеши +// --------------------------------------------------------------------------- + +test('uuid: формат v4 и уникальность', function (): void { + $tool = new UuidTool(); + $first = $tool->handle([]); + $second = $tool->handle([]); + + assertTrue( + preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $first) === 1, + 'не UUID v4: ' . $first + ); + assertTrue($first !== $second, 'два вызова вернули одинаковый UUID'); +}); + +test('hash_text: известные значения', function (): void { + $tool = new HashTool(); + + assertSame('sha256: ' . hash('sha256', 'привет'), $tool->handle(['text' => 'привет'])); + assertSame('md5: ' . md5('x'), $tool->handle(['text' => 'x', 'algo' => 'md5'])); + assertContains('Неизвестный алгоритм', $tool->handle(['text' => 'x', 'algo' => 'crc32'])); +}); + +// --------------------------------------------------------------------------- +// http_get: защита от SSRF (без сети) +// --------------------------------------------------------------------------- + +test('http_get: localhost запрещён', function (): void { + assertContains('локальному адресу', (new HttpGetTool())->handle(['url' => 'http://localhost/x'])); +}); + +test('http_get: приватные адреса запрещены', function (): void { + $tool = new HttpGetTool(); + + assertContains('приватному адресу', $tool->handle(['url' => 'http://127.0.0.1/x'])); + assertContains('приватному адресу', $tool->handle(['url' => 'http://10.0.0.5/x'])); + assertContains('приватному адресу', $tool->handle(['url' => 'http://192.168.1.10/x'])); +}); + +test('http_get: только http и https', function (): void { + assertContains('только http и https', (new HttpGetTool())->handle(['url' => 'ftp://example.com/x'])); +}); + +// --------------------------------------------------------------------------- + +removeDir(__DIR__ . '/tmp'); echo PHP_EOL . 'пройдено: ' . $passed . ', провалено: ' . $failed . PHP_EOL; diff --git a/tools/ConvertUnitsTool.php b/tools/ConvertUnitsTool.php new file mode 100644 index 0000000..45fba97 --- /dev/null +++ b/tools/ConvertUnitsTool.php @@ -0,0 +1,149 @@ + 0.001, 'cm' => 0.01, 'm' => 1.0, 'km' => 1000.0, + 'in' => 0.0254, 'ft' => 0.3048, 'yd' => 0.9144, 'mi' => 1609.344, + ]; + + /** Килограммы. */ + private const MASS = [ + 'mg' => 0.000001, 'g' => 0.001, 'kg' => 1.0, 't' => 1000.0, + 'oz' => 0.028349523125, 'lb' => 0.45359237, + ]; + + /** Метры в секунду. */ + private const SPEED = [ + 'mps' => 1.0, 'kmh' => 1 / 3.6, 'mph' => 0.44704, 'kn' => 0.514444444, + ]; + + /** Синонимы -> канонический код. */ + private const ALIASES = [ + 'мм' => 'mm', 'см' => 'cm', 'м' => 'm', 'км' => 'km', + 'дюйм' => 'in', 'дюймы' => 'in', 'фут' => 'ft', 'футы' => 'ft', 'ярд' => 'yd', 'миля' => 'mi', 'мили' => 'mi', + 'мг' => 'mg', 'г' => 'g', 'кг' => 'kg', 'т' => 't', 'тонна' => 't', 'тонны' => 't', + 'унция' => 'oz', 'фунт' => 'lb', 'фунты' => 'lb', + 'м/с' => 'mps', 'км/ч' => 'kmh', 'узел' => 'kn', 'узлов' => 'kn', + '°c' => 'c', 'celsius' => 'c', 'цельсий' => 'c', 'градус' => 'c', + '°f' => 'f', 'fahrenheit' => 'f', 'фаренгейт' => 'f', + '°k' => 'k', 'kelvin' => 'k', 'кельвин' => 'k', + 'метр' => 'm', 'метры' => 'm', 'километр' => 'km', 'километры' => 'km', + 'сантиметр' => 'cm', 'сантиметры' => 'cm', 'миллиметр' => 'mm', 'миллиметры' => 'mm', + 'грамм' => 'g', 'граммы' => 'g', 'килограмм' => 'kg', 'килограммы' => 'kg', + ]; + + public function name(): string + { + return 'convert_units'; + } + + public function description(): string + { + return 'Перевести величину между единицами. Температура: c, f, k. ' + . 'Длина: mm, cm, m, km, in, ft, yd, mi. Масса: mg, g, kg, t, oz, lb. ' + . 'Скорость: mps, kmh, mph, kn.'; + } + + public function parameters(): array + { + return [ + 'type' => 'object', + 'properties' => [ + 'value' => ['type' => 'number', 'description' => 'Число для перевода.'], + 'from' => ['type' => 'string', 'description' => 'Исходная единица, например km.'], + 'to' => ['type' => 'string', 'description' => 'Целевая единица, например mi.'], + ], + 'required' => ['value', 'from', 'to'], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $value = $args['value'] ?? null; + + if (!is_numeric($value)) { + return 'value должно быть числом.'; + } + + $from = $this->normalize((string) ($args['from'] ?? '')); + $to = $this->normalize((string) ($args['to'] ?? '')); + + if ($from === '' || $to === '') { + return 'Укажи from и to, например from: km, to: mi.'; + } + + $value = (float) $value; + + $result = $this->convert($value, $from, $to); + + if ($result === null) { + return 'Не знаю единицы "' . $from . '" или "' . $to . '". ' + . 'Доступно: c, f, k, mm, cm, m, km, in, ft, yd, mi, mg, g, kg, t, oz, lb, mps, kmh, mph, kn.'; + } + + return $this->format($value) . ' ' . $from . ' = ' . $this->format($result) . ' ' . $to; + } + + private function convert(float $value, string $from, string $to): ?float + { + // Температура — не масштаб, а сдвиг, поэтому отдельно. + $temperatures = ['c', 'f', 'k']; + + if (in_array($from, $temperatures, true) || in_array($to, $temperatures, true)) { + if (!in_array($from, $temperatures, true) || !in_array($to, $temperatures, true)) { + return null; + } + + $celsius = match ($from) { + 'c' => $value, + 'f' => ($value - 32) * 5 / 9, + 'k' => $value - 273.15, + }; + + return match ($to) { + 'c' => $celsius, + 'f' => $celsius * 9 / 5 + 32, + 'k' => $celsius + 273.15, + }; + } + + foreach ([self::LENGTH, self::MASS, self::SPEED] as $table) { + if (isset($table[$from], $table[$to])) { + return $value * $table[$from] / $table[$to]; + } + } + + return null; + } + + private function normalize(string $unit): string + { + $unit = mb_strtolower(trim($unit)); + + return self::ALIASES[$unit] ?? $unit; + } + + private function format(float $value): string + { + if (abs($value - round($value)) < 1e-9) { + return (string) (int) round($value); + } + + return rtrim(rtrim(number_format($value, 6, '.', ''), '0'), '.'); + } +} diff --git a/tools/CsvQueryTool.php b/tools/CsvQueryTool.php new file mode 100644 index 0000000..9fc3870 --- /dev/null +++ b/tools/CsvQueryTool.php @@ -0,0 +1,268 @@ + 'object', + 'properties' => [ + 'path' => ['type' => 'string', 'description' => 'Путь к CSV относительно корня.'], + 'where' => ['type' => 'string', 'description' => 'Фильтр: city=Тула или name~иван.'], + 'columns' => ['type' => 'string', 'description' => 'Список колонок через запятую.'], + 'limit' => ['type' => 'integer', 'description' => 'Сколько строк, по умолчанию 20, максимум ' . self::MAX_ROWS . '.'], + 'delimiter' => ['type' => 'string', 'description' => 'Разделитель, по умолчанию запятая.'], + ], + 'required' => ['path'], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $path = (string) ($args['path'] ?? ''); + $limit = (int) ($args['limit'] ?? 20); + $delimiter = (string) ($args['delimiter'] ?? ','); + $delimiter = $delimiter !== '' ? $delimiter[0] : ','; + + if ($limit < 1) { + $limit = 20; + } + + $limit = min($limit, self::MAX_ROWS); + + try { + $file = $this->sandbox->resolve($path); + } catch (\RuntimeException $e) { + return $e->getMessage(); + } + + if (!is_file($file)) { + return 'Это не файл: ' . $path; + } + + $size = filesize($file); + + if ($size !== false && $size > self::MAX_BYTES) { + return 'CSV слишком большой: ' . round($size / 1048576, 1) . ' МБ (максимум 5 МБ).'; + } + + $handle = fopen($file, 'rb'); + + if ($handle === false) { + return 'Не удалось открыть файл.'; + } + + $header = fgetcsv($handle, 0, $delimiter); + + if ($header === false || $header === [null] || $header === []) { + fclose($handle); + + return 'Не удалось прочитать заголовок CSV.'; + } + + $header = array_map(static fn ($name): string => trim((string) $name), $header); + + $requested = $this->requestedColumns($header, (string) ($args['columns'] ?? '')); + + if (is_string($requested)) { + fclose($handle); + + return $requested; + } + + $filter = $this->parseWhere($header, (string) ($args['where'] ?? '')); + + if (is_string($filter)) { + fclose($handle); + + return $filter; + } + + $allRows = []; + + while (($row = fgetcsv($handle, 0, $delimiter)) !== false) { + $allRows[] = array_map(static fn ($cell): string => trim((string) $cell), $row); + } + + fclose($handle); + + $total = count($allRows); + $rows = []; + + foreach ($allRows as $row) { + if ($filter !== null && !$this->matches($row, $header, $filter)) { + continue; + } + + $picked = []; + + foreach ($requested as $index) { + $picked[] = $this->cell($row[$index] ?? ''); + } + + $rows[] = $picked; + + if (count($rows) >= $limit) { + break; + } + } + + if ($rows === []) { + return 'Подходящих строк нет (всего строк: ' . $total . ').'; + } + + $table = [array_map(static fn (int $i): string => $header[$i], $requested)]; + $table = array_merge($table, $rows); + + return 'CSV ' . $path . ': ' . count($rows) . ' из ' . $total . " строк\n" . $this->render($table); + } + + /** + * @param list $header + * @return list|string индексы колонок или текст ошибки + */ + private function requestedColumns(array $header, string $columns): array|string + { + if (trim($columns) === '') { + return array_keys($header); + } + + $wanted = array_map('trim', explode(',', $columns)); + $indexes = []; + + foreach ($wanted as $name) { + $index = array_search($name, $header, true); + + if ($index === false) { + return 'Нет колонки "' . $name . '". Есть: ' . implode(', ', $header) . '.'; + } + + $indexes[] = (int) $index; + } + + return $indexes; + } + + /** + * @param list $header + * @return array{index: int, value: string, contains: bool}|string|null + */ + private function parseWhere(array $header, string $where): array|string|null + { + $where = trim($where); + + if ($where === '') { + return null; + } + + if (preg_match('/^([^=~]+)([=~])(.*)$/u', $where, $match) !== 1) { + return 'Фильтр должен быть вида "колонка=значение" или "колонка~значение".'; + } + + $column = trim($match[1]); + $index = array_search($column, $header, true); + + if ($index === false) { + return 'Нет колонки "' . $column . '". Есть: ' . implode(', ', $header) . '.'; + } + + return [ + 'index' => (int) $index, + 'value' => trim($match[3]), + 'contains' => $match[2] === '~', + ]; + } + + /** + * @param list $row + * @param list $header + * @param array{index: int, value: string, contains: bool} $filter + */ + private function matches(array $row, array $header, array $filter): bool + { + $cell = $row[$filter['index']] ?? ''; + + if ($filter['contains']) { + return mb_stripos($cell, $filter['value']) !== false; + } + + return mb_strtolower($cell) === mb_strtolower($filter['value']); + } + + private function cell(string $value): string + { + $value = str_replace(["\r", "\n"], ' ', $value); + + return mb_strlen($value) > self::CELL_MAX + ? mb_substr($value, 0, self::CELL_MAX) . '…' + : $value; + } + + /** + * @param list> $table + */ + private function render(array $table): string + { + $widths = []; + + foreach ($table as $row) { + foreach ($row as $index => $cell) { + $widths[$index] = max($widths[$index] ?? 0, mb_strlen($cell)); + } + } + + $lines = []; + + foreach ($table as $rowIndex => $row) { + $parts = []; + + foreach ($row as $index => $cell) { + $parts[] = str_pad($cell, $widths[$index]); + } + + $lines[] = implode(' | ', $parts); + + if ($rowIndex === 0) { + $lines[] = implode('-+-', array_map( + static fn (int $width): string => str_repeat('-', $width), + $widths + )); + } + } + + return implode("\n", $lines); + } +} diff --git a/tools/DateCalcTool.php b/tools/DateCalcTool.php new file mode 100644 index 0000000..ecb2057 --- /dev/null +++ b/tools/DateCalcTool.php @@ -0,0 +1,142 @@ + 'object', + 'properties' => [ + 'from' => ['type' => 'string', 'description' => 'Начальная дата или now.'], + 'to' => ['type' => 'string', 'description' => 'Конечная дата — если нужна разница.'], + 'modifier' => ['type' => 'string', 'description' => 'Интервал, например +30 days.'], + 'timezone' => ['type' => 'string', 'description' => 'IANA-пояс, по умолчанию UTC.'], + ], + 'required' => [], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $timezone = trim((string) ($args['timezone'] ?? '')); + $timezone = $timezone !== '' ? $timezone : 'UTC'; + + try { + $zone = new \DateTimeZone($timezone); + } catch (\Throwable) { + return 'Неизвестный часовой пояс: ' . $timezone . '.'; + } + + $fromRaw = trim((string) ($args['from'] ?? 'now')); + $toRaw = trim((string) ($args['to'] ?? '')); + $modifier = trim((string) ($args['modifier'] ?? '')); + + $from = $this->parse($fromRaw !== '' ? $fromRaw : 'now', $zone); + + if ($from === null) { + return 'Не понял дату: ' . $fromRaw . '. Пример: 2026-11-12 или now.'; + } + + if ($toRaw !== '') { + $to = $this->parse($toRaw, $zone); + + if ($to === null) { + return 'Не понял дату: ' . $toRaw . '. Пример: 2026-11-12.'; + } + + return $this->diff($from, $to); + } + + if ($modifier !== '') { + $shifted = $from->modify($modifier); + + if ($shifted === false) { + return 'Не понял интервал: ' . $modifier . '. Пример: +30 days.'; + } + + return $from->format('Y-m-d H:i:s T') . ' ' . $modifier . ' = ' + . $shifted->format('Y-m-d H:i:s T'); + } + + return 'Нужен либо to (разница), либо modifier (сдвиг).'; + } + + private function parse(string $value, \DateTimeZone $zone): ?\DateTimeImmutable + { + if (strcasecmp($value, 'now') === 0) { + return new \DateTimeImmutable('now', $zone); + } + + // «!» сбрасывает незаданные части в ноль: без него PHP подставит + // текущее время вместо 00:00:00. + foreach (['!Y-m-d H:i:s', '!Y-m-d\TH:i:s', '!Y-m-d'] as $format) { + $date = \DateTimeImmutable::createFromFormat($format, $value, $zone); + + if ($date !== false) { + return $date; + } + } + + // Естественный язык: «next friday», «tomorrow». + try { + return new \DateTimeImmutable($value, $zone); + } catch (\Throwable) { + return null; + } + } + + private function diff(\DateTimeImmutable $from, \DateTimeImmutable $to): string + { + $interval = $from->diff($to); + $sign = $to < $from ? ' (раньше)' : ''; + + $days = (int) $interval->days; + $hours = (int) $interval->h; + $minutes = (int) $interval->i; + + return $from->format('Y-m-d H:i') . ' → ' . $to->format('Y-m-d H:i') . ': ' + . $days . ' ' . $this->pluralDays($days) . ', ' + . $hours . ' ч ' . $minutes . ' мин' . $sign; + } + + private function pluralDays(int $days): string + { + $mod100 = $days % 100; + $mod10 = $days % 10; + + if ($mod100 >= 11 && $mod100 <= 14) { + return 'дней'; + } + + return match ($mod10) { + 1 => 'день', + 2, 3, 4 => 'дня', + default => 'дней', + }; + } +} diff --git a/tools/FileSandbox.php b/tools/FileSandbox.php new file mode 100644 index 0000000..091146c --- /dev/null +++ b/tools/FileSandbox.php @@ -0,0 +1,100 @@ +root = rtrim($resolved, DIRECTORY_SEPARATOR); + } + + public function root(): string + { + return $this->root; + } + + /** + * Привести относительный путь к абсолютному внутри корня. + * + * @throws \RuntimeException если путь вне корня или (для чтения) не найден + */ + public function resolve(string $path, bool $mustExist = true): string + { + $path = trim($path); + + if ($path === '' || $path === '.') { + 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); + + if ($real === false) { + if ($mustExist) { + throw new \RuntimeException('Путь не найден: ' . $path); + } + + return $candidate; + } + + if ($real !== $this->root && !$this->startsWithRoot($real)) { + throw new \RuntimeException('Путь выходит за пределы разрешённого каталога.'); + } + + return $real; + } + + /** + * Путь для показа пользователю (относительно корня). + */ + public function relative(string $absolute): string + { + if ($absolute === $this->root) { + return '.'; + } + + $prefix = $this->root . DIRECTORY_SEPARATOR; + + if ($this->startsWithRoot($absolute)) { + return str_replace(DIRECTORY_SEPARATOR, '/', substr($absolute, strlen($prefix))); + } + + return $absolute; + } + + private function startsWithRoot(string $path): bool + { + $prefix = $this->root . DIRECTORY_SEPARATOR; + + // На Windows путь регистронезависим, на Unix — нет. + return DIRECTORY_SEPARATOR === '\\' + ? stripos($path, $prefix) === 0 + : str_starts_with($path, $prefix); + } +} diff --git a/tools/HashTool.php b/tools/HashTool.php new file mode 100644 index 0000000..0e403a4 --- /dev/null +++ b/tools/HashTool.php @@ -0,0 +1,58 @@ + 'object', + 'properties' => [ + 'text' => ['type' => 'string', 'description' => 'Текст для хеширования.'], + 'algo' => [ + 'type' => 'string', + 'enum' => self::ALGOS, + 'description' => 'Алгоритм, по умолчанию sha256.', + ], + ], + 'required' => ['text'], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $text = (string) ($args['text'] ?? ''); + $algo = strtolower(trim((string) ($args['algo'] ?? 'sha256'))); + + if ($algo === '') { + $algo = 'sha256'; + } + + if (!in_array($algo, self::ALGOS, true)) { + return 'Неизвестный алгоритм: ' . $algo . '. Доступно: ' . implode(', ', self::ALGOS) . '.'; + } + + return $algo . ': ' . hash($algo, $text); + } +} diff --git a/tools/HttpGetTool.php b/tools/HttpGetTool.php new file mode 100644 index 0000000..eb3938d --- /dev/null +++ b/tools/HttpGetTool.php @@ -0,0 +1,209 @@ + 'object', + 'properties' => [ + 'url' => [ + 'type' => 'string', + 'description' => 'Полный адрес, например https://api.example.com/status.', + ], + 'max_chars' => [ + 'type' => 'integer', + 'description' => 'Сколько символов вернуть, по умолчанию ' . $this->defaultChars . ', максимум 20000.', + ], + ], + 'required' => ['url'], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $url = trim((string) ($args['url'] ?? '')); + $maxChars = (int) ($args['max_chars'] ?? $this->defaultChars); + $maxChars = max(200, min($maxChars, 20000)); + + if ($url === '') { + return 'Не указан URL.'; + } + + try { + $current = $this->normalize($url); + $response = null; + + for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) { + $this->assertPublic($current); + $response = Http::request($current, self::TIMEOUT, false, self::MAX_BYTES); + + $isRedirect = $response['status'] >= 300 && $response['status'] < 400; + + if (!$isRedirect || $response['location'] === null) { + break; + } + + $current = $this->normalize($this->absolute($current, $response['location'])); + } + } catch (\Throwable $e) { + return 'Ошибка: ' . $e->getMessage(); + } + + if ($response === null) { + return 'Не удалось получить ответ.'; + } + + if ($response['status'] >= 400) { + return 'HTTP ' . $response['status'] . ' для ' . $current; + } + + $text = trim($response['body']); + + if ($text === '') { + return 'Пустой ответ (HTTP ' . $response['status'] . ') для ' . $current . '.'; + } + + $truncated = $response['truncated'] || mb_strlen($text) > $maxChars; + $text = mb_substr($text, 0, $maxChars); + + return 'HTTP ' . $response['status'] . ', ' . $current + . ($truncated ? ' (обрезано)' : '') + . ":\n" . $text; + } + + private function normalize(string $url): string + { + $url = trim($url); + + // Схему не подменяем: пусть assertPublic сам скажет, что ftp не годится. + if (preg_match('#^[a-z][a-z0-9+.-]*://#i', $url) === 1) { + return $url; + } + + return 'https://' . ltrim($url, '/'); + } + + private function absolute(string $base, string $location): string + { + if (preg_match('#^https?://#i', $location) === 1) { + return $location; + } + + $parts = parse_url($base); + + if ($parts === false || !isset($parts['scheme'], $parts['host'])) { + throw new \RuntimeException('некорректный адрес редиректа'); + } + + $origin = $parts['scheme'] . '://' . $parts['host'] + . (isset($parts['port']) ? ':' . $parts['port'] : ''); + + if (str_starts_with($location, '//')) { + return $parts['scheme'] . ':' . $location; + } + + if (str_starts_with($location, '/')) { + return $origin . $location; + } + + $dir = rtrim(dirname($parts['path'] ?? '/'), '/'); + + return $origin . $dir . '/' . $location; + } + + private function assertPublic(string $url): void + { + $parts = parse_url($url); + + if ($parts === false || !isset($parts['scheme'], $parts['host'])) { + throw new \RuntimeException('некорректный URL'); + } + + $scheme = strtolower((string) $parts['scheme']); + + if (!in_array($scheme, ['http', 'https'], true)) { + throw new \RuntimeException('разрешены только http и https'); + } + + $host = strtolower((string) $parts['host']); + + if ($host === 'localhost' || str_ends_with($host, '.local') || str_contains($host, 'metadata')) { + throw new \RuntimeException('запрос к локальному адресу запрещён'); + } + + $ips = []; + + if (filter_var($host, FILTER_VALIDATE_IP) !== false) { + $ips[] = $host; + } else { + $resolved = @gethostbynamel($host); + + if ($resolved === false || $resolved === []) { + throw new \RuntimeException('не удалось разрешить хост: ' . $host); + } + + $ips = $resolved; + } + + foreach ($ips as $ip) { + if (!$this->isPublicIp($ip)) { + throw new \RuntimeException('запрос к приватному адресу запрещён: ' . $host); + } + } + } + + private function isPublicIp(string $ip): bool + { + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { + return false; + } + + // 100.64.0.0/10 (CGNAT) не покрывается флагами PHP. + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) { + $long = ip2long($ip); + $cgnat = ip2long('100.64.0.0'); + + if ($long !== false && $cgnat !== false && ($long & 0xFFC00000) === ($cgnat & 0xFFC00000)) { + return false; + } + } + + return true; + } +} diff --git a/tools/ListDirTool.php b/tools/ListDirTool.php new file mode 100644 index 0000000..be30d52 --- /dev/null +++ b/tools/ListDirTool.php @@ -0,0 +1,114 @@ + 'object', + 'properties' => [ + 'path' => [ + 'type' => 'string', + 'description' => 'Каталог относительно корня. По умолчанию корень.', + ], + ], + 'required' => [], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $path = (string) ($args['path'] ?? ''); + + try { + $dir = $this->sandbox->resolve($path); + } catch (\RuntimeException $e) { + return $e->getMessage(); + } + + if (!is_dir($dir)) { + return 'Это не каталог: ' . $path; + } + + $entries = @scandir($dir); + + if ($entries === false) { + return 'Не удалось прочитать каталог.'; + } + + $entries = array_values(array_filter( + $entries, + static fn (string $name): bool => $name !== '.' && $name !== '..' + )); + + sort($entries); + + $dirs = []; + $files = []; + + foreach ($entries as $name) { + $full = $dir . DIRECTORY_SEPARATOR . $name; + + if (is_dir($full)) { + $dirs[] = $name . '/'; + + continue; + } + + $size = @filesize($full); + $files[] = $name . ' (' . $this->human($size === false ? 0 : $size) . ')'; + } + + $all = array_merge($dirs, $files); + $shown = array_slice($all, 0, self::MAX_ENTRIES); + $title = $this->sandbox->relative($dir); + + $text = 'Каталог ' . $title . ': ' . count($all) . " объектов\n" . implode("\n", $shown); + + if (count($all) > count($shown)) { + $text .= "\n…и ещё " . (count($all) - count($shown)); + } + + return $text; + } + + 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/ReadFileTool.php b/tools/ReadFileTool.php new file mode 100644 index 0000000..e21c363 --- /dev/null +++ b/tools/ReadFileTool.php @@ -0,0 +1,144 @@ + 'object', + 'properties' => [ + 'path' => [ + 'type' => 'string', + 'description' => 'Путь к файлу относительно корня, например logs/bot.log.', + ], + 'offset' => [ + 'type' => 'integer', + 'description' => 'С какой строки начать (с нуля). По умолчанию 0.', + ], + 'limit' => [ + 'type' => 'integer', + 'description' => 'Сколько строк вернуть, максимум ' . self::MAX_LINES . '. По умолчанию 200.', + ], + ], + 'required' => ['path'], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $path = (string) ($args['path'] ?? ''); + $offset = max(0, (int) ($args['offset'] ?? 0)); + $limit = (int) ($args['limit'] ?? 200); + + if ($limit < 1) { + $limit = 200; + } + + $limit = min($limit, self::MAX_LINES); + + try { + $file = $this->sandbox->resolve($path); + } catch (\RuntimeException $e) { + return $e->getMessage(); + } + + if (!is_file($file)) { + return 'Это не файл: ' . $path; + } + + $size = filesize($file); + + if ($size === false) { + return 'Не удалось узнать размер файла.'; + } + + if ($size > 10 * 1024 * 1024) { + return 'Файл слишком большой (' . $this->human($size) . '). Читай частями через offset и limit.'; + } + + $handle = fopen($file, 'rb'); + + if ($handle === false) { + return 'Не удалось открыть файл.'; + } + + $first = fread($handle, 4096); + fclose($handle); + + if ($first === false) { + return 'Не удалось прочитать файл.'; + } + + if ($first !== '' && !mb_check_encoding($first, 'UTF-8')) { + return 'Файл бинарный (' . $this->human($size) . '), не читаю.'; + } + + $lines = file($file, FILE_IGNORE_NEW_LINES); + + if ($lines === false) { + return 'Не удалось прочитать файл.'; + } + + $total = count($lines); + $slice = array_slice($lines, $offset, $limit); + + if ($slice === []) { + return 'В файле ' . $total . ' строк — диапазон пуст.'; + } + + $text = implode("\n", $slice); + + if (strlen($text) > self::MAX_BYTES) { + $text = mb_strcut($text, 0, self::MAX_BYTES); + } + + $from = $offset + 1; + $to = $offset + count($slice); + + return 'Файл ' . $path . ', строки ' . $from . '–' . $to . ' из ' . $total . ":\n" . $text; + } + + 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/UuidTool.php b/tools/UuidTool.php new file mode 100644 index 0000000..5318064 --- /dev/null +++ b/tools/UuidTool.php @@ -0,0 +1,53 @@ + 'object', + 'properties' => (object) [], + 'required' => [], + 'additionalProperties' => false, + ]; + } + + public function handle(array $args): string + { + $data = random_bytes(16); + + // Версия 4 и вариант RFC 4122. + $data[6] = chr((ord($data[6]) & 0x0f) | 0x40); + $data[8] = chr((ord($data[8]) & 0x3f) | 0x80); + + $hex = bin2hex($data); + + return sprintf( + '%s-%s-%s-%s-%s', + substr($hex, 0, 8), + substr($hex, 8, 4), + substr($hex, 12, 4), + substr($hex, 16, 4), + substr($hex, 20, 12) + ); + } +}